Created
July 26, 2019 18:55
-
-
Save winhtut/5bbc165812c1601809dc88ad693ff561 to your computer and use it in GitHub Desktop.
Node.js RESTFUL api by Win Htut
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 app=express(); | |
const Joi=require('joi') | |
app.use(express.json()) | |
const courses=[ | |
{id:1,name:'course1'}, | |
{id:2,name:'course2'}, | |
{id:3,name:'course3'}, | |
]; | |
app.get('/',(req,res)=>{ | |
res.send('Hello World'); | |
}) | |
app.get('/api/courses',(req,res)=>{ | |
res.send(courses); | |
}) | |
app.get('/api/courses/:id',(req,res)=>{ | |
const course=courses.find(c => c.id === parseInt(req.params.id)); | |
if(!course)res.status(404).send('The course with the given id was not found'); | |
res.send(course); | |
}) | |
app.post('/api/course',(req,res)=>{ | |
const schema={ | |
name : Joi.string().min(3).required() | |
};//schema | |
const result=Joi.validate(req.body,schema) | |
if(result.error){ | |
res.status(400).send(result.error.details[0].message); | |
return; | |
} | |
const course={ | |
id: courses.length+1, | |
name: req.body.name | |
}; | |
courses.push(course); | |
res.send(course); | |
}) | |
app.put('/api/courses/:id',(req,res)=>{ | |
const course=courses.find(c => c.id === parseInt(req.params.id)); | |
if(!course)res.status(404).send('The course with the given id was not found'); | |
const schema={ | |
name : Joi.string().min(3).required() | |
};//schema | |
const result=Joi.validate(req.body,schema) | |
if(result.error){ | |
res.status(400).send(result.error.details[0].message); | |
return; | |
} | |
course.name=req.body.name; | |
res.send(course); | |
}); | |
app.delete('/api/courses/:id',(req,res)=>{ | |
const course=courses.find(c => c.id === parseInt(req.params.id)); | |
if(!course)res.status(404).send('The course with the given id was not found'); | |
const index=courses.indexOf(course) | |
courses.splice(index,1); | |
}) | |
const port=process.env.PORT || 3000; | |
app.listen(port,()=>{ | |
console.log(`A journey is on port ${port}... `) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment