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

Make validate side-effect free / handle Immutable data #559

Closed
smeijer opened this issue Sep 8, 2017 · 1 comment
Closed

Make validate side-effect free / handle Immutable data #559

smeijer opened this issue Sep 8, 2017 · 1 comment

Comments

@smeijer
Copy link

smeijer commented Sep 8, 2017

What version of Ajv are you using?
5.2.2, latest at the moment of writing

The problem you want to solve
I don't want to modify properties in a different scope, to prevent unwanted side-effects. Side-effects are
often responsible for causing bugs.

schema:

import Ajv from 'ajv';
import deepFreeze from 'deep-freeze';

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

var data = deepFreeze({ "foo": 1 });

issue:

var validate = ajv.compile(schema);
var isValid = validate(data); // THROW: ​​Can't add property bar, object is not extensible​​

// expected results without `deepFreeze`
console.log(validate.errors); // null
console.log(isValid); // true
console.log(data); // { foo: 1, bar: 'baz' }

What do you think is the correct solution to the problem?
The correct solution would be to make ajv behave side-effect free. Make the validate function side-effect free / immutable, don't reassign arguments there.

var validate = ajv.compile(schema);
var result = validate(data);

console.log(result.errors); // null
console.log(result.isValid); // true
console.log(result.data); // { foo: 1, bar: 'baz' }
console.log(data); // { foo: 1 }

If validate does not modify data, be sure that result.data === data. When it does modify data (because of applying defaults, or Coercing data types), result.data !== data

Will you be able to implement it
At this moment probably not, because of lack of time. Maybe in the future, but don't hold your breath.

@epoberezkin
Copy link
Member

duplicate of #549

Please comment there.

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

No branches or pull requests

2 participants