const validate = (json) => { const v = new Validator(); const list = fileReader.readAsJson(json); const errors = []; for (const l in list) { const error = v.validate(list[l], schema) .errors.map(e => `Item: ${e.instance} - ${e.stack}`); if (Object.keys(list[l]).length !== 8) { errors.push(`Item: ${l} - Don't have the correct number of attributes.`); } errors.push(error); } const errorsFlattened = errors.reduce((a, b) => a.concat(b), []); if (errorsFlattened.length > 0) { console.log('The unified list you provided has errors:'); errorsFlattened.forEach(e => { console.error(e); }); } }
/** * Update a single thing * @param {String} name - the name of the Thing to update */ async function updateThing(request, response, next) { const { name } = request.params; const validation = validate(request.body, thingUpdateSchema); if (!validation.valid) { return next( new APIError( 400, "Bad Request", validation.errors.map(e => e.stack).join(". ") ) ); } try { const thing = await Thing.updateThing(name, request.body); return response.json(thing); } catch (err) { return next(err); } }
/** * Validate the POST request body and create a new Thing */ async function createThing(request, response, next) { const validation = validate(request.body, thingNewSchema); if (!validation.valid) { return next( new APIError( 400, "Bad Request", validation.errors.map(e => e.stack).join(". ") ) ); } try { const newThing = await Thing.createThing(new Thing(request.body)); return response.status(201).json(newThing); } catch (err) { return next(err); } }