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(dbPluginsetup)app/admin.server.ts(createDbForAdmin)- any route handler that built
Dbad-hoc fromenv.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’sdb: createDbForAdminconfig:db: appDb- any route handler:
const db = appDb(ctx.grants, ctx.user)
Type Parameters
Section titled “Type Parameters”TSchema
Section titled “TSchema”TSchema extends Record<string, unknown>
Parameters
Section titled “Parameters”config
Section titled “config”AppDbConfig<TSchema>
Returns
Section titled “Returns”AppDbFactory<TSchema>
Example
Section titled “Example”// app/db/factory.ts -- defined onceimport { 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 pluginconst dbPlugin = definePlugin({ name: "db", requires: [authPlugin], setup(ctx) { return { client: appDb(ctx.auth.grants, ctx.auth.user) }; },});
// app/admin.server.ts -- consume from adminconst adminConfig = { db: appDb, // (grants, user) => Db -- already the right shape ...};