Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Non-mutating useDefaults option #549

Closed
danny-andrews opened this issue Aug 16, 2017 · 2 comments
Closed

Non-mutating useDefaults option #549

danny-andrews opened this issue Aug 16, 2017 · 2 comments
Labels

Comments

@danny-andrews
Copy link

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.

@epoberezkin
Copy link
Member

@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.

@danny-andrews
Copy link
Author

danny-andrews commented Aug 16, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

2 participants