-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
tasks.handlers.ts
99 lines (83 loc) · 2.42 KB
/
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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { eq } from "drizzle-orm";
import * as HttpStatusCodes from "stoker/http-status-codes";
import * as HttpStatusPhrases from "stoker/http-status-phrases";
import type { AppRouteHandler } from "@/lib/types";
import db from "@/db";
import { tasks } from "@/db/schema";
import { ZOD_ERROR_CODES, ZOD_ERROR_MESSAGES } from "@/lib/constants";
import type { CreateRoute, GetOneRoute, ListRoute, PatchRoute, RemoveRoute } from "./tasks.routes";
export const list: AppRouteHandler<ListRoute> = async (c) => {
const tasks = await db.query.tasks.findMany();
return c.json(tasks);
};
export const create: AppRouteHandler<CreateRoute> = async (c) => {
const task = c.req.valid("json");
const [inserted] = await db.insert(tasks).values(task).returning();
return c.json(inserted, HttpStatusCodes.OK);
};
export const getOne: AppRouteHandler<GetOneRoute> = async (c) => {
const { id } = c.req.valid("param");
const task = await db.query.tasks.findFirst({
where(fields, operators) {
return operators.eq(fields.id, id);
},
});
if (!task) {
return c.json(
{
message: HttpStatusPhrases.NOT_FOUND,
},
HttpStatusCodes.NOT_FOUND,
);
}
return c.json(task, HttpStatusCodes.OK);
};
export const patch: AppRouteHandler<PatchRoute> = async (c) => {
const { id } = c.req.valid("param");
const updates = c.req.valid("json");
if (Object.keys(updates).length === 0) {
return c.json(
{
success: false,
error: {
issues: [
{
code: ZOD_ERROR_CODES.INVALID_UPDATES,
path: [],
message: ZOD_ERROR_MESSAGES.NO_UPDATES,
},
],
name: "ZodError",
},
},
HttpStatusCodes.UNPROCESSABLE_ENTITY,
);
}
const [task] = await db.update(tasks)
.set(updates)
.where(eq(tasks.id, id))
.returning();
if (!task) {
return c.json(
{
message: HttpStatusPhrases.NOT_FOUND,
},
HttpStatusCodes.NOT_FOUND,
);
}
return c.json(task, HttpStatusCodes.OK);
};
export const remove: AppRouteHandler<RemoveRoute> = 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: HttpStatusPhrases.NOT_FOUND,
},
HttpStatusCodes.NOT_FOUND,
);
}
return c.body(null, HttpStatusCodes.NO_CONTENT);
};