1.0.1 • Published 6 years ago
jamin-json-schema-validation v1.0.1
jamin-json-schema-validation
This JSON schema validator allows developers to run a function on each property in a JSON object and test if the JSON is what you expected.
Installing
npm install jamin-json-schema-validation --save
Use
const SchemaValidator = require("jamin-json-schema-validation"),
validateSchema = SchemaValidator.validateSchema,
schemaRejection = SchemaValidator.schemaRejection;
let data = {
name: "ben",
color: "blue",
age: 17
}
let schema = {
name: (name) => {
if (name.length > 50) {
throw schemaRejection("Exceeded maximum amount of characters for your name.")
}
},
color: null, //use null if you don't need to validate with a function
age: (age) => {
if(age < 18){
throw schemaRejection("You are too young.")
}
}
}
validateSchema(data, schema)
.then((validSchema) => {
console.log("VALID SCHEMA: ", validSchema)
})
.catch((err) => {
console.log("INVALID SCHEMA: ", err)
})
Suggested use with Express
app.post("/route", function (req, res) {
let body = req.body
/*
body = {
name: "ben",
color: "blue",
age: 17
}
*/
validateSchema(body, schema)
.then((validSchema) => {
//validSchema == body
//Now:
//Perform ops on database...
})
.catch((err) => {
//err is an object in the form {message: "", key: ""}
//key may be undefined if the error was not found due to a custom thrown schemaRejection
if(key === "age"){
res.send(err.message)
//sends - You are too young.
}
})
})
NOTE: The example with Express uses a body parser for the post data
npm install body-parser --save
Then
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))