Lumen & Gesso / website · lumengesso.com / app / lib / d1-commerce.ts
| 1 | import type { Database } from './supabase/types'; |
| 2 | |
| 3 | export type BindingValue = string | number | null; |
| 4 | |
| 5 | type Statement = { |
| 6 | bind(...values: BindingValue[]): Statement; |
| 7 | all<T>(): Promise<{ results: T[] }>; |
| 8 | }; |
| 9 | |
| 10 | export type CommerceBinding = { prepare(sql: string): Statement }; |
| 11 | |
| 12 | type Table = 'orders' | 'generations' | 'order_reviews' | 'integrations'; |
| 13 | type Row = Record<string, any>; |
| 14 | type Result<T> = { data: T | null; error: { code: string; message: string } | null }; |
| 15 | type SourceTables = Database['public']['Tables']; |
| 16 | type Rows = { |
| 17 | orders: Omit<SourceTables['orders']['Row'], 'config' | 'shipping_address'> & { |
| 18 | config: Row; shipping_address: Row | null; cart_reminders_sent: number; rejected_at: string | null; |
| 19 | }; |
| 20 | generations: SourceTables['generations']['Row']; |
| 21 | order_reviews: { |
| 22 | id: string; order_id: string; rating: number; comment: string; display_name: string | null; |
| 23 | photo_path: string | null; status: string; created_at: string; published_at: string | null; discovery_source: string | null; |
| 24 | }; |
| 25 | integrations: { key: string; value: string | null; updated_at: string }; |
| 26 | }; |
| 27 | type Trim<S extends string> = S extends ` ${infer Rest}` ? Trim<Rest> |
| 28 | : S extends `${infer Rest} ` ? Trim<Rest> : S; |
| 29 | type FieldNames<S extends string> = S extends `${infer First},${infer Rest}` |
| 30 | ? Trim<First> | FieldNames<Rest> : Trim<S>; |
| 31 | type Projection<T extends Table, S extends string> = S extends '*' ? Rows[T] |
| 32 | : string extends S ? Rows[T] : Pick<Rows[T], Extract<FieldNames<S>, keyof Rows[T]>>; |
| 33 | |
| 34 | const jsonColumns = new Set(['config', 'pet_photo_urls', 'shipping_address']); |
| 35 | const timestampFields = new Set(['created_at', 'updated_at', 'published_at']); |
| 36 | |
| 37 | function identifier(name: string): string { |
| 38 | if (!/^[a-z][a-z_]*$/.test(name)) throw new Error('Invalid commerce field.'); |
| 39 | return `"${name}"`; |
| 40 | } |
| 41 | |
| 42 | function column(name: string): string { |
| 43 | if (name === 'config->customerCancellation->>state') return "json_extract(config, '$.customerCancellation.state')"; |
| 44 | return identifier(name); |
| 45 | } |
| 46 | |
| 47 | function bindValue(value: unknown): BindingValue { |
| 48 | if (value === null || typeof value === 'number' || typeof value === 'string') return value; |
| 49 | if (typeof value === 'boolean') return Number(value); |
| 50 | const json = JSON.stringify(value); |
| 51 | if (json === undefined) throw new Error('Invalid commerce field value.'); |
| 52 | return json; |
| 53 | } |
| 54 | |
| 55 | function decode(row: Row): Row { |
| 56 | for (const key of jsonColumns) { |
| 57 | if (typeof row[key] === 'string') row[key] = JSON.parse(row[key]); |
| 58 | } |
| 59 | if (typeof row.published === 'number') row.published = Boolean(row.published); |
| 60 | return row; |
| 61 | } |
| 62 | |
| 63 | function insertDefaults(table: Table, row: Row): Row { |
| 64 | const now = new Date().toISOString(); |
| 65 | if (table === 'orders') return { |
| 66 | status: 'pending_payment', pet_photo_urls: [], cart_reminders_sent: 0, |
| 67 | created_at: now, updated_at: now, ...row, |
| 68 | }; |
| 69 | if (table === 'generations') return { id: crypto.randomUUID(), published: false, created_at: now, ...row }; |
| 70 | if (table === 'order_reviews') return { id: crypto.randomUUID(), status: 'pending', created_at: now, ...row }; |
| 71 | return { updated_at: now, ...row }; |
| 72 | } |
| 73 | |
| 74 | function databaseError(error: unknown): Result<never> { |
| 75 | const detail = error instanceof Error ? error.message : ''; |
| 76 | if (/unique constraint failed|SQLITE_CONSTRAINT_UNIQUE/i.test(detail)) { |
| 77 | return { data: null, error: { code: '23505', message: 'That record already exists.' } }; |
| 78 | } |
| 79 | return { data: null, error: { code: 'D1_ERROR', message: 'The studio database could not complete the request.' } }; |
| 80 | } |
| 81 | |
| 82 | class CommerceQuery<T extends Table, Selected = Rows[T]> implements PromiseLike<Result<Selected[]>> { |
| 83 | private action: 'select' | 'insert' | 'update' | 'delete' = 'select'; |
| 84 | private projection: string | undefined; |
| 85 | private filters: string[] = []; |
| 86 | private binds: BindingValue[] = []; |
| 87 | private ordering = ''; |
| 88 | private rowLimit: number | undefined; |
| 89 | private fields: Row = {}; |
| 90 | private conflictKey: string | undefined; |
| 91 | private db: CommerceBinding; |
| 92 | private table: T; |
| 93 | |
| 94 | constructor(db: CommerceBinding, table: T) { |
| 95 | this.db = db; |
| 96 | this.table = table; |
| 97 | } |
| 98 | |
| 99 | select<const S extends string = '*'>(fields?: S): CommerceQuery<T, Projection<T, S>> { |
| 100 | this.projection = !fields || fields === '*' ? '*' : fields.split(',').map((name) => identifier(name.trim())).join(', '); |
| 101 | return this as unknown as CommerceQuery<T, Projection<T, S>>; |
| 102 | } |
| 103 | |
| 104 | insert(fields: Row) { |
| 105 | this.action = 'insert'; |
| 106 | this.fields = fields; |
| 107 | return this; |
| 108 | } |
| 109 | |
| 110 | upsert(fields: Row, options: { onConflict: string }) { |
| 111 | this.conflictKey = options.onConflict; |
| 112 | return this.insert(fields); |
| 113 | } |
| 114 | |
| 115 | update(fields: Row) { |
| 116 | this.action = 'update'; |
| 117 | this.fields = fields; |
| 118 | return this; |
| 119 | } |
| 120 | |
| 121 | delete() { |
| 122 | this.action = 'delete'; |
| 123 | return this; |
| 124 | } |
| 125 | |
| 126 | private compare(field: string, operator: '=' | '<>' | '<' | '>', value: unknown) { |
| 127 | const name = column(field); |
| 128 | const dated = (operator === '<' || operator === '>') && timestampFields.has(field); |
| 129 | this.filters.push(dated ? `julianday(${name}) ${operator} julianday(?)` : `${name} ${operator} ?`); |
| 130 | this.binds.push(bindValue(value)); |
| 131 | return this; |
| 132 | } |
| 133 | |
| 134 | eq(field: string, value: unknown) { return this.compare(field, '=', value); } |
| 135 | neq(field: string, value: unknown) { return this.compare(field, '<>', value); } |
| 136 | lt(field: string, value: unknown) { return this.compare(field, '<', value); } |
| 137 | gt(field: string, value: unknown) { return this.compare(field, '>', value); } |
| 138 | |
| 139 | in(field: string, values: readonly unknown[]) { |
| 140 | this.filters.push(values.length ? `${column(field)} IN (${values.map(() => '?').join(', ')})` : '0 = 1'); |
| 141 | this.binds.push(...values.map(bindValue)); |
| 142 | return this; |
| 143 | } |
| 144 | |
| 145 | order(field: string, options: { ascending?: boolean } = {}) { |
| 146 | this.ordering = ` ORDER BY ${column(field)} ${options.ascending === false ? 'DESC' : 'ASC'}`; |
| 147 | return this; |
| 148 | } |
| 149 | |
| 150 | limit(count: number) { |
| 151 | if (!Number.isSafeInteger(count) || count < 0) throw new Error('Invalid commerce query limit.'); |
| 152 | this.rowLimit = count; |
| 153 | return this; |
| 154 | } |
| 155 | |
| 156 | private statement(maximumRows?: number) { |
| 157 | const table = identifier(this.table); |
| 158 | const where = this.filters.length ? ' WHERE ' + this.filters.join(' AND ') : ''; |
| 159 | const select = this.projection ?? '*'; |
| 160 | const returning = this.projection ? ' RETURNING ' + this.projection : ''; |
| 161 | |
| 162 | if (this.action === 'select') { |
| 163 | const limit = Math.min(this.rowLimit ?? Infinity, maximumRows ?? Infinity); |
| 164 | return { |
| 165 | sql: `SELECT ${select} FROM ${table}${where}${this.ordering}${Number.isFinite(limit) ? ' LIMIT ' + limit : ''}`, |
| 166 | values: this.binds, |
| 167 | }; |
| 168 | } |
| 169 | |
| 170 | if (this.action === 'delete') { |
| 171 | if (!where) throw new Error('Commerce delete requires a filter.'); |
| 172 | return { sql: `DELETE FROM ${table}${where}${returning}`, values: this.binds }; |
| 173 | } |
| 174 | |
| 175 | const input = this.action === 'insert' ? insertDefaults(this.table, this.fields) : this.fields; |
| 176 | const entries = Object.entries(input).filter(([, value]) => value !== undefined); |
| 177 | const values = entries.map(([, value]) => bindValue(value)); |
| 178 | const columns = entries.map(([key]) => identifier(key)); |
| 179 | |
| 180 | if (this.action === 'insert') { |
| 181 | const conflict = this.conflictKey; |
| 182 | const merge = conflict ? ` ON CONFLICT (${identifier(conflict)}) DO UPDATE SET ${entries |
| 183 | .filter(([key]) => key !== conflict) |
| 184 | .map(([key]) => `${identifier(key)} = excluded.${identifier(key)}`).join(', ')}` : ''; |
| 185 | const slots = values.map(() => '?').join(', '); |
| 186 | return { sql: `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${slots})${merge}${returning}`, values }; |
| 187 | } |
| 188 | |
| 189 | if (!where) throw new Error('Commerce update requires a filter.'); |
| 190 | const assignments = columns.map((name) => name + ' = ?'); |
| 191 | if ((this.table === 'orders' || this.table === 'integrations') && !columns.includes('"updated_at"')) { |
| 192 | // Keep optimistic claims distinct even when two writes land in the same millisecond. |
| 193 | assignments.push(`updated_at = CASE |
| 194 | WHEN julianday(updated_at) >= julianday('now') |
| 195 | THEN strftime('%Y-%m-%dT%H:%M:%fZ', updated_at, '+0.001 seconds') |
| 196 | ELSE strftime('%Y-%m-%dT%H:%M:%fZ', 'now') |
| 197 | END`); |
| 198 | } |
| 199 | return { |
| 200 | sql: `UPDATE ${table} SET ${assignments.join(', ')}${where}${returning}`, |
| 201 | values: [...values, ...this.binds], |
| 202 | }; |
| 203 | } |
| 204 | |
| 205 | private async execute(maximumRows?: number): Promise<Result<Selected[]>> { |
| 206 | try { |
| 207 | const { sql, values } = this.statement(maximumRows); |
| 208 | const { results } = await this.db.prepare(sql).bind(...values).all<Row>(); |
| 209 | const returnsRows = this.action === 'select' || this.projection; |
| 210 | return { data: returnsRows ? results.map(decode) as Selected[] : null, error: null }; |
| 211 | } catch (error) { |
| 212 | return databaseError(error); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | private async one(optional: boolean): Promise<Result<Selected>> { |
| 217 | const result = await this.execute(2); |
| 218 | if (result.error) return { data: null, error: result.error }; |
| 219 | const rows = result.data ?? []; |
| 220 | if (rows.length === 1 || (optional && rows.length === 0)) return { data: rows[0] ?? null, error: null }; |
| 221 | return { data: null, error: { code: 'PGRST116', message: 'Expected a single record.' } }; |
| 222 | } |
| 223 | |
| 224 | single() { return this.one(false); } |
| 225 | maybeSingle() { return this.one(true); } |
| 226 | |
| 227 | then<TResult1 = Result<Selected[]>, TResult2 = never>( |
| 228 | fulfilled?: ((value: Result<Selected[]>) => TResult1 | PromiseLike<TResult1>) | null, |
| 229 | rejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null, |
| 230 | ): PromiseLike<TResult1 | TResult2> { |
| 231 | return this.execute().then(fulfilled, rejected); |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | export function d1Commerce(db: CommerceBinding) { |
| 236 | return { from: <T extends Table>(table: T) => new CommerceQuery(db, table) }; |
| 237 | } |
| 238 | |
| 239 | export async function sweepAbandonedCheckouts(db: CommerceBinding, cutoff: string) { |
| 240 | await db.prepare(` |
| 241 | UPDATE orders SET status = 'abandoned', updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') |
| 242 | WHERE status = 'pending_payment' AND julianday(created_at) < julianday(?) |
| 243 | `).bind(cutoff).all(); |
| 244 | } |