Diffinery

homeflare/celldpublic

35 lines · 1.2 KBRaw History
1export class Palette {
2 constructor(state) {
3 this.sql = state.storage.sql;
4 this.sql.exec("CREATE VIRTUAL TABLE IF NOT EXISTS colors USING vec0(rgb float[3], +name text)");
5 }
6
7 async fetch(request) {
8 const path = new URL(request.url).pathname.slice(1);
9 const rgb = request.method === "PUT" ? await request.json() : path.split(",").map(Number);
10 if (
11 !Array.isArray(rgb) ||
12 rgb.length !== 3 ||
13 rgb.some((n) => !Number.isFinite(n) || n < 0 || n > 255) ||
14 (request.method === "PUT" && !path)
15 ) {
16 return new Response("Use an RGB array with three values from 0 through 255.\n", { status: 400 });
17 }
18 const vector = JSON.stringify(rgb.map((n) => n / 255));
19 if (request.method === "PUT") {
20 this.sql.exec("INSERT INTO colors(rgb, name) VALUES (?, ?)", vector, decodeURIComponent(path));
21 return new Response(null, { status: 201 });
22 }
23 const match = this.sql.exec(
24 "SELECT name, distance FROM colors WHERE rgb MATCH ? AND k = 1",
25 vector,
26 ).toArray()[0];
27 return match ? Response.json(match) : new Response("The palette is empty.\n", { status: 404 });
28 }
29}
30
31export default {
32 fetch(request, env) {
33 return env.PALETTE.getByName("colors").fetch(request);
34 },
35};