Skip to content

Instantly share code, notes, and snippets.

@Prince-Shaikh
Created September 18, 2021 11:36
Show Gist options
  • Select an option

  • Save Prince-Shaikh/ae8c556964b39353af787af6edeb4d5c to your computer and use it in GitHub Desktop.

Select an option

Save Prince-Shaikh/ae8c556964b39353af787af6edeb4d5c to your computer and use it in GitHub Desktop.
simple node api
const express = require('express');
const app = express();
app.use(express.json);
const PORT = process.env.PORT || 8000;
app.listen(PORT, ()=>{
console.log(`[Server Started] Server is running on ${PORT}`);
});
const arr=[
{id:1,name:"Money Hesit",rating:"5.0"},
{id:2,name:"Black Clover",rating:"4.5"},
{id:3,name:"Jujutsu Kaisen",rating:"4.8"},
{id:4,name:"Honey and Clover",rating:"3.8"},
{id:5,name:"Tokyo Revengers",rating:"5.0"}
];
app.get("/",(req,res)=>{
res.send("API is working");
});
app.get("/titles",(req,res)=>{
res.send(arr);
});
app.post("/titles",(req,res)=>{
arr.push(req.body);
res.send("Title Added");
});
app.put("/titles/:id",(req,res)=>{
const {id}=req.params;
const {name}=req.body;
let obj = arr.find((e)=>{e.id == 'id'});
if(obj == null){
res.status(404).send("Item does not exist in the database.");
}else{
arr[id-1].name = name;
res.send("Item modified.")
}
});
app.put("/ratings/:id",(req,res)=>{
const {id}=req.params;
const {rating}=req.body;
let obj = arr.find((e)=>{e.id == 'id'});
if(obj == null){
res.status(404).send("Item does not exist in the database.");
}else{
arr[id-1].rating = rating;
res.send("Item modified.")
}
});
app.delete("/titles/:id",(req,res)=>{
const {id}=req.params;
let obj = arr.find((e,index)=>{e.id == 'id'});
if(obj == null){
res.status(404).send("Item does not exist in the database.");
}else{
let index = arr.indexOf(obj);
removed_object = arr.splice(index,1);
res.send(removed_object);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment