Last active
January 30, 2018 13:59
-
-
Save vnglst/6a4b7707ba0eff1c47883502e1747377 to your computer and use it in GitHub Desktop.
JSON Schema function validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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