Skip to content

Commit

Permalink
Refactor getD1Database from wrangler → miniflare@3
Browse files Browse the repository at this point in the history
• the CLI migrate command doesn’t work if miniflare is imported statically
• adding it as a dependency ensures we get the correct types for miniflare v3.x (otherwise we get miniflare v2.x types)
• the previous version (using wrangler’s getPlatformProxy) was resulting in the following error:

service core:user:__WRANGLER_EXTERNAL_DURABLE_OBJECTS_WORKER: Worker "core:user:__WRANGLER_EXTERNAL_DURABLE_OBJECTS_WORKER"'s binding "Channel" refers to a service "core:user:worker", but no such service is defined.
  • Loading branch information
acusti committed Jul 25, 2024
1 parent fe766b9 commit 22f47d4
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 5 deletions.
37 changes: 32 additions & 5 deletions packages/superflare/cli/d1-database.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { D1Database as D1DatabaseType } from "@cloudflare/workers-types";
import { getWranglerJsonConfig } from "./config";

export async function createD1Database(
sqliteDbPath: string,
Expand All @@ -13,12 +14,38 @@ export async function createD1Database(
return db as any as D1DatabaseType;
}

export async function getD1Database(dbName: string, logger = console.log) {
type DBConfig = {
binding: string;
database_id: string;
};

export async function getD1Database(
dbName: string,
logger = console.log
): Promise<D1DatabaseType | null> {
const wranglerJsonConfig = await getWranglerJsonConfig(process.cwd());
if (!wranglerJsonConfig) {
logger("Unable to load wrangler.json");
return null;
}

const databaseId = wranglerJsonConfig.d1_databases?.find(
({ binding }: DBConfig) => binding === dbName
)?.database_id;

if (!databaseId) {
logger(`No d1_databases {"binding": "${dbName}"} item in wrangler.json`);
return null;
}

const { npxImport } = await import("npx-import");
const { getPlatformProxy } = await npxImport<typeof import("wrangler")>(
"wrangler",
const { Miniflare } = await npxImport<typeof import("miniflare")>(
"miniflare",
logger
);
const { env } = await getPlatformProxy({ experimentalJsonConfig: true });
return env[dbName] as D1DatabaseType | undefined;

const d1Databases = { [dbName]: databaseId };
const mf = new Miniflare({ d1Databases, modules: true, script: "" });

return await mf.getD1Database(dbName);
}
1 change: 1 addition & 0 deletions packages/superflare/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"@types/pluralize": "^0.0.29",
"@types/tar-fs": "^2.0.1",
"@types/yargs": "^17.0.20",
"miniflare": "^3",
"tsconfig": "workspace:*",
"tsup": "^6.6.3",
"typescript": "^5",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 22f47d4

Please sign in to comment.