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

Add async schema validation support #159

Merged
merged 5 commits into from
May 2, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions src/services/validate-schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,40 @@ export default function (schema, ajvOrAjv, options = { allErrors: true }) {
let errorMessages = null;
let invalid = false;

if (schema.$async) {
return Promise.all(itemsArray.map((item, index) => {
return validate(item)
.catch(err => {
if (!(err instanceof ajv.constructor.ValidationError)) throw err;

invalid = true;

addErrors(err.errors, index);
});
})).then(() => {
if (invalid) {
throw new errors.BadRequest('Invalid schema', { errors: errorMessages });
}
});
}

itemsArray.forEach((item, index) => {
if (!validate(item)) {
invalid = true;

validate.errors.forEach(ajvError => {
errorMessages = addNewError(errorMessages, ajvError, itemsLen, index);
});
addErrors(validate.errors, index);
}
});
});

if (invalid) {
throw new errors.BadRequest('Invalid schema', { errors: errorMessages });
}

function addErrors (errors, index) {
errors.forEach(ajvError => {
errorMessages = addNewError(errorMessages, ajvError, itemsLen, index);
});
}
};
}

Expand Down
256 changes: 186 additions & 70 deletions test/services/validate-schema.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ describe('services validateSchema', () => {
let hookBeforeArrayForAjvInstance;
let schema;
let schemaForAjvInstance;
let asyncSchema;
let ajvAsync;

beforeEach(() => {
hookBefore = {
Expand Down Expand Up @@ -56,82 +58,196 @@ describe('services validateSchema', () => {
};
});

it('works with valid single item', () => {
validateSchema(schema, Ajv)(hookBefore);
});

it('works with array of valid items', () => {
validateSchema(schema, Ajv)(hookBeforeArray);
});

it('works with valid single item when ajv instance is passed', () => {
validateSchema(schemaForAjvInstance, ajv)(hookBefore);
});

it('works with array of valid items when ajv instance is passed', () => {
validateSchema(schemaForAjvInstance, ajv)(hookBeforeArrayForAjvInstance);
});

it('fails with invalid single item', () => {
hookBefore.data = { first: 1 };

try {
describe('Sync validation', () => {
beforeEach(() => {
schema = {
'properties': {
'first': { 'type': 'string' },
'last': { 'type': 'string' }
},
'required': ['first', 'last']
};
});

it('works with valid single item', () => {
validateSchema(schema, Ajv)(hookBefore);
assert.fail(true, false, 'test succeeds unexpectedly');
} catch (err) {
assert.deepEqual(err.errors, [
'\'first\' should be string',
'should have required property \'last\''
]);
}
});
});

it('fails with invalid single item when ajv instance is passed', () => {
hookBefore.data = { first: 'Jane' };

try {
it('works with array of valid items', () => {
validateSchema(schema, Ajv)(hookBeforeArray);
});

it('works with valid single item when ajv instance is passed', () => {
validateSchema(schemaForAjvInstance, ajv)(hookBefore);
assert.fail(true, false, 'test succeeds unexpectedly');
} catch (err) {
console.log(err.errors);
assert.deepEqual(err.errors, [
'\'first\' should match format "startWithJo"',
'should have required property \'last\''
]);
}
});

it('works with array of valid items when ajv instance is passed', () => {
validateSchema(schemaForAjvInstance, ajv)(hookBeforeArrayForAjvInstance);
});


it('fails with in valid single item', () => {
hookBefore.data = { first: 1 };

try {
validateSchema(schema, Ajv)(hookBefore);
assert.fail(true, false, 'test succeeds unexpectedly');
} catch (err) {
assert.deepEqual(err.errors, [
'\'first\' should be string',
'should have required property \'last\''
]);
}
});

it('fails with array of invalid items', () => {
hookBeforeArray.data[0] = { first: 1 };
delete hookBeforeArray.data[2].last;

try {
validateSchema(schema, Ajv)(hookBeforeArray);
assert.fail(true, false, 'test succeeds unexpectedly');
} catch (err) {
assert.deepEqual(err.errors, [
"'in row 1 of 3, first' should be string",
"in row 1 of 3, should have required property 'last'",
"in row 3 of 3, should have required property 'last'"
]);
}
});
it('fails with invalid single item when ajv instance is passed', () => {
hookBefore.data = { first: 'Jane' };

try {
validateSchema(schemaForAjvInstance, ajv)(hookBefore);
assert.fail(true, false, 'test succeeds unexpectedly');
} catch (err) {
console.log(err.errors);
assert.deepEqual(err.errors, [
'\'first\' should match format "startWithJo"',
'should have required property \'last\''
]);
}
});

it('fails with array of invalid items when ajv instance is passed', () => {
hookBeforeArray.data[0] = { first: 'Jane' };
delete hookBeforeArray.data[2].last;

try {
validateSchema(schemaForAjvInstance, ajv)(hookBeforeArray);
assert.fail(true, false, 'test succeeds unexpectedly');
} catch (err) {
console.log(err.errors);
assert.deepEqual(err.errors, [
"'in row 1 of 3, first' should match format \"startWithJo\"",
"in row 1 of 3, should have required property 'last'",
"'in row 2 of 3, first' should match format \"startWithJo\"",
"in row 3 of 3, should have required property 'last'"
]);
}
});
});

it('fails with array of invalid items', () => {
hookBeforeArray.data[0] = { first: 1 };
delete hookBeforeArray.data[2].last;

try {
validateSchema(schema, Ajv)(hookBeforeArray);
assert.fail(true, false, 'test succeeds unexpectedly');
} catch (err) {
assert.deepEqual(err.errors, [
"'in row 1 of 3, first' should be string",
"in row 1 of 3, should have required property 'last'",
"in row 3 of 3, should have required property 'last'"
]);
}
});

it('fails with array of invalid items when ajv instance is passed', () => {
hookBeforeArray.data[0] = { first: 'Jane' };
delete hookBeforeArray.data[2].last;

try {
validateSchema(schemaForAjvInstance, ajv)(hookBeforeArray);
assert.fail(true, false, 'test succeeds unexpectedly');
} catch (err) {
console.log(err.errors);
assert.deepEqual(err.errors, [
"'in row 1 of 3, first' should match format \"startWithJo\"",
"in row 1 of 3, should have required property 'last'",
"'in row 2 of 3, first' should match format \"startWithJo\"",
"in row 3 of 3, should have required property 'last'"
]);
}
describe('Async validation', () => {
before(() => {
ajvAsync = new Ajv({ allErrors: true });

ajvAsync.addKeyword('equalsDoe', {
async: true,
schema: false,
validate: (item) => new Promise((resolve, reject) => {
setTimeout(() => {
item === 'Doe'
? resolve(true)
: reject(new Ajv.ValidationError([{message: 'should be Doe'}]));
}, 50);
})
});

ajvAsync.addFormat('3or4chars', {
async: true,
validate: (item) => new Promise((resolve, reject) => {
setTimeout(() => {
(item.length === 3 || item.length === 4)
? resolve(true)
: resolve(false);
}, 50);
})
});
});

beforeEach(() => {
asyncSchema = {
'$async': true,
'properties': {
'first': {
'type': 'string',
'format': '3or4chars'
},
'last': {
'type': 'string',
'equalsDoe': true
}
},
'required': ['first', 'last']
};
});

it('works with valid single item', (next) => {
validateSchema(asyncSchema, ajvAsync)(hookBefore)
.then(() => {
next();
})
.catch((err) => {
console.log(err);
assert.fail(true, false, 'test fails unexpectedly');
});
});

it('works with array of valid items', (next) => {
validateSchema(asyncSchema, ajvAsync)(hookBeforeArray)
.then(() => {
next();
})
.catch(() => {
assert.fail(true, false, 'test fails unexpectedly');
});
});

it('fails with in valid single item', (next) => {
hookBefore.data = { first: '1' };

validateSchema(asyncSchema, ajvAsync)(hookBefore)
.then(() => {
assert.fail(true, false, 'test succeeds unexpectedly');
})
.catch((err) => {
assert.deepEqual(err.errors, [
'\'first\' should match format "3or4chars"',
'should have required property \'last\''
]);
next();
});
});

it('fails with array of invalid items', (next) => {
hookBeforeArray.data[0].last = 'not Doe';
delete hookBeforeArray.data[2].last;

validateSchema(asyncSchema, ajvAsync)(hookBeforeArray)
.then(() => {
assert.fail(true, false, 'test succeeds unexpectedly');
})
.catch((err) => {
assert.deepEqual(err.errors, [
'in row 3 of 3, should have required property \'last\'',
'\'in row 1 of 3, last\' should be Doe'
]);
next();
});
});
});
});