Skip to content

Instantly share code, notes, and snippets.

@vnglst
Last active January 30, 2018 13:59
Show Gist options
  • Save vnglst/6a4b7707ba0eff1c47883502e1747377 to your computer and use it in GitHub Desktop.
Save vnglst/6a4b7707ba0eff1c47883502e1747377 to your computer and use it in GitHub Desktop.
JSON Schema function validation
const api = {};
const ajv = new Ajv({
coerceTypes: true,
useDefaults: true,
allErrors: true,
});
api.api = (schema, handler) => {
const validator = ajv.compile(schema);
return (event, callback) => {
const data = event.data;
const valid = validator(data);
if (!valid) {
// callback or promise
if (!callback) {
return Bluebird.reject(new errors.INVALID_DATA(validator.errors));
}
return callback(new errors.INVALID_DATA(validator.errors));
}
// callback or promise
if (!callback) {
return Bluebird.promisify(handler)(event);
}
return handler(event, callback);
};
};
fnChecker = (schema, fn) => {
let _schema = schemas[schema];
return function (...args) {
if (schema.validate(args)) {
return fn.apply(fn, args);
}
throw new SchemaValidationError(schema.errors);
}
}
const schemas = {
'callUser': {
...
}
};
const callUser = createRemoteUserApiMethod('callUser', (name, language) => {
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment