Last active
October 2, 2018 22:59
-
-
Save dotspencer/15aef9623ad18fbe16e110f098efb591 to your computer and use it in GitHub Desktop.
Sample api validation using yup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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