Skip to content

Commit

Permalink
feat(example): extend batcher examples to use bindings (D1)
Browse files Browse the repository at this point in the history
  • Loading branch information
sor4chi committed Dec 3, 2023
1 parent 504a315 commit fa4166d
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 26 deletions.
21 changes: 20 additions & 1 deletion examples/batcher/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,25 @@ The code is based on [Cloudflare's Alarm example](https://developers.cloudflare.

```
pnpm install
pnpm dev
```

Setup the database:

```
pnpm create-db
```

Copy the outputted database configuration.
Add the database configuration to the `wrangler.toml` file.

Add the following to the `wrangler.toml` file's `[[d1_databases]]` section:

```
preview_database_id = "DB"
```

Run the following to start the batcher:

```
pnpm dev
```
3 changes: 2 additions & 1 deletion examples/batcher/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"format": "prettier --write \"src/**/*.{ts,tsx}\"",
"format:check": "prettier --check \"src/**/*.{ts,tsx}\"",
"dev": "wrangler dev src/index.ts",
"deploy": "wrangler deploy --minify src/index.ts"
"deploy": "wrangler deploy --minify src/index.ts",
"create-db": "wrangler d1 create batch-db"
},
"dependencies": {
"hono": "^3.6.0",
Expand Down
59 changes: 37 additions & 22 deletions examples/batcher/src/batcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import { generateHonoObject } from "hono-do";

import { Env } from ".";

const SECONDS = 1000;

declare module "hono-do" {
Expand All @@ -10,29 +12,42 @@ declare module "hono-do" {
}
}

export const Batcher = generateHonoObject(
"/batcher",
async (app, state, vars) => {
const { storage } = state;
const vals = await storage.list({ reverse: true, limit: 1 });
vars.count = vals.size === 0 ? 0 : parseInt(vals.keys().next().value);

app.post("/", async (c) => {
vars.count++;

const currentAlarm = await storage.getAlarm();
if (currentAlarm == null) {
await storage.setAlarm(Date.now() + 10 * SECONDS);
}

await storage.put(vars.count.toString(), await c.req.text());
return c.json({ queued: vars.count });
});
},
).alarm(async (state, vars) => {
export const Batcher = generateHonoObject<
Env,
Record<string, never>,
"/batcher"
>("/batcher", async (app, state, vars) => {
await vars.env.DB.prepare(
"CREATE TABLE IF NOT EXISTS batcher (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT)",
).run();

const { storage } = state;
const vals = await storage.list();
console.log(Array.from(vals.values())); // eg: POST other upstream service
const vals = await storage.list<string>({ reverse: true, limit: 1 });
vars.count = vals.size === 0 ? 0 : parseInt(vals.keys().next().value);

app.post("/", async (c) => {
vars.count++;

const currentAlarm = await storage.getAlarm();
if (currentAlarm == null) {
await storage.setAlarm(Date.now() + 10 * SECONDS);
}

await storage.put(vars.count.toString(), await c.req.text());
return c.json({ queued: vars.count });
});
}).alarm(async ({ storage }, vars) => {
const vals = await storage.list<string>();
let query = "INSERT INTO batcher (data) VALUES ";
const params: string[] = [];
for (const value of vals.values()) {
query += "(?),";
params.push(value);
}
query = query.slice(0, -1);
await vars.env.DB.prepare(query)
.bind(...params)
.run();
await storage.deleteAll();
vars.count = 0;
});
7 changes: 5 additions & 2 deletions examples/batcher/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { Hono } from "hono";

const app = new Hono<{
export interface Env {
Bindings: {
BATCHER: DurableObjectNamespace;
DB: D1Database;
};
}>();
}

const app = new Hono<Env>();

app.all("/batcher/*", (c) => {
const id = c.env.BATCHER.idFromName("Batcher");
Expand Down

0 comments on commit fa4166d

Please sign in to comment.