/
undefinedAsNull.js
39 lines (34 loc) · 990 Bytes
/
undefinedAsNull.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/** @typedef {import("ajv").default} Ajv */
/** @typedef {import("ajv").SchemaValidateFunction} SchemaValidateFunction */
/** @typedef {import("ajv").AnySchemaObject} AnySchemaObject */
/** @typedef {import("ajv").ValidateFunction} ValidateFunction */
/**
*
* @param {Ajv} ajv
* @returns {Ajv}
*/
function addUndefinedAsNullKeyword(ajv) {
ajv.addKeyword({
keyword: "undefinedAsNull",
before: "enum",
modifying: true,
/** @type {SchemaValidateFunction} */
validate(kwVal, data, metadata, dataCxt) {
if (
kwVal &&
dataCxt &&
metadata &&
typeof metadata.enum !== "undefined"
) {
const idx = dataCxt.parentDataProperty;
if (typeof dataCxt.parentData[idx] === "undefined") {
// eslint-disable-next-line no-param-reassign
dataCxt.parentData[dataCxt.parentDataProperty] = null;
}
}
return true;
},
});
return ajv;
}
export default addUndefinedAsNullKeyword;