You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
2.5 KiB

import { Router } from "express";
import { CatType, Cat } from "./cats.model";
const router = Router();
// * C
router.post("/cats", (req, res) => {
try {
const data = req.body;
Cat.push(data);
res.status(200).send({
success: true,
data: { data },
});
} catch (error) {}
});
// * R
router.get("/cats", (req, res) => {
try {
const cats = Cat;
res.status(200).send({
success: true,
data: { cats },
});
} catch (error) {
res.status(400).send({
success: false,
error: error.message,
});
}
});
router.get("/cats/:id", (req, res) => {
try {
const params = req.params;
const cats = Cat.find((cat) => {
return cat.id === params.id;
});
if (!cats) throw new Error("no matched data");
res.status(200).send({
success: true,
data: { cats },
});
} catch (error) {
res.status(400).send({
success: false,
error: error.message,
});
}
});
2 weeks ago
// * U
router.put("/cats/:id", (req, res) => {
try {
const params = req.params;
const body = req.body;
let result;
const index = Cat.findIndex((cat) => cat.id === params.id);
if (index !== -1) {
const tempId = params.id;
const newCat = { ...body, id: tempId };
Cat[index] = newCat;
result = newCat;
}
res.status(200).send({
success: true,
data: { cat: result },
});
} catch (error) {
res.status(400).send({
success: false,
error: error.message,
});
}
});
router.patch("/cats/:id", (req, res) => {
try {
const params = req.params;
const body = req.body;
let result;
const index = Cat.findIndex((cat) => cat.id === params.id);
if (index !== -1) {
const tempId = params.id;
const newCat = { ...Cat[index], ...body, id: tempId };
Cat[index] = newCat;
result = newCat;
}
res.status(200).send({
success: true,
data: { cat: result },
});
} catch (error) {
res.status(400).send({
success: false,
error: error.message,
});
}
});
// * D
router.delete("/cats/:id", (req, res) => {
try {
const params = req.params;
const body = req.body;
let result;
const index = Cat.findIndex((cat) => cat.id === params.id);
if (index !== -1) {
Cat.splice(index, 1);
}
res.status(200).send({
success: true,
data: { cat: result },
});
} catch (error) {
res.status(400).send({
success: false,
error: error.message,
});
}
});
export default router;