ref.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.hasRef = void 0;
  4. const compile_1 = require("../../compile");
  5. const codegen_1 = require("../../compile/codegen");
  6. const error_classes_1 = require("../../compile/error_classes");
  7. const names_1 = require("../../compile/names");
  8. const ref_1 = require("../core/ref");
  9. const metadata_1 = require("./metadata");
  10. const def = {
  11. keyword: "ref",
  12. schemaType: "string",
  13. code(cxt) {
  14. metadata_1.checkMetadata(cxt);
  15. const { gen, data, schema: ref, parentSchema, it } = cxt;
  16. const { schemaEnv: { root }, } = it;
  17. const valid = gen.name("valid");
  18. if (parentSchema.nullable) {
  19. gen.var(valid, codegen_1._ `${data} === null`);
  20. gen.if(codegen_1.not(valid), validateJtdRef);
  21. }
  22. else {
  23. gen.var(valid, false);
  24. validateJtdRef();
  25. }
  26. cxt.ok(valid);
  27. function validateJtdRef() {
  28. var _a;
  29. const refSchema = (_a = root.schema.definitions) === null || _a === void 0 ? void 0 : _a[ref];
  30. if (!refSchema)
  31. throw new error_classes_1.MissingRefError("", ref, `No definition ${ref}`);
  32. if (hasRef(refSchema) || !it.opts.inlineRefs)
  33. callValidate(refSchema);
  34. else
  35. inlineRefSchema(refSchema);
  36. }
  37. function callValidate(schema) {
  38. const sch = compile_1.compileSchema.call(it.self, new compile_1.SchemaEnv({ schema, root }));
  39. const v = ref_1.getValidate(cxt, sch);
  40. const errsCount = gen.const("_errs", names_1.default.errors);
  41. ref_1.callRef(cxt, v, sch, sch.$async);
  42. gen.assign(valid, codegen_1._ `${errsCount} === ${names_1.default.errors}`);
  43. }
  44. function inlineRefSchema(schema) {
  45. const schName = gen.scopeValue("schema", it.opts.code.source === true ? { ref: schema, code: codegen_1.stringify(schema) } : { ref: schema });
  46. cxt.subschema({
  47. schema,
  48. dataTypes: [],
  49. schemaPath: codegen_1.nil,
  50. topSchemaRef: schName,
  51. errSchemaPath: `/definitions/${ref}`,
  52. }, valid);
  53. }
  54. },
  55. };
  56. function hasRef(schema) {
  57. for (const key in schema) {
  58. let sch;
  59. if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch)))
  60. return true;
  61. }
  62. return false;
  63. }
  64. exports.hasRef = hasRef;
  65. exports.default = def;
  66. //# sourceMappingURL=ref.js.map