I have an express app, which has a post method(the post is a json type):
server.js(simplified version):
app.post('/listener/v1/event/', function(req, res) {
.
.
var event = req.body;
var validator = require("./validator");
validator.validate(event);
}
validator.js contains the validation for the json:
var jsonschemavalidate = require("json-schema");
var basicSchema = require('fs').readFileSync('./schema.json', 'utf8');
exports.validate = function (event) {
console.log(jsonschemavalidate.validate(event, basicSchema).errors);
}
The schema.json:
{
name : "test",
type : 'object',
properties : {
event_id : { type : 'string' },
timestamp : { type : 'string' }
}
}
For the input I use curl:
curl -i -X POST -H 'Content-Type: application/json' -d '{"event_id": "NedaleGassss", "timestamp": "a2009321"}' http://localhost:3000/listener/v1/event/
The output is as follows:
[ { property: '',
message: 'Invalid schema/property definition {\n name : "test",\n type : "object",\n additionalProperties : false,\n properties :\n {\n event_id : { type : "string" },\n timestamp \t: { type : "string" }\n }\n}' } ]
Your schema is invalid, as the error says. The schema should also be valid JSON, so properties and strings should be double quoted:
{
"name" : "test",
"type" : "object",
"properties" : {
"event_id" : { "type" : "string" },
"timestamp" : { "type" : "string" }
}
}
This should do the trick, (unless you figured it out already in the past year)
And also:
var basicSchema = require('fs').readFileSync('./schema.json', 'utf8');
could probably be replaced by:
var basicSchema = require('./schema');