-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
157 lines (135 loc) · 3.97 KB
/
index.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import { WorkerEntrypoint } from 'cloudflare:workers'
import { desc, sql } from 'drizzle-orm'
import { drizzle } from 'drizzle-orm/d1'
import { feeds } from '../db/schema/feeds'
import { apples, findColorName } from './apples'
interface Env {
DB: D1Database
}
export class DatabaseWorkerEntrypoint extends WorkerEntrypoint<Env> {
async calculateTotalByName() {
// this.env で WorkerEntrypoint のenvを参照できる
const db = drizzle(this.env.DB)
const results = await db
.select({
name: feeds.name,
total: sql<number>`cast(count(${feeds.id}) as int)`,
})
.from(feeds)
.groupBy(feeds.name)
.orderBy(desc(sql<number>`cast(count(${feeds.id}) as int)`))
const labels = results.map((r) => r.name) ?? []
const totals = results.map((r) => r.total) ?? []
const colorNames = results.map((r) => {
return apples.find((a) => a.name === r.name)?.color
})
const r = {
labels: labels,
datasets: [
{
label: '食べた数',
data: totals,
backgroundColor: colorNames,
borderColor: colorNames,
borderWidth: 1,
},
],
}
return JSON.stringify(r)
}
async calculateTotalByNameAndMonth() {
const db = drizzle(this.env.DB)
const total = await db
.select({
name: feeds.name,
month: sql<number>`cast(strftime('%m', ${feeds.createdAt}) as int)`,
total: sql<number>`cast(count(${feeds.id}) as int)`,
})
.from(feeds)
.groupBy(
feeds.name,
sql<number>`cast(strftime('%m', ${feeds.createdAt}) as int)`,
)
.orderBy(
feeds.name,
sql<number>`cast(strftime('%m', ${feeds.createdAt}) as int)`,
)
const datasets = []
const defaultAttributes = {
tension: 0.1,
}
let name = total[0]?.name as string
let quantities = new Array(12).fill(0)
for (const t of total) {
if (name !== t.name) {
datasets.push({
label: name,
data: quantities,
borderColor: findColorName(name),
backgroundColor: findColorName(name),
...defaultAttributes,
})
name = t.name as string
quantities = new Array(12).fill(0)
}
quantities[t.month - 1] = t.total
}
datasets.push({
label: name,
data: quantities,
borderColor: findColorName(name),
backgroundColor: findColorName(name),
...defaultAttributes,
})
const r = {
labels: [
'1月',
'2月',
'3月',
'4月',
'5月',
'6月',
'7月',
'8月',
'9月',
'10月',
'11月',
'12月',
],
datasets: datasets,
}
return JSON.stringify(r)
}
async insertFeeds(ringoFeeds: string) {
// JSON文字列でわたってくるので、オブジェクトにする
const r = JSON.parse(ringoFeeds)
const v = r.map((fields) => {
// 属性名は、db/schema/feeds.ts で定義した名前にすること
return {
name: fields.name,
content: fields.text,
createdAt: formatDateTime(fields.createdAt),
snsId: fields.cid,
}
})
const db = drizzle(this.env.DB)
// Drizzle ORMの batch API を使ってトランザクションっぽく更新する
// https://orm.drizzle.team/docs/batch-api
await db.batch([db.insert(feeds).values(v)])
}
}
const formatDateTime = (iso8601DateTime: string) => {
const d = new Date(iso8601DateTime)
const year = d.getFullYear()
const month = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
const hours = String(d.getHours()).padStart(2, '0')
const minutes = String(d.getMinutes()).padStart(2, '0')
const seconds = String(d.getSeconds()).padStart(2, '0')
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
export default {
async fetch(_req, _env, _ctx): Promise<Response> {
return new Response('Hello')
},
}