const.ts 807 B

123456789101112131415161718192021222324252627
  1. import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
  2. import type KeywordCxt from "../../compile/context"
  3. import {_} from "../../compile/codegen"
  4. import equal = require("fast-deep-equal")
  5. export type ConstError = ErrorObject<"const", {allowedValue: any}>
  6. const error: KeywordErrorDefinition = {
  7. message: "should be equal to constant",
  8. params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`,
  9. }
  10. const def: CodeKeywordDefinition = {
  11. keyword: "const",
  12. $data: true,
  13. error,
  14. code(cxt: KeywordCxt) {
  15. const eql = cxt.gen.scopeValue("func", {
  16. ref: equal,
  17. code: _`require("ajv/dist/compile/equal")`,
  18. })
  19. // TODO optimize for scalar values in schema
  20. cxt.fail$data(_`!${eql}(${cxt.data}, ${cxt.schemaCode})`)
  21. },
  22. }
  23. export default def