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