import {
FastifyPluginAsyncTypebox,
Type,
} from "@fastify/type-provider-typebox";
import { TodoControllerDto } from "./todo-controller-dto.js";
export const todoController: FastifyPluginAsyncTypebox = async (
fastify,
_options
) => {
let todos: TodoControllerDto[] = [];
fastify.get("/", async (request, reply) => {
return reply.code(200).send(todos);
});
fastify.get(
"/:id",
{
schema: {
params: Type.Object({
id: Type.String(),
}),
},
},
async (request, reply) => {
const { id } = request.params;
return reply.code(200).send(todos.find((t) => t.id === id));
}
);
fastify.post(
"/",
{
schema: {
body: Type.Object({
name: Type.String(),
done: Type.Boolean(),
}),
},
},
async (request, reply) => {
const { name, done } = request.body;
console.log(name, done);
const todo: TodoControllerDto = { id: crypto.randomUUID(), name, done };
todos = [...todos, todo];
return reply.code(201).send(todo);
}
);
fastify.patch(
"/:id",
{
schema: {
params: Type.Object({
id: Type.String(),
}),
body: Type.Object({
name: Type.Optional(Type.String()),
done: Type.Optional(Type.Boolean()),
}),
},
},
async (request, reply) => {
const { id } = request.params;
const { name, done } = request.body;
const todo = todos.find((t) => t.id === id);
todo!.name = name ?? todo!.name;
todo!.done = done ?? todo!.done;
return reply.code(200).send(todo);
}
);
fastify.delete(
"/:id",
{
schema: {
params: Type.Object({
id: Type.String(),
}),
},
},
async (request, reply) => {
const { id } = request.params;
todos = todos.filter((t) => t.id !== id);
return reply.code(204).send();
}
);
};