Created
March 15, 2020 15:26
Star
You must be signed in to star a gist
Express, use Joi to validate data. in post request
This file contains 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 Joi = require('@hapi/joi'); | |
const express = require('express'); | |
const app = express(); | |
app.use(express.json()) | |
const people = [ | |
{id: 1, name:"Jack",}, | |
{id: 2, name:"Ben",}, | |
{id: 3, name:"Well",}, | |
{id: 4, name: "Niggan",}, | |
] | |
app.get('/api/:id', (req, res) => { | |
const personId = req.params.id; | |
const person = people.find(p => p.id === parseInt(personId)) | |
if(!person) return res.status(404).send('the person with giving ID was not found'); | |
res.send(person); | |
}); | |
app.post('/api/person', (req, res) => { | |
// validate with Joi | |
const schema = Joi.object({name: Joi.string().min(3).required()}) | |
const result = schema.validate(req.body); | |
// check if the data was received is validate or not | |
if(result.error) return res.status(400).send(result.error.message); | |
// if it passed the code above it'll add now person to the collection | |
const newPerson = { | |
id: people.length +1, | |
name: req.body.name | |
} | |
people.push(newPerson) | |
res.send(people) | |
console.log(newPerson) | |
}); | |
const port = process.env.PORT || 3000; | |
app.listen(port, () => { | |
console.log(`Example app listening on ${port} port! http://localhost:${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment