limitLength.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
  2. import type KeywordCxt from "../../compile/context"
  3. import {_, str, operators} from "../../compile/codegen"
  4. import ucs2length from "../../compile/ucs2length"
  5. const error: KeywordErrorDefinition = {
  6. message({keyword, schemaCode}) {
  7. const comp = keyword === "maxLength" ? "more" : "fewer"
  8. return str`should NOT have ${comp} than ${schemaCode} characters`
  9. },
  10. params: ({schemaCode}) => _`{limit: ${schemaCode}}`,
  11. }
  12. const def: CodeKeywordDefinition = {
  13. keyword: ["maxLength", "minLength"],
  14. type: "string",
  15. schemaType: "number",
  16. $data: true,
  17. error,
  18. code(cxt: KeywordCxt) {
  19. const {keyword, data, schemaCode, it} = cxt
  20. const op = keyword === "maxLength" ? operators.GT : operators.LT
  21. let len
  22. if (it.opts.unicode === false) {
  23. len = _`${data}.length`
  24. } else {
  25. const u2l = cxt.gen.scopeValue("func", {
  26. ref: ucs2length,
  27. code: _`require("ajv/dist/compile/ucs2length").default`,
  28. })
  29. len = _`${u2l}(${data})`
  30. }
  31. cxt.fail$data(_`${len} ${op} ${schemaCode}`)
  32. },
  33. }
  34. export default def