从头开始创建一个自动产生文档/类型安全的现代API(11) 按id删除任务

下面我们给 API 添加按id删除任务。

添加根据 ID 修改任务

添加路径

添加路径,修改app/api/[[...route]]/routes/tasks/tasks.routes.ts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
...
export const deleteById = createRoute({
tags: ["Tasks"],
path: "/tasks/{id}",
method: "delete",
request: {
params: IdParamsSchema,
},
responses: {
[HttpStatusCodes.NO_CONTENT]: {
description: "Task deleted",
},
[HttpStatusCodes.NOT_FOUND]: jsonContent(
notFoundSchema,
"The task was not found",
),
[HttpStatusCodes.UNPROCESSABLE_ENTITY]: jsonContent(
createErrorSchema(IdParamsSchema),
"Invalid id error",
),
},
});

...
export type DeleteByIdRoute = typeof deleteById;

添加实现

添加实现,修改 app/api/[[...route]]/routes/tasks/tasks.handlers.ts :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
...
export const deleteById: AppRouteHandler<DeleteByIdRoute> = async (c) => {
const { id } = c.req.valid("param");

const result = await db
.delete(tasks)
.where(eq(tasks.id, id));

if ( result.rowsAffected === 0 ) {
return c.json({ message: HttpstatusPhase.NOT_FOUND }, HttpStatusCodes.NOT_FOUND);
};

return c.body(null, HttpStatusCodes.NO_CONTENT );
};

...

添加引用

添加引用,修改 `` :

1
2
3
...
.openapi(routes.deleteById, handlers.deleteById);
...

测试

访问 localhost:3000/reference, 可以看到API已更新:


作者:Bearalise
出处:从头开始创建一个自动产生文档/类型安全的现代API(11) 按id删除任务
版权:本文版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明,必须在文章中给出原文链接。

请我喝杯咖啡吧~

支付宝
微信