ajv-validator/ajv

Non-mutating useDefaults option

danny-andrews opened this issue · 2 comments

What version of Ajv you are you using?
5.2.2

What problem do you want to solve?
I want a non-mutating version of the useDefaults option.

What do you think is the correct solution to problem?
I think that instead of mutating the passed in data, we could set a property on the ajv object with the values, similar to how we do it with errors. Example:

var ajv = new Ajv({ useDefaults: true });
var schema = {
  "type": "object",
  "properties": {
    "foo": { "type": "number" },
    "bar": { "type": "string", "default": "baz" }
  },
  "required": [ "foo", "bar" ]
};

var data = { "foo": 1 };

var validate = ajv.compile(schema);

console.log(validate(data)); // true
console.log(data); // { "foo": 1 } (unchanged)
console.log(ajv.result); // { "foo": 1, "bar": "baz" }

Note: this technique could be applied to filtering and coercing data types as well.

Will you be able to implement it?
Sure thing. With some help understanding doT and why it's used for source code.

@danny-andrews given that Ajv is not limited to validating JSON data making defaults etc. mutating is a conscious decision.

If you have JSON data all that is required to preserve the original in your code is this:

let dataCopy = JSON.parse(JSON.stringify(data));
const valid = ajv.validate(schema, dataCopy);

Returning changed data as a separate object requires deep-cloning of the data-structure that is not possible in JavaScript in general case, without restricting what this data can be.

Thanks for the quick reply! That makes sense. Cheers!