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.
|
|
|
import * as express from "express";
|
|
|
|
import * as cors from "cors";
|
|
|
|
|
|
|
|
import { CatType, Cat } from "./app.model";
|
|
|
|
|
|
|
|
const app: express.Express = express();
|
|
|
|
const port: number = 8000;
|
|
|
|
|
|
|
|
app.use(cors());
|
|
|
|
|
|
|
|
// * Logging Middleware
|
|
|
|
app.use((req, res, next) => {
|
|
|
|
console.log(req.rawHeaders[1]);
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
|
|
|
|
// * json middleware
|
|
|
|
app.use(express.json());
|
|
|
|
|
|
|
|
// * C
|
|
|
|
app.post("/cats", (req, res) => {
|
|
|
|
try {
|
|
|
|
const data = req.body;
|
|
|
|
Cat.push(data);
|
|
|
|
res.status(200).send({
|
|
|
|
success: true,
|
|
|
|
data: { data },
|
|
|
|
});
|
|
|
|
} catch (error) {}
|
|
|
|
});
|
|
|
|
|
|
|
|
// * R
|
|
|
|
app.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,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
app.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,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// * 404 middleware
|
|
|
|
app.use((req, res, next) => {
|
|
|
|
console.log(req.rawHeaders[1]);
|
|
|
|
console.log("This is 404 middleware");
|
|
|
|
res.send({ error: "404 not found error" });
|
|
|
|
});
|
|
|
|
|
|
|
|
app.listen(port, () => {
|
|
|
|
console.log(`server is on ${port}`);
|
|
|
|
});
|