Skip to content

Instantly share code, notes, and snippets.

@benyou1969
Created March 15, 2020 15:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save benyou1969/8f4e3db998ab83a8b05809bfe73d2fd8 to your computer and use it in GitHub Desktop.
Express, use Joi to validate data. in post request
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