@brickkit/crud

中文文档
0.13.1发布于 2026/11/07MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 2958

Opt-in resource CRUD plugin for Brick

原始使用文档
文档目录5 节
  1. Field policies
  2. Operations and routes
  3. Hooks and transactions
  4. Local vs HTTP row precision
  5. Security properties

@brickkit/crud

Opt-in auto-CRUD resource plugin for Brick-TS. Core resources declare identity and a table but register no actions; crud() adds typed list/get/create/ update/delete/findOne/count/exists operations with HTTP routes.

You need Bun 1.2 or later and @brickkit/core as a peer dependency.

bun add @brickkit/crud @brickkit/core
import { defineService } from "@brickkit/core";
import { crud } from "@brickkit/crud";

const service = defineService("pages");
const page = service.resource({ name: "page", table: pages, id: pages.id }).use(
  crud({
    access: "public",
    fields: {
      id: { read: true, filter: ["eq", "in"] },
      title: {
        read: true,
        create: true,
        update: true,
        filter: ["eq", "contains"],
        sort: true,
      },
    },
  }),
);

await page.list.run({ where: { field: "title", op: "contains", value: "Hi" } });

access is required: use "public" or an authorize/scope policy.

authorize receives validated input as an operation-discriminated union. Checking operation narrows input to that operation's shape:

crud({
  fields: { teamId: { read: true, filter: ["eq"] } },
  access: {
    authorize: ({ operation, input, ctx }) => {
      if (operation === "list" && input.where && "field" in input.where) {
        const filter = input.where;
        return filter.field === "teamId" && filter.value === ctx.teamId;
      }
      return false;
    },
  },
});

CrudAuthorizeArgs<F> and CrudInputs<F> are exported for reusable policies and per-operation inputs, with F supplied as typeof fields. Field policies constrain selections, writes, sorting, and filter operators. Explicit field schemas provide value types. Column-derived values and IDs remain unknown because crud() receives the table only when the plugin attaches to a resource. Create properties remain optional because column defaults and nullability are also unavailable at configuration time. scope still receives only { operation, ctx }. Unlisted fields and omitted permissions stay disabled.

Field policies

read, create, update, filter, and sort are independent. Unlisted fields and omitted permissions are disabled. schema overrides validation for a field; scrub transforms returned values (reads and write results) without changing stored values.

Filter operators must be enabled per field and compatible with the column type: text operators (contains, startsWith, endsWith) require string columns; ordered operators (gt, gte, lt, lte, between) require string/number/date/bigint columns. Sorting is supported for string/number/boolean/date/bigint columns.

Operations and routes

MethodPathAction
POST/api/page/querylist
GET/api/page/:idget
POST/api/pagecreate
PATCH/api/page/:idupdate
DELETE/api/page/:iddelete
POST/api/page/find-onefindOne
POST/api/page/countcount
POST/api/page/existsexists
POST/api/page/bulk-createbulkCreate
POST/api/page/bulk-updatebulkUpdate
POST/api/page/bulk-deletebulkDelete

operations: { delete: false } (or operations: false) removes local capabilities. routes: { list: false } (or routes: false) keeps local actions callable without HTTP, OpenAPI, or browser exposure. defaultLimit (default 20) and maxLimit (default 100) bound pagination.

The bulk operations are off until operations sets them to true. bulkCreate takes { items }, bulkUpdate takes { items: [{ id, data }] } and bulkDelete takes { ids }. Each item is validated, authorized, scoped and hooked as its single-row operation would be. The whole batch is one transaction: when an item fails, nothing is kept, and the error carries the item's code and details: { index, code, message }. maxBatchSize (default 100) caps the items per call.

Hooks and transactions

beforeCreate, afterCreate, beforeUpdate, afterUpdate, beforeDelete and afterDelete run inside the write's transaction and receive it as tx. Write other tables through tx, or call another resource with { ...ctx, db: tx }, and the writes commit or roll back with the row. A hook that throws rolls the whole operation back. afterCommit runs after the commit, for cache clears and realtime publishes. Its errors are logged, not returned.

Local vs HTTP row precision

Local list/get actions are typed Selected<T, F, S> — the select projection narrows the return type. Over HTTP every readable key is optional in the row schema because select projections omit keys, so validate presence client-side when using select.

Security properties

  • Only allowlisted fields, operators, and sort columns reach SQL; unknown projections, writes, filters, and ordering fail validation with a 400.
  • where supports nested and/or arrays up to 20 levels; deeper nesting is rejected with a 400 before validation recurses.
  • contains/startsWith/endsWith escape LIKE wildcards (%, _, \).
  • access.scope constrains every read and mutation (including local action calls); scoped creation is rejected without an explicit create policy.
  • Unique violations return 409 without leaking driver errors.
  • Read queries reuse bounded prepared statements (128-entry cache) where the driver supports them.

See the resources guide for the full guide.

版本与发布记录

@brickkit/crud 共发布 23 个版本,首次发布于 2026/10/11;过去 12 个月发布了 23 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.13.1latest2026/11/071 天前
0.13.02026/11/071 天前
0.12.02026/11/053 天前
0.11.02026/10/309 天前
0.10.02026/10/309 天前
0.9.12026/10/2613 天前

其他发布通道:beta → 0.3.0-beta.5。

关于 @brickkit/crud 的常见问题

@brickkit/crud 是什么?

Opt-in resource CRUD plugin for Brick

如何安装 @brickkit/crud?

在项目目录运行 npm install @brickkit/crud,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:drizzle-orm(^0.45.2)、@brickkit/core(^0.13.1)、@sinclair/typebox(^0.34.52)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@brickkit/crud 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@brickkit/crud 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@brickkit/crud 可以商用吗?

@brickkit/crud 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@brickkit/crud 的下载量有多少?

根据 npm 官方下载统计,@brickkit/crud 在 2026/10/09 – 2026/11/07 这 30 天内被下载 2,958 次,日均约 99 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@brickkit/crud 还在维护吗?

最新版本 0.13.1 发布于 2026/11/07(1 天前);至今共发布 23 个版本,其中过去 12 个月发布了 23 个;首次发布于 2026/10/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。