-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
88 lines (77 loc) · 2.56 KB
/
Copy pathmain.ts
File metadata and controls
88 lines (77 loc) · 2.56 KB
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
import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { z } from "zod";
const pathValidator = zValidator("param", z.object({ slug: z.string() }));
const queryValidator = zValidator("query", z.object({ userUuid: z.string() }));
const bodyValidator = zValidator("json", z.object({ userUuid: z.string() }));
type Bindings = { DB: D1Database };
const likesApp = new Hono<{ Bindings: Bindings }>()
.get(":slug", pathValidator, queryValidator, async (c) => {
const { slug } = c.req.valid("param");
const { userUuid } = c.req.valid("query");
const likes = await countLikes(c.env.DB, { slug, userUuid });
c.header("Cache-Control", "public, max-age=1800, s-maxage=1800"); // 30分キャッシュする
return c.json(likes);
})
.post(":slug", pathValidator, bodyValidator, async (c) => {
const { slug } = c.req.valid("param");
const { userUuid } = c.req.valid("json");
const newLikes = await like(c.env.DB, { slug, userUuid });
return c.json(newLikes);
})
.delete(":slug", pathValidator, bodyValidator, async (c) => {
const { slug } = c.req.valid("param");
const { userUuid } = c.req.valid("json");
const newLikes = await unlike(c.env.DB, { slug, userUuid });
return c.json(newLikes);
});
interface LikesQueryParam {
slug: string;
userUuid: string;
}
export async function countLikes(
db: D1Database,
{ slug, userUuid }: LikesQueryParam,
) {
const result = await db
.prepare(
`SELECT
count(*) as count,
count(*) FILTER (WHERE user_uuid = ?) as likedByMe
FROM likes WHERE slug = ? GROUP BY slug`,
)
.bind(userUuid, slug)
.all()
.then((result) => {
return (
(result.results[0] as { count: number; likedByMe: number }) ?? {
// NOTE: データ件数が0件のとき、カウント行が取得できないのでデフォルト値を返す
count: 0,
likedByMe: 0,
}
);
});
return {
count: result.count,
likedByMe: result.likedByMe > 0,
};
}
async function like(db: D1Database, { slug, userUuid }: LikesQueryParam) {
await db
.prepare(
"INSERT INTO likes (slug, user_uuid) VALUES (?, ?) ON CONFLICT DO NOTHING",
)
.bind(slug, userUuid)
.run();
return countLikes(db, { slug, userUuid });
}
async function unlike(db: D1Database, { slug, userUuid }: LikesQueryParam) {
await db
.prepare("DELETE FROM likes WHERE slug = ? AND user_uuid = ?")
.bind(slug, userUuid)
.run();
return countLikes(db, { slug, userUuid });
}
const app = new Hono<{ Bindings: Bindings }>().route("/api/likes", likesApp);
export default { fetch: app.fetch };
export type ServerType = typeof app;