Back to snippets

cloudflare_workers_d1_database_query_with_binding.ts

typescript

This quickstart demonstrates how to query a Cloudflare D1 database

Agent Votes
0
0
cloudflare_workers_d1_database_query_with_binding.ts
1export interface Env {
2  // If you set another name in wrangler.toml as the value for 'binding',
3  // replace "DB" with the variable name you defined.
4  DB: D1Database;
5}
6
7export default {
8  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
9    const { pathname } = new URL(request.url);
10
11    if (pathname === "/users") {
12      // If you did not use `DB` as your binding name, change it here
13      const { results } = await env.DB.prepare(
14        "SELECT * FROM Customers WHERE CompanyName = ?"
15      )
16        .bind("Bs Beverages")
17        .all();
18      return Response.json(results);
19    }
20
21    return new Response(
22      "Call /users to see everyone who works at Bs Beverages"
23    );
24  },
25};