Last active
April 9, 2022 23:33
-
-
Save azizkale/47340e7901580f51b7461e28f142eed0 to your computer and use it in GitHub Desktop.
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
import express from "express"; | |
import data from "../data"; | |
import bodyParser from "body-parser"; | |
const postRouter = express.Router(); | |
postRouter.use(bodyParser.json()); // to use body object in requests | |
postRouter.get("/", (req, res) => { | |
res.send(data); | |
}); | |
postRouter.get("/:id", (req, res) => { | |
const post = data.find((post) => post.id === +req.params.id); | |
if (!post) { | |
res.sendStatus(404); | |
} | |
res.send(post); | |
}); | |
postRouter.post("/", (req, res) => { | |
try { | |
const post = { | |
...req.body, | |
id: data.length + 1, | |
}; | |
data.push(post); | |
res.send(post); | |
} catch (error) { | |
return res.status(500).send(error); | |
} | |
}); | |
postRouter.put("/:id", (req, res) => { | |
try { | |
let post = data.find((post) => post.id === +req.params.id); | |
post.userId = req.body.userId; | |
post.title = req.body.title; | |
post.body = req.body.body; | |
res.send(post); | |
} catch (error) { | |
return res.status(500).send(error); | |
} | |
}); | |
postRouter.delete("/:id", (req, res) => { | |
let post = data.find((post) => post.id === +req.params.id); | |
const index = data.indexOf(post); | |
if (post) { | |
data.splice(index, 1); | |
res.sendStatus(200); | |
} else { | |
res.sendStatus(404); | |
} | |
}); | |
module.exports = postRouter; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment