Implement Keyword lifecycle methods
mainKeywords can implement several methods to control schema processing:
parse: Executed at compile time. Often used to compile sub-schemas and attach them to the parent node.resolve: Returns a child schema for a specific key or index (used for traversing properties or items).reduce: Replaces a JSON Schema keyword with a simpler, static schema based on the current data (e.g., narrowing atypekeyword).validate: The core logic that checks if the data conforms to the keyword's constraints.
/* Example: parse method */
export const notKeyword: Keyword = {
id: "not",
keyword: "not",
parse: (node: SchemaNode) => {
const { schema, evaluationPath, schemaLocation } = node;
if (schema.not != null) {
node.not = node.compileSchema(schema.not, `${evaluationPath}/not`, `${schemaLocation}/not`);
}
}
};
/* Example: resolve method */
export const propertiesKeyword: Keyword = {
id: "property",
keyword: "properties",
parse: parseProperties,
addResolve: (node: SchemaNode) => node.properties != null,
resolve: ({ node, key }) => node.properties?.[key]
};
/* Example: reduce method */
export const typeKeyword: Keyword = {
id: "type",
keyword: "type",
addReduce: (node) => Array.isArray(node.schema.type),
reduce: ( { node, pointer, data } ) => {
const dataType = getJsonSchemaType(data, node.schema.type);
if (dataType !== "undefined" && Array.isArray(node.schema.type) && node.schema.type.includes(dataType)) {
return node.compileSchema({ ...node.schema, pointer, type: dataType }, node.evaluationPath);
}
return undefined;
},
addValidate: ({ schema }) => schema.type != null,
validate: validateType
};