|
1 | 1 | /** |
2 | | - * Aggregate drink ratings API (v1). |
| 2 | + * Ratings resource family for the /v1 API (AIP resource-oriented). |
3 | 3 | * |
4 | | - * Endpoints (all under /v1/ratings, served by the same worker as the proxy): |
5 | | - * POST /v1/ratings upsert a device's rating |
6 | | - * DELETE /v1/ratings remove a device's rating |
7 | | - * GET /v1/ratings/{festivalId}/{drinkId} aggregate for one drink |
8 | | - * GET /v1/ratings/{festivalId} aggregate for every rated drink |
| 4 | + * GET /v1/festivals/{f}/drinks/{d}/ratings/{device} get my rating |
| 5 | + * PATCH /v1/festivals/{f}/drinks/{d}/ratings/{device} upsert my rating |
| 6 | + * DELETE /v1/festivals/{f}/drinks/{d}/ratings/{device} remove my rating |
| 7 | + * GET /v1/festivals/{f}/ratingSummaries/{d} aggregate for a drink |
| 8 | + * GET /v1/festivals/{f}/ratingSummaries list (paginated) |
9 | 9 | * |
10 | | - * Writes are local-first on the client; the server is the shared aggregate. |
11 | | - * Shared bucket/validation/routing plumbing lives in shared.js. |
| 10 | + * Backed by the `ratings` table in D1. Writes are local-first on the client. |
12 | 11 | */ |
13 | 12 |
|
14 | | -import { |
15 | | - validateIds, |
16 | | - jsonResponse, |
17 | | - parseJsonBody, |
18 | | - routeResource, |
19 | | -} from "./shared.js"; |
| 13 | +import { handleResourceFamily, rfc3339 } from "./shared.js"; |
20 | 14 |
|
21 | | -/** |
22 | | - * Validate a write payload. POST requires `rating`; DELETE only needs ids. |
23 | | - * Returns { ok: true, value } or { ok: false, error }. |
24 | | - */ |
25 | | -export function validateWritePayload(body, { requireRating }) { |
26 | | - const ids = validateIds(body); |
27 | | - if (!ids.ok) return ids; |
28 | | - |
29 | | - const { rating } = body; |
30 | | - if (requireRating) { |
31 | | - if (!Number.isInteger(rating) || rating < 1 || rating > 5) { |
32 | | - return { ok: false, error: "rating must be an integer between 1 and 5" }; |
33 | | - } |
34 | | - } |
35 | | - return { ok: true, value: { ...ids.value, rating } }; |
36 | | -} |
37 | | - |
38 | | -/** Round an average to one decimal place, or null when there are no ratings. */ |
39 | | -export function formatAverage(average, count) { |
40 | | - if (!count || average == null) return null; |
41 | | - return Math.round(average * 10) / 10; |
42 | | -} |
43 | | - |
44 | | -/** Aggregate (count + average) for a single drink in a bucket. */ |
45 | | -async function readAggregate(db, bucket, festivalId, drinkId, deviceId) { |
46 | | - const agg = await db |
47 | | - .prepare( |
48 | | - "SELECT COUNT(*) AS count, AVG(rating) AS average " + |
49 | | - "FROM ratings WHERE bucket = ? AND festival_id = ? AND drink_id = ?", |
50 | | - ) |
51 | | - .bind(bucket, festivalId, drinkId) |
52 | | - .first(); |
53 | | - |
54 | | - let yourRating = null; |
55 | | - if (deviceId) { |
56 | | - const own = await db |
57 | | - .prepare( |
58 | | - "SELECT rating FROM ratings " + |
59 | | - "WHERE bucket = ? AND festival_id = ? AND drink_id = ? AND device_id = ?", |
60 | | - ) |
61 | | - .bind(bucket, festivalId, drinkId, deviceId) |
62 | | - .first(); |
63 | | - yourRating = own ? own.rating : null; |
64 | | - } |
65 | | - |
66 | | - const count = agg ? agg.count : 0; |
67 | | - return { |
68 | | - festivalId, |
69 | | - drinkId, |
70 | | - count, |
71 | | - average: formatAverage(agg ? agg.average : null, count), |
72 | | - yourRating, |
73 | | - }; |
| 15 | +function round1(value) { |
| 16 | + return Math.round(value * 10) / 10; |
74 | 17 | } |
75 | 18 |
|
76 | | -async function handlePost(request, db, bucket, corsHeaders) { |
77 | | - const parsed = await parseJsonBody(request); |
78 | | - if (!parsed.ok) { |
79 | | - return jsonResponse({ error: "Invalid JSON body" }, 400, corsHeaders); |
80 | | - } |
81 | | - |
82 | | - const result = validateWritePayload(parsed.body, { requireRating: true }); |
83 | | - if (!result.ok) { |
84 | | - return jsonResponse({ error: result.error }, 400, corsHeaders); |
85 | | - } |
86 | | - |
87 | | - const { festivalId, drinkId, deviceId, rating } = result.value; |
88 | | - await db |
89 | | - .prepare( |
90 | | - "INSERT INTO ratings (bucket, festival_id, drink_id, device_id, rating, updated_at) " + |
91 | | - "VALUES (?, ?, ?, ?, ?, ?) " + |
92 | | - "ON CONFLICT (bucket, festival_id, drink_id, device_id) " + |
93 | | - "DO UPDATE SET rating = excluded.rating, updated_at = excluded.updated_at", |
94 | | - ) |
95 | | - .bind(bucket, festivalId, drinkId, deviceId, rating, Date.now()) |
96 | | - .run(); |
97 | | - |
98 | | - const aggregate = await readAggregate( |
99 | | - db, |
100 | | - bucket, |
101 | | - festivalId, |
102 | | - drinkId, |
103 | | - deviceId, |
104 | | - ); |
105 | | - return jsonResponse(aggregate, 200, corsHeaders); |
106 | | -} |
107 | | - |
108 | | -async function handleDelete(request, db, bucket, corsHeaders) { |
109 | | - const parsed = await parseJsonBody(request); |
110 | | - if (!parsed.ok) { |
111 | | - return jsonResponse({ error: "Invalid JSON body" }, 400, corsHeaders); |
112 | | - } |
113 | | - |
114 | | - const result = validateWritePayload(parsed.body, { requireRating: false }); |
115 | | - if (!result.ok) { |
116 | | - return jsonResponse({ error: result.error }, 400, corsHeaders); |
117 | | - } |
118 | | - |
119 | | - const { festivalId, drinkId, deviceId } = result.value; |
120 | | - await db |
121 | | - .prepare( |
122 | | - "DELETE FROM ratings " + |
123 | | - "WHERE bucket = ? AND festival_id = ? AND drink_id = ? AND device_id = ?", |
124 | | - ) |
125 | | - .bind(bucket, festivalId, drinkId, deviceId) |
126 | | - .run(); |
127 | | - |
128 | | - const aggregate = await readAggregate( |
129 | | - db, |
130 | | - bucket, |
131 | | - festivalId, |
132 | | - drinkId, |
133 | | - deviceId, |
134 | | - ); |
135 | | - return jsonResponse(aggregate, 200, corsHeaders); |
136 | | -} |
137 | | - |
138 | | -async function handleGetSingle( |
139 | | - db, |
140 | | - bucket, |
141 | | - festivalId, |
142 | | - drinkId, |
143 | | - deviceId, |
144 | | - corsHeaders, |
145 | | -) { |
146 | | - const aggregate = await readAggregate( |
147 | | - db, |
148 | | - bucket, |
149 | | - festivalId, |
150 | | - drinkId, |
151 | | - deviceId, |
152 | | - ); |
153 | | - return jsonResponse(aggregate, 200, corsHeaders); |
154 | | -} |
155 | | - |
156 | | -/** Batch: every rated drink for a festival, keyed by drink id. */ |
157 | | -async function handleGetFestival( |
158 | | - db, |
159 | | - bucket, |
160 | | - festivalId, |
161 | | - deviceId, |
162 | | - corsHeaders, |
163 | | -) { |
164 | | - const { results } = await db |
165 | | - .prepare( |
166 | | - "SELECT drink_id, COUNT(*) AS count, AVG(rating) AS average " + |
167 | | - "FROM ratings WHERE bucket = ? AND festival_id = ? GROUP BY drink_id", |
168 | | - ) |
169 | | - .bind(bucket, festivalId) |
170 | | - .all(); |
171 | | - |
172 | | - const own = new Map(); |
173 | | - if (deviceId) { |
174 | | - const ownRows = await db |
175 | | - .prepare( |
176 | | - "SELECT drink_id, rating FROM ratings " + |
177 | | - "WHERE bucket = ? AND festival_id = ? AND device_id = ?", |
178 | | - ) |
179 | | - .bind(bucket, festivalId, deviceId) |
180 | | - .all(); |
181 | | - for (const row of ownRows.results) { |
182 | | - own.set(row.drink_id, row.rating); |
| 19 | +export const RATINGS_FAMILY = { |
| 20 | + table: "ratings", |
| 21 | + valueColumn: "rating", |
| 22 | + writeCollection: "ratings", |
| 23 | + summaryCollection: "ratingSummaries", |
| 24 | + |
| 25 | + /** Validate the Rating body { value: 1..5 }. */ |
| 26 | + parseValue(body) { |
| 27 | + if (body === null || typeof body !== "object") { |
| 28 | + return { |
| 29 | + ok: false, |
| 30 | + reason: "INVALID_BODY", |
| 31 | + message: "Body must be a JSON object", |
| 32 | + }; |
183 | 33 | } |
184 | | - } |
185 | | - |
186 | | - const aggregates = {}; |
187 | | - for (const row of results) { |
188 | | - aggregates[row.drink_id] = { |
189 | | - count: row.count, |
190 | | - average: formatAverage(row.average, row.count), |
191 | | - yourRating: own.has(row.drink_id) ? own.get(row.drink_id) : null, |
| 34 | + const { value } = body; |
| 35 | + if (!Number.isInteger(value) || value < 1 || value > 5) { |
| 36 | + return { |
| 37 | + ok: false, |
| 38 | + reason: "RATING_VALUE_OUT_OF_RANGE", |
| 39 | + message: "value must be an integer between 1 and 5", |
| 40 | + }; |
| 41 | + } |
| 42 | + return { ok: true, columnValue: value }; |
| 43 | + }, |
| 44 | + |
| 45 | + /** Serialize a Rating resource from a DB row { value, updated_at }. */ |
| 46 | + serializeResource(name, row) { |
| 47 | + return { name, value: row.value, updateTime: rfc3339(row.updated_at) }; |
| 48 | + }, |
| 49 | + |
| 50 | + // Aggregate columns selected for summary single + list queries. |
| 51 | + summaryColumns: "COUNT(*) AS agg_count, AVG(rating) AS agg_average", |
| 52 | + |
| 53 | + /** Build RatingSummary fields from an aggregate row. */ |
| 54 | + summaryFields(row) { |
| 55 | + const count = row.agg_count || 0; |
| 56 | + return { |
| 57 | + ratingCount: count, |
| 58 | + averageRating: count ? round1(row.agg_average) : 0, |
192 | 59 | }; |
193 | | - } |
194 | | - |
195 | | - return jsonResponse({ festivalId, aggregates }, 200, corsHeaders); |
196 | | -} |
| 60 | + }, |
| 61 | +}; |
197 | 62 |
|
198 | | -/** Route and handle a /v1/ratings request, or null if not a ratings path. */ |
| 63 | +/** Route a ratings request, or null if the path is not a ratings path. */ |
199 | 64 | export function handleRatings(request, url, env, corsHeaders) { |
200 | | - return routeResource(request, url, env, corsHeaders, { |
201 | | - basePath: "/v1/ratings", |
202 | | - db: "RATINGS_DB", |
203 | | - post: handlePost, |
204 | | - del: handleDelete, |
205 | | - getSingle: handleGetSingle, |
206 | | - getFestival: handleGetFestival, |
207 | | - }); |
| 65 | + return handleResourceFamily(request, url, env, corsHeaders, RATINGS_FAMILY); |
208 | 66 | } |
0 commit comments