Created
March 6, 2025 20:17
-
-
Save Brayden/dfbf51e889323484b10c7f4a7e343eb1 to your computer and use it in GitHub Desktop.
Basic Starbase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { DurableObject } from "cloudflare:workers"; | |
export class MyDurableObject extends DurableObject<Env> { | |
public sql: SqlStorage | |
constructor(ctx: DurableObjectState, env: Env) { | |
super(ctx, env); | |
this.sql = ctx.storage.sql | |
} | |
async executeTransaction(opts: { | |
queries: { sql: string; params?: any[] }[] | |
}): Promise<any> { | |
const { queries } = opts | |
const results = [] | |
for (const query of queries) { | |
let result = await this.executeQuery({ | |
sql: query.sql, | |
params: query.params ?? [], | |
isRaw: true | |
}) | |
if (!result) { | |
console.error('Returning empty array.') | |
return [] | |
} | |
results.push(result) | |
} | |
return results | |
} | |
private async executeRawQuery< | |
T extends Record<string, SqlStorageValue> = Record< | |
string, | |
SqlStorageValue | |
>, | |
>(opts: { sql: string; params?: unknown[] }) { | |
const { sql, params } = opts | |
try { | |
let cursor | |
if (params && params.length) { | |
cursor = this.sql.exec<T>(sql, ...params) | |
} else { | |
cursor = this.sql.exec<T>(sql) | |
} | |
return cursor | |
} catch (error) { | |
console.error('SQL Execution Error:', error) | |
throw error | |
} | |
} | |
public async executeQuery(opts: { | |
sql: string | |
params?: unknown[] | |
isRaw?: boolean | |
}) { | |
const cursor = await this.executeRawQuery(opts) | |
if (opts.isRaw) { | |
return { | |
columns: cursor.columnNames, | |
rows: Array.from(cursor.raw()), | |
meta: { | |
rows_read: cursor.rowsRead, | |
rows_written: cursor.rowsWritten, | |
}, | |
} | |
} | |
return cursor.toArray() | |
} | |
} | |
export default { | |
async fetch(request, env, ctx): Promise<Response> { | |
const path = new URL(request.url).pathname | |
let id: DurableObjectId = env.MY_DURABLE_OBJECT.idFromName(path); | |
let stub = env.MY_DURABLE_OBJECT.get(id); | |
if (path === '/query/raw' && request.method === 'POST') { | |
const { sql, params, transaction } = (await request.json()) as any | |
let data = await stub.executeTransaction({ | |
queries: transaction ?? [{ sql, params }] | |
}) | |
return new Response(JSON.stringify({ result: data }), { | |
status: 200, | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
}) | |
} | |
return new Response('Bad'); | |
} | |
} satisfies ExportedHandler<Env>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment