Skip to content

Instantly share code, notes, and snippets.

@harmanjotsingh1997
Created April 3, 2019 11:04
Show Gist options
  • Save harmanjotsingh1997/7bed67a4c3a5b40bf8deed1c67f2be74 to your computer and use it in GitHub Desktop.
Save harmanjotsingh1997/7bed67a4c3a5b40bf8deed1c67f2be74 to your computer and use it in GitHub Desktop.
node.js todo
const express=require('express')
const app=express()
let todo=[]
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.get('/todo',(req,res) =>
{
if(todo.length==0)
{
res.send({error:'todo is empty'})
}
else
{
res.send(todo)
}
})
app.get('/todo/:id',(req,res)=>
{
const id=req.params.id
res.send(todo[id])
})
app.post('/todo',(req,res)=>
{
todo.push({
task:req.body.task,
priority:req.body.priority
})
res.send({success: true})
})
app.put('/todo/:id',(req,res)=>
{
const id=req.param.id;
let task=req.body.task, priority=req.body.priority;
if(id>todo.length-1 ||(task=null && priority==null))
{
res.send({error:'no todo to replace'})
}
else{
todo[id].task=task;
todo[id].priority=priority;
res.send('replaced successfully')
}
})
app.delete('/todos/:id', (req, res) => {
const id = req.params.id;
if(id > todos.length - 1) {
res.send({error: "Todo with given id does not exist."})
} else {
todos.splice(id, 1);
res.send({msg: "Todo deleted successfully"});
}
})
app.patch('/todos/:id', (req, res) => {
const id = req.params.id;
let task = req.body.task, priority = req.body.priority;
if(id > todos.length - 1 || (task == null && priority == null)) {
res.send({error: "No todo to update"})
} else {
if(task != null)
todos[id].task = task;
if(priority != null)
todos[id].priority = parseInt(priority);
res.send({msg: "Todo updated successfully."})
}
})
app.listen(9000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment