MongoDB error parse

node v7.10.1
version: 1.1.0
endpointsharetweet
const R = require('ramda'); // Request data ... const error = { "errors": { "code": { "message":"not found on field code.", "name":"ValidatorError", "properties": { "path": "code", "message": "not found on field code.", "type":"user defined", "value":"321564" }, "kind": "user defined","path":"code","value":"321564"} }, "message":"Generic validation failed","name":"ValidationError" }; const resp = { response: { status: 400, data: error } }; // Resolving module ... function execute() { // Pickup errors const mapError = (it) => ({ field: it[0], message: it[1].message }); const pickErrors = R.path(['response', 'data', 'errors']); const getErrors = R.pipe(pickErrors, R.toPairs, R.map(mapError), R.objOf('errors')); // Get generic message const messageLens = R.lensProp('message'); const pickMessage = R.path(['response', 'data', 'message']); const setMessage = R.lift(R.set(messageLens))(pickMessage, R.identity); const getMessage = R.pipe(setMessage, R.pick(['message'])); return R.converge(R.merge, [getErrors, getMessage]); } function match() { return R.pathEq(['response', 'status'], 400); }
// Resolve response const resolve = R.cond([ [R.call(match), R.call(execute)], [R.T, R.pipe(R.prop('statusText'), R.objOf('message'))], ]); const resolved = resolve(resp);
// Assert data const Ajv = require('ajv'); const assert = require('assert') const ajv = new Ajv(); const schema = { "type": "object", "required": ["errors"], "additionalProperties": false, "properties": { "message": { "type": "string", }, "errors": { "type": "array", "additionalProperties": false, "items": { "type": "object", "required": ["field"], "properties" : { "message" : { "type" : "string" }, "field" : { "type" : "string" } }, }, }, } }; var valid = ajv.validate(schema, resolved); assert(valid, ajv.errorsText()); console.info('Everything OK!');
Loading…

no comments

    sign in to comment