|
1 | | -import fastify, { FastifyInstance } from "fastify"; |
| 1 | +import { FastifyInstance } from "fastify"; |
| 2 | +import { StatusCodes } from "http-status-codes"; |
2 | 3 |
|
| 4 | +const dynamicDbData: any = []; |
| 5 | + |
| 6 | +interface Diary { |
| 7 | + id: string; |
| 8 | + title: string; |
| 9 | + content: string; |
| 10 | + createdAt: string; |
| 11 | +} |
| 12 | + |
| 13 | +// CRUD endpoints for diary app |
3 | 14 | export async function diaryRouter(app: FastifyInstance) { |
4 | 15 | app.get("/", async (request, reply) => { |
5 | | - return { hello: "world" }; |
| 16 | + reply.status(StatusCodes.OK).send(dynamicDbData); |
| 17 | + }); |
| 18 | + |
| 19 | + app.post("/", async (request, reply) => { |
| 20 | + const { body } = request; |
| 21 | + dynamicDbData.push(body); |
| 22 | + reply.status(StatusCodes.CREATED).send(body); |
| 23 | + }); |
| 24 | + |
| 25 | + app.patch("/:id", async (request, reply) => { |
| 26 | + const { id } = request.params as Diary; |
| 27 | + const { body } = request; |
| 28 | + const index = dynamicDbData.findIndex((item: Diary) => item.id === id); |
| 29 | + if (index === -1) { |
| 30 | + reply.status(StatusCodes.NOT_FOUND).send(); |
| 31 | + } else { |
| 32 | + dynamicDbData[index] = { ...dynamicDbData[index], ...(body as Diary) }; |
| 33 | + reply.status(StatusCodes.OK).send(dynamicDbData[index]); |
| 34 | + } |
| 35 | + }); |
| 36 | + |
| 37 | + app.delete("/:id", async (request, reply) => { |
| 38 | + const { id } = request.params as { id: string }; |
| 39 | + const index = dynamicDbData.findIndex((item: Diary) => item.id === id); |
| 40 | + if (index === -1) { |
| 41 | + reply.status(StatusCodes.NOT_FOUND).send(); |
| 42 | + } else { |
| 43 | + dynamicDbData.splice(index, 1); |
| 44 | + reply.status(StatusCodes.NO_CONTENT).send(); |
| 45 | + } |
6 | 46 | }); |
7 | 47 | } |
0 commit comments