1 | import type {CodeKeywordDefinition, KeywordCxt, KeywordErrorDefinition, ErrorObject} from "ajv"
|
2 | import {_, str, and} from "ajv/dist/compile/codegen"
|
3 | import {usePattern} from "./_util"
|
4 |
|
5 | export type PatternRequiredError = ErrorObject<"patternRequired", {missingPattern: string}>
|
6 |
|
7 | const error: KeywordErrorDefinition = {
|
8 | message: ({params: {missingPattern}}) =>
|
9 | str`should have property matching pattern '${missingPattern}'`,
|
10 | params: ({params: {missingPattern}}) => _`{missingPattern: ${missingPattern}}`,
|
11 | }
|
12 |
|
13 | export default function getDef(): CodeKeywordDefinition {
|
14 | return {
|
15 | keyword: "patternRequired",
|
16 | type: "object",
|
17 | schemaType: "array",
|
18 | error,
|
19 | code(cxt: KeywordCxt) {
|
20 | const {gen, schema, data} = cxt
|
21 | if (schema.length === 0) return
|
22 | const valid = gen.let("valid", true)
|
23 | for (const pat of schema) validateProperties(pat)
|
24 |
|
25 | function validateProperties(pattern: string): void {
|
26 | const matched = gen.let("matched", false)
|
27 |
|
28 | gen.forIn("key", data, (key) => {
|
29 | gen.assign(matched, _`${usePattern(cxt, pattern)}.test(${key})`)
|
30 | gen.if(matched, () => gen.break())
|
31 | })
|
32 |
|
33 | cxt.setParams({missingPattern: pattern})
|
34 | gen.assign(valid, and(valid, matched))
|
35 | cxt.pass(valid)
|
36 | }
|
37 | },
|
38 | metaSchema: {
|
39 | type: "array",
|
40 | items: {type: "string", format: "regex"},
|
41 | uniqueItems: true,
|
42 | },
|
43 | }
|
44 | }
|
45 |
|
46 | module.exports = getDef
|