Keystone 自定义字段开发全指南:从后端 `fieldType` 到 Admin UI 视图的完整实现

原创2026-09-23 13:34:221,745 阅读
文章标签:后端

Keystone 自定义字段开发全指南:从后端 fieldType 到 Admin UI 视图的完整实现

Keystone 内置了一批开箱即用的字段类型(如 text、integer、relationship 等),但真实业务往往需要更专门的字段形态。本文以当前仓库中 docs/content/docs/guides/custom-fields.md 为核心指南,完整讲解如何从零定义一个自定义字段类型 myInt(完整复刻内置 integer 字段),并深入源码剖析 fieldType、GraphQL 输入输出、控制器(controller)、Field/Cell 视图组件等底层实现,同时结合 examples/custom-field 示例项目给出可直接落地的实战方案。

读完本文,你将掌握:自定义字段后端的配置骨架(DB 字段、GraphQL 输入输出、索引与校验)、前端视图的四个核心导出(controller、Field、Cell,以及可选的 filter)、如何通过 getAdminMeta 把后端元数据传递给前端,以及如何在 schema 中接入自研字段并让 Keystone Admin UI 与 GraphQL API 完整可用。

为什么需要自定义字段:思路与适用场景

Keystone 为常见数据形态提供了丰富的 字段类型 集合。当出现以下两种情况时,官方字段无法直接满足需求:

  • 需要官方没有的字段类型(例如评分、颜色选择器、坐标对等业务化字段);
  • 需要对现有字段做专业化改造(例如限制取值范围、自定义 UI 交互、把多个数据库列组合成一个逻辑字段)。

此时就应该定义自己的自定义字段类型。Keystone 官方推荐的做法是:以现有字段类型为起点,针对你的用例做针对性修改——而不是从零搭建全部基础设施。这一点在仓库中体现得非常直接:examples/custom-field 示例中的 stars 字段就是基于内置 integer 字段改造而来的(其源码注释明确写着 "this field is based on the integer field",见 examples/custom-field/2-stars-field/index.ts)。

一个字段类型由两大部分组成:

部分 职责
后端(Backend) 定义数据在数据库中的存储形态,以及它在 GraphQL API 中的呈现方式
前端(Frontend) 定义字段在 Admin UI 中的外观与交互行为

提示:想要获得更多灵感,可以阅读仓库中 Keystone 内置字段的源码 packages/core/src/fields/types 目录,以及 examples/custom-field 示例项目。本文以下内容基本沿用原指南中 myInt 的例子,并对照这两个源码位置逐层展开。

后端部分:字段类型的入口

后端是字段类型的入口。我们定义一个字段函数 myInt 以及对应的配置类型 MyIntFieldConfig,它声明了该字段接受的配置项。从仓库中内置 integer 的源码(packages/core/src/fields/types/integer/index.ts)可以看到,IntegerFieldConfig 由 CommonFieldConfig(提供 access、hooks、ui、label 等通用配置)与字段特有配置(如 isIndexed、defaultValue、validation、db)组合而成。下面的 myInt 就是这一结构的精简版:

import {
  BaseListTypeInfo,
  FieldTypeFunc,
  CommonFieldConfig,
  fieldType,
  orderDirectionEnum,
} from '@keystone-6/core/types'
import { g } from '@keystone-6/core'

export type MyIntFieldConfig<ListTypeInfo extends BaseListTypeInfo> =
  CommonFieldConfig<ListTypeInfo> & {
    isIndexed?: boolean | 'unique'
  }

export function myInt <ListTypeInfo extends BaseListTypeInfo>({
  isIndexed,
  ...config
}: MyIntFieldConfig<ListTypeInfo> = {}): FieldTypeFunc<ListTypeInfo> {
  return meta =>
    fieldType({
      kind: 'scalar',
      mode: 'optional',
      scalar: 'Int',
      index: isIndexed === true ? 'index' : isIndexed || undefined,
    })({
      ...config,
      input: {
        create: { arg: g.arg({ type: g.Int }) },
        update: { arg: g.arg({ type: g.Int }) },
        orderBy: { arg: g.arg({ type: orderDirectionEnum }) },
      },
      output: g.field({ type: g.Int }),
      views: './view',
    })
}

几个值得注意的细节:

  • 字段函数接收配置对象(带默认值 = {}),返回一个以 meta 为参数的函数,meta 中带有 listKey、fieldKey 等上下文信息(仓库源码中的校验错误信息就是用它拼接的,见 packages/core/src/fields/types/integer/index.ts)。
  • 返回值的类型是 FieldTypeFunc<ListTypeInfo>,泛型参数让字段配置能与 List 的 TypeInfo 保持类型安全。
  • ...config 透传 CommonFieldConfig 中的公共配置(access、hooks、ui 等),这与 stars 示例中 "this passes through all of the common configuration like access control and etc." 的注释(examples/custom-field/2-stars-field/index.ts)完全一致。

DB Field:定义数据库存储形态

fieldType 的第一个参数被称为 db field,它定义了字段在数据库中如何存储。上面的例子中使用了 scalar: 'Int',但 DBField 还有其他形态,全部定义在 packages/core/src/types/next-fields.ts 的类型定义中。

结合内置 integer 的源码(packages/core/src/fields/types/integer/index.ts),db field 中常用的属性包括:

属性 含义 取值示例
kind 字段形态 'scalar'、'enum'、'relationship' 等
mode 是否可空 'optional'(允许 null)或 'required'
scalar Prisma 标量类型 'Int'、'String'、'Boolean'、'Float'、'DateTime' 等
index 是否建索引 'index' 或 'unique'
default 数据库层默认值 { kind: 'literal', value } 或 { kind: 'autoincrement' }
map 映射到数据库中的列名 字符串
extendPrismaSchema 扩展生成的 Prisma schema 函数

从源码可以看出,index: isIndexed === true ? 'index' : isIndexed || undefined 这行把布尔值 true 归一化为 'index',同时透传 'unique' 字符串——这一逻辑在 myInt 与内置 integer 中完全相同。

输入(Inputs):GraphQL 写入侧的接口

input 对象定义了字段类型的 GraphQL 输入。它通常包含三部分:

input: {
  create: { arg: g.arg({ type: g.Int }) },
  update: { arg: g.arg({ type: g.Int }) },
  orderBy: { arg: g.arg({ type: orderDirectionEnum }) },
},
  • create / update:分别对应创建与更新操作中写入该字段的 GraphQL 参数;
  • orderBy:对应列表排序时使用的排序方向枚举(orderDirectionEnum 提供 asc / desc)。

这些输入都是可选的——如果某个输入对字段类型没有意义,完全可以省略(stars 示例源码注释也明确说明了这一点:"all of these inputs are optional if they don't make sense for a particular field type",见 examples/custom-field/2-stars-field/index.ts)。

输入 resolver:你还可以为输入提供 resolve 函数,把从 GraphQL 收到的值转换成传给 Prisma 的值:

input: {
  create: { arg: g.arg({ type: g.Int }), resolve: (val, context) => val },
  update: { arg: g.arg({ type: g.Int }), resolve: (val, context) => val },
  orderBy: { arg: g.arg({ type: orderDirectionEnum }), resolve: (val, context) => val },
},

关于 resolve 返回值语义,stars 示例的注释给出了权威解释(examples/custom-field/2-stars-field/index.ts):

  • 返回 null:该字段将被设为数据库中的 null;
  • 返回 undefined:表示请求中省略了该字段,即"不改变现有值"(注意这意味着每次更新 item 时此函数都会被调用,即使该字段未被更新);
  • 返回具体数值:直接写入。

内置 integer 的 create resolver(packages/core/src/fields/types/integer/index.ts)还会处理默认值与自增逻辑:值未提供时回落到 defaultValue,若默认值为 'autoincrement' 则返回 undefined 交由数据库生成。

输出(Output):GraphQL 读取侧的接口

output 字段定义了可以从该字段读取什么:

output: g.field({ type: g.Int })

同样可以提供一个 resolver:

output: g.field({
  type: g.Int,
  resolve({ value, item }, args, context, info) {
    return value
  }
})

如果只是原样返回数据库中的值,resolver 可以省略——stars 示例特意在源码中保留了无操作 resolver 并注释 "providing the resolver is unnecessary if you're just returning the value"(examples/custom-field/2-stars-field/index.ts),用来说明你可以在输出层做任意值变换。

前端部分:视图(views)与四个核心导出

前端部分必须放在独立文件中,由后端通过 views 选项指向它。views 的值按"从项目目录下某个文件导入"的方式来解析:

views: './view',

也就是说,后端字段文件所在目录下的 view.tsx(或示例中的 ./2-stars-field/views)就是这个字段的视图文件。视图文件需要导出 controller、Field、Cell 三个(filter 可选)成员,分别对应不同的 Admin UI 场景:

导出 使用场景
controller 字段前端的功能核心:数据序列化/反序列化、校验、GraphQL 查询字段
Field 条目详情页(item view)与创建弹窗(create modal)中的编辑组件
Cell 列表视图(list view)表格中的只读展示组件
filter(可选) 列表筛选器 UI 与 GraphQL 筛选条件生成

Controller:数据与 Admin UI 之间的桥梁

controller 导出定义了字段前端的功能部分。它接收 FieldControllerConfig,返回一个控制器对象:

// view.tsx

export const controller = (config: FieldControllerConfig): FieldController<string, string> => {
  return {
    path: config.path,
    label: config.label,
    graphqlSelection: config.path,
    defaultValue: '',
    deserialize: data => {
      const value = data[config.path]
      return typeof value === 'number' ? value + '' : ''
    },
    serialize: value => ({ [config.path]: value === '' ? null : parseInt(value, 10) }),
  }
}

各成员职责:

  • path / label:字段路径与展示名,直接取自 config;
  • graphqlSelection:从 GraphQL 查询中取该字段时使用的选择字段,这里直接使用 config.path;
  • defaultValue:创建新条目时该字段的初始值;
  • deserialize(data):把从 GraphQL 查到的原始值转换成控制器内部值(myInt 把 number 转成字符串以配合输入框展示,空值转为 '');
  • serialize(value):把控制器内部值转换回写入 GraphQL 的对象(空字符串转 null,否则用 parseInt 转回整数)。

对照真实的内置 integer 控制器(packages/core/src/fields/types/integer/views/index.tsx)可以看到,生产级控制器还会暴露 filter、validate 以及通过 getAdminMeta 传递过来的 validation、hasAutoIncrementDefault 等增强能力。stars 示例的控制器(examples/custom-field/2-stars-field/views.tsx)则展示了控制器如何携带自定义元数据:

export function controller(
  config: FieldControllerConfig<{ maxStars: number }>
): FieldController<number | null, string> & { maxStars: number } {
  return {
    fieldKey: config.fieldKey,
    label: config.label,
    description: config.description ?? '',
    maxStars: config.fieldMeta.maxStars,
    defaultValue: null,
    deserialize: data => {
      const value = data[config.fieldKey]
      return typeof value === 'number' ? value : null
    },
    serialize: value => ({ [config.fieldKey]: value }),
    validate: value => value === null || (value >= 0 && value <= config.fieldMeta.maxStars),
    graphqlSelection: config.fieldKey,
  }
}

注意这里的 config.fieldMeta.maxStars——它正是由后端 getAdminMeta() 返回的:

getAdminMeta() {
  return { maxStars } satisfies Parameters<typeof controller>[0]['fieldMeta']
}

(见 examples/custom-field/2-stars-field/index.ts)。getAdminMeta 是后端与前端共享字段元数据的关键机制:后端在构建 schema 时调用它,把结果注入到前端的 fieldMeta 中,从而让 maxStars 等后端配置直接驱动前端校验逻辑(validate: value => value === null || (value >= 0 && value <= config.fieldMeta.maxStars))。内置 integer 同样通过 getAdminMeta 下发 min/max 校验范围与默认值(packages/core/src/fields/types/integer/index.ts)。

Field:编辑组件

Field 导出是一个 React 组件,用在**条目详情页(item view)和创建弹窗(create modal)**中,让用户查看和编辑字段值:

// view.tsx

import { TextField } from '@keystar/ui/text-field'

export function Field ({ field, value, onChange, autoFocus }: FieldProps<typeof controller>) {
  const disabled = onChange === undefined

  return (
    <TextField
      autoFocus={autoFocus}
      description={field.description}
      label={field.label}
      isDisabled={disabled}
      onChange={x => onChange?.(x === '' ? null : x)}
      value={value ?? ''}
    />
  )
}

关键点:

  • onChange === undefined 表示当前用户对该字段没有写权限(如 access control 限制),此时组件应渲染为只读/禁用形态;
  • 组件基于 @keystar/ui 设计系统构建(TextField 来自 @keystar/ui/text-field),保证与 Admin UI 其他部分视觉一致;
  • stars 示例则展示了另一种输入形态:用自定义的 <input> 放大字号渲染,并套用 KeystarField 的 label/description/readOnly 语义(examples/custom-field/2-stars-field/views.tsx),证明 Field 组件拥有完全自由的交互设计空间。

Cell:列表视图中的只读展示

Cell 导出是可选的 React 组件,用于在列表视图表格中格式化展示字段值。它不允许修改值:

// view.tsx

import { CellLink, CellContainer } from '@keystone-6/core/admin-ui/components'
import { CellComponent } from '@keystone-6/core/types'

export const Cell: CellComponent<typeof controller> = ({ value }) => {
  return <CellContainer>{value}</CellContainer>
}

CellContainer(以及可选的 CellLink,当列表存在到条目详情页的链接时使用)来自 @keystone-6/core/admin-ui/components,确保单元格渲染与列表视图既有样式一致。

实战:把自定义字段接入 schema

以仓库中的 examples/custom-field 为例,自定义字段的实际接入方式如下。

第一步:实现字段后端。2-stars-field/index.ts 中导出 stars 字段函数(核心差异点在于用 validate hooks 保证评分值在 0-maxStars 范围内,见 examples/custom-field/2-stars-field/index.ts 与 hooks 部分 L55-L71)。这也是后端改造内置字段时最典型的做法:复用 fieldType 的标量存储,叠加自己的校验逻辑。

第二步:实现字段视图。2-stars-field/views.tsx 导出 Field 与 controller,后端通过 views: './2-stars-field/views' 指向它(examples/custom-field/2-stars-field/index.ts)。

第三步:在 schema 中使用。在列表定义中像使用内置字段一样调用:

import { stars } from './2-stars-field'

export const lists = {
  Post: list({
    access: allowAll,
    fields: {
      rating: stars({
        ui: {
          description: 'A star rating, with a scale of 5',
        },
      }),
      // ...其他字段
    },
  }),
} satisfies Lists

(完整示例见 examples/custom-field/schema.ts。)examples/custom-field 同时展示了多种字段设计形态,可对照研读:

子目录 设计要点
1-text-field 基于 text 的字段,演示基本改造
2-stars-field 基于 integer 的 5 星评分,含 maxStars 元数据传递
3-pair-field 一个逻辑字段映射两个数据库列(如 "foo bar")
3-pair-field-nested 两个字符串、两个数据库字段的 pair 变体
3-pair-field-json 两个字符串、一个 JSON 数据库字段的 pair 变体
4-conditional-field 依赖其他字段值(如 rating ≥ 3 才出现的条件字段)

第四步:配置数据库并运行。示例使用 SQLite 作为默认数据库(examples/custom-field/keystone.ts),按惯例执行 schema 生成/迁移后启动开发服务器,即可在 Admin UI 中看到新的 rating 字段,并通过 GraphQL API 的 create/update/orderBy 输入读写它。示例项目根目录的 package.json 中列出了完整的依赖与启动脚本。

进阶:从 myInt 到生产级字段还需补什么

对照内置 integer(packages/core/src/fields/types/integer/index.ts),一个可直接上生产的自定义字段通常还要补齐以下能力:

  1. 校验 hooks:内置 integer 用 makeValidateHook 把 isRequired、min/max 校验挂到 hooks.validate 上,并在配置阶段对默认值、min/max 做合法性检查(抛出带 listKey.fieldKey 上下文的错误,见 packages/core/src/fields/types/integer/index.ts)。stars 字段则直接在 hooks.validate.create/update 中拦截越界值(examples/custom-field/2-stars-field/index.ts)。
  2. 筛选能力(filter):内置 integer 通过 input.where 接入字段过滤器(filters<a href="https://link.gitcode.com/i/bea1aa99e5ef1bb10e49deaddd601a5f" target="_blank">meta.provider].Int[mode]),并在控制器中提供 filter 对象(含 Filter 组件、graphql 生成、types 声明、Label 展示,见 [packages/core/src/fields/types/integer/views/index.tsx),让列表页可按该字段筛选。
  3. uniqueWhere:当 isIndexed: 'unique' 时,内置 integer 会额外暴露 uniqueWhere 输入,使该字段可参与按唯一值查询。
  4. 默认值与 db 层细节:defaultValue(含 'autoincrement')、db.isNullable、db.map、db.extendPrismaSchema 等按需支持。
  5. 遥测标识:内置字段还会设置 __ksTelemetryFieldTypeName 用于遥测统计。

小结

自定义字段是 Keystone 扩展能力的核心手段之一。核心流程可归纳为:后端用 fieldType 定义数据库存储与 GraphQL 输入输出 → 用 getAdminMeta 向视图传递元数据 → 前端在独立视图文件中导出 controller/Field/Cell(及可选 filter)→ 在 schema 中像内置字段一样使用。以现有字段为起点做增量改造(存储复用、逻辑叠加),是官方推荐且示例反复验证的稳妥路线。

想深入研究的读者,推荐按以下路径阅读仓库源码:

登录后查看全文
keystone