Skip to content

Instantly share code, notes, and snippets.

@drbh
Created January 8, 2023 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drbh/d1d726e4f97002541ec4e569fb2b53fd to your computer and use it in GitHub Desktop.
Save drbh/d1d726e4f97002541ec4e569fb2b53fd to your computer and use it in GitHub Desktop.
A hacky but working solution to call D1 from a Durable Object
// our DO class
export class SomeDurableObject {
// should upgrade to explicit type in prod
env: any;
constructor(_controller, env) {
this.env = env;
}
// manually make request to D1 binding
async executeSQL(name: string, sql: string): Promise<any> {
return await this.env[`__D1_BETA__${name}`].fetch(`/query`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ sql }),
});
}
async fetch(_request) {
// specify the binding name and sql we want to execute
const bindingName = "DB";
const query = `SELECT * FROM contacts`;
const response = await this.executeSQL(bindingName, query);
// deconstruct response
const { results } = response;
// return it 💪
return new Response(JSON.stringify(results), { status: 200 });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment