Created
January 8, 2023 22:29
-
-
Save drbh/d1d726e4f97002541ec4e569fb2b53fd to your computer and use it in GitHub Desktop.
A hacky but working solution to call D1 from a Durable Object
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
// 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