Skip to content

createAppDb

createAppDb<TSchema>(config): AppDbFactory<TSchema>

Defined in: packages/db/src/create-db.ts:349

Consolidates the three near-identical createDb factories that every cfast app used to define (#149):

  • app/cfast.server.ts (dbPlugin setup)
  • app/admin.server.ts (createDbForAdmin)
  • any route handler that built Db ad-hoc from env.DB

Splits the configuration into “app constants” (D1 binding, schema, cache) and “per-request inputs” (grants, user). The returned factory captures the constants once at module load and accepts the request-scoped inputs at call time.

Use this whenever the same shape of createDb({ d1, schema, grants, user, cache }) shows up in more than one file in your app. The factory is a stable (grants, user) => Db callable that plugs directly into:

  • @cfast/core’s db plugin: setup(ctx) { return { client: appDb(ctx.auth.grants, ctx.auth.user) } }
  • @cfast/admin’s db: createDbForAdmin config: db: appDb
  • any route handler: const db = appDb(ctx.grants, ctx.user)

TSchema extends Record<string, unknown>

AppDbConfig<TSchema>

AppDbFactory<TSchema>

// app/db/factory.ts -- defined once
import { createAppDb } from "@cfast/db";
import * as schema from "./schema";
export const appDb = createAppDb({
d1: env.get().DB,
schema,
cache: false,
});
// app/cfast.server.ts -- consume from the plugin
const dbPlugin = definePlugin({
name: "db",
requires: [authPlugin],
setup(ctx) {
return { client: appDb(ctx.auth.grants, ctx.auth.user) };
},
});
// app/admin.server.ts -- consume from admin
const adminConfig = {
db: appDb, // (grants, user) => Db -- already the right shape
...
};