Skip to content

Instantly share code, notes, and snippets.

@dotspencer
Last active October 2, 2018 22:59
Show Gist options
  • Save dotspencer/15aef9623ad18fbe16e110f098efb591 to your computer and use it in GitHub Desktop.
Save dotspencer/15aef9623ad18fbe16e110f098efb591 to your computer and use it in GitHub Desktop.
Sample api validation using yup
const express = require('express');
const yup = require('yup');
const app = express();
app.get('/api/user/new', async (req, res) => {
const valid = await validateParams(req, res, {
name: yup.string().required('Name is required'),
extern_id: yup.string().required('Please select a location'),
});
if (!valid) return;
res.json('success');
});
app.set('json spaces', 2);
app.listen(8005);
/**
*
*/
async function validateParams(req, res, shape) {
const schema = yup.object().shape(shape);
const params = {};
Object.assign(params, req.query);
try {
await schema.validate(params, { abortEarly: false });
return true;
}
catch (error) {
const errors = error.inner.reduce((obj, err) => ({ ...obj, [err.path]: err.message }), {});
console.log('error:', error);
res.json(errors);
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment