从头开始创建一个自动产生文档/类型安全的现代API(10) 按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
26
27
28
29
30
31
32
33
34
35
36
...
import { notFoundSchema, IdParamsSchema, badRequestSchema } from "@/utility/constants";
...
export const patch = createRoute({
tags: ["Tasks"],
path: "/tasks/{id}",
method: "patch",
request: {
params: IdParamsSchema,
body: jsonContentRequired(
patchTasksSchema,
"The task to be changed",
)
},
responses: {
[HttpStatusCodes.OK]: jsonContent(
selectTasksSchema,
"The changed task",
),
[HttpStatusCodes.NOT_FOUND]: jsonContent(
notFoundSchema,
"The task id was not found",
),
[HttpStatusCodes.BAD_REQUEST]: jsonContent(
badRequestSchema,
"Update data is empty",
),
[HttpStatusCodes.UNPROCESSABLE_ENTITY]: jsonContent(
createErrorSchema(IdParamsSchema)
.or(createErrorSchema(patchTasksSchema)),
"The validation errors",
),
},
});
...
export type PatchRoute = typeof patch;

添加类型,添加utility/constants.ts:

1
2
...
export const badRequestSchema = createMessageObjectSchema(HttpStatusPhrases.BAD_REQUEST);

修改 db/schema.ts:

1
2
...
export const patchTasksSchema = insertTasksSchema.partial();

添加实现

添加实现,修改 app/api/[[...route]]/routes/tasks/tasks.handlers.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
...
export const patch: AppRouteHandler<PatchRoute> = async (c) => {
const { id } = c.req.valid("param");
const updates = c.req.valid("json");

if (updates.name === undefined && updates.done === undefined) {
return c.json({ message: HttpstatusPhase.BAD_REQUEST }, HttpStatusCodes.BAD_REQUEST);
};

const [task] = await db.update(tasks)
.set({
...updates,
updatedAt: sql`(current_timestamp)`,
})
.where(eq(tasks.id,id))
.returning();

if ( !task ) {
return c.json({ message: HttpstatusPhase.NOT_FOUND }, HttpStatusCodes.NOT_FOUND);
};

return c.json(task, HttpStatusCodes.OK);
};
...

注意,我们这里实现了更新记录时同时更新 updatedAt 字段。

添加引用

添加引用,修改 `` :

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

测试

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

测试一下,用 2 去修改,可以成功修改 name 和 done :

测试一下传空值,可以看到会返回错误 400:

测试一下传不存在的ID,可以看到会返回错误 404:

测试一下id不为数字,可以看到会返回错误 422:

测试一下请求体不符合格式,可以看到会返回错误 422:


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

请我喝杯咖啡吧~

支付宝
微信