Redwood 框架的 RedwoodRecord 使用指南:基于 Prisma 构建的 ActiveRecord 风格 ORM

Redwood 框架的 RedwoodRecord 使用指南:基于 Prisma 构建的 ActiveRecord 风格 ORM

【免费下载链接】redwood RedwoodGraphQL 【免费下载链接】redwood 项目地址: https://gitcode.com/gh_mirrors/re/redwood

RedwoodRecord 是 Redwood 框架中一套基于 Prisma 构建的 ORM(对象关系映射)层,它深受 Ruby on Rails 中 ActiveRecord 的启发,让开发者以接近自然语言的方式操作数据库中的记录,而无需关心 SQL 语法细节。本文将以 Redwood 仓库中 redwoodrecord.md 文档为主线,结合 @redwoodjs/record 包的源码实现,系统讲解模型定义、record init 初始化流程、CRUD 操作、验证、错误处理与关系代理的完整用法,帮助你直接在 api 侧 Service 或脚本中高效访问数据库。

注意:RedwoodRecord 目前仍被官方标记为 Experimental(实验性) 功能,官方希望社区在真实项目中使用它并提供反馈,以帮助完善其开发体验。在关键路径上使用前请评估风险。

背景与术语:从数据表关系说起

RedwoodRecord 的使用建立在“为每个要访问的数据库表创建类”的基础上。以博客系统为例,假设有三张表:User、Post 与 Comment,它们之间存在一对多(one-to-many)关系:

┌───────────┐       ┌────────────┐      ┌────────────┐
│   User    │       │    Post    │      │  Comment   │
├───────────┤       ├────────────┤      ├────────────┤
│ id        │•──┐   │ id         │•──┐  │ id         │
│ name      │   └──<│ userId     │   └─<│ postId     │
│ email     │       │ title      │      │ name       │
└───────────┘       │ body       │      │ message    │
                    └────────────┘      └────────────┘

图中从左到右,• 表示“一”的一侧,< 表示“多”的一侧:一个 User 可以拥有多个 Post,一个 Post 可以拥有多个 Comment。反过来从右往左读,可以说一个 Comment 属于(belongs to) 一个 Post(它持有外键 postId,即 Comment.postId → Post.id),一个 Post 属于一个 User(Post.userId → User.id)。

除了一对多,还存在**多对多(many-to-many)**关系,例如 Product 与 Category:一个 Product 可以有多个 Category,一个 Category 也会连接多个 Product:

┌───────────┐       ┌────────────┐
│  Product  │       │  Category  │
├───────────┤       ├────────────┤
│ id        │>─────<│ id         │
│ name      │       │ name       │
│ upc       │       │ shelf      │
└───────────┘       └────────────┘

这两张表都没有对方的 productId / categoryId 外键,如何保持彼此关联?通常需要一张连接表(join table),同时引用两侧的外键:

┌───────────┐      ┌───────────────────┐       ┌────────────┐
│  Product  │      │  ProductCategory  │       │  Category  │
├───────────┤      ├───────────────────┤       ├────────────┤
│ id        │•────<│ productId         │   ┌──•│ id         │
│ name      │      │ categoryId        │>──┘   │ name       │
│ upc       │      └───────────────────┘       │ shelf      │
└───────────┘                                  └────────────┘

这样又回归到了一对多关系。在 Prisma 中:

  • 隐式多对多(implicit many-to-many):连接表由 Prisma 自动创建和维护,表名形如 _CategoryToPost,外键被简单命名为 A 和 B,分别指向两侧表。对应官方文档中的 implicit many-to-many relations。
  • 显式多对多(explicitly many-to-many):你自己创建连接表,并可以在其中存放额外数据(例如商品被归类的时刻)。此时两侧都退化为“一对多”:Product 拥有多个 ProductCategory,Category 也拥有多个 ProductCategory。

文档中标注了一个 TODO:未来将支持在显式多对多中直接从 product 拿到 categories,而无需手动穿越 ProductCategory:

// 现在的写法(需要两步)
const product = await Product.find(1)
const productCategories = await product.productCategories.all()
const categories = productCategories.map(async (pc) => await pc.categories.all()).flat()

// 规划中的写法
const product = await Product.find(1)
const categories = await product.categories.all()

最后需要区分两个高频术语:model(模型) 与 record(记录)。model 是代表一张数据库表的类(上述例子中有 User、Post、Comment 三个模型;注意 Prisma 在 schema.prisma 中把每张表声明也叫 model,但本文所说的 model 特指继承 RedwoodRecord 的类);record 则是模型的一个实例,代表表中的一行数据。即:用 User 模型去查找某个用户,找到后手里就是一个 user record。

快速上手:安装与模型初始化

安装包

RedwoodRecord 运行在 api 侧,通过 workspace 添加依赖:

yarn workspace api add @redwoodjs/record

从 packages/record/package.json 可以看到,该包名为 @redwoodjs/record,核心依赖包括 @prisma/client、@redwoodjs/api(提供验证与错误基类)与 @redwoodjs/project-config(用于解析项目路径)。

定义模型

针对要访问的数据库表创建一个模型类。以博客示例的 User 为例,创建 api/src/models/User.js:

import { RedwoodRecord } from '@redwoodjs/record'

export default class User extends RedwoodRecord { }

初始化 schema 缓存

接着解析 Prisma schema、缓存为 JSON 文件,并生成带配置的 index.js:

yarn rw record init

执行后会在 api/src/models/ 下生成 datamodel.js(schema 的 JSON 缓存)和 index.js(模型装配文件)。

从 packages/record/src/tasks/parse.js 的源码可以看到这个命令做了三件事:

  1. 通过 getSchema(getPaths().api.dbSchema) 读取 schema.prisma,再用 Prisma 官方的 getDMMF 解析为 datamodel 结构,经 esbuild 转成 CJS 后写入 api/src/models/datamodel.js;
  2. 扫描 api/src/models 目录(排除 index.js 与 datamodel.js),为每个模型生成 import 语句,并依据 datamodel 中 kind === 'object' 的字段推断模型间的依赖,写出 xxx.requiredModels = [...];
  3. 在 index.js 中把 RedwoodRecord.db = db、RedwoodRecord.schema = datamodel 以及所有模型统一导出,从而避免循环依赖。

生成的 index.js 大致结构如下(由 parse.js 的模板拼装):

// This file is autogenerated by Redwood and will be overwritten periodically

import { db } from 'src/lib/db'
import datamodel from 'src/models/datamodel'
import { RedwoodRecord } from '@redwoodjs/record'

RedwoodRecord.db = db
RedwoodRecord.schema = datamodel

在控制台(或应用内)尝试查询

模型定义好、schema 初始化完成后,就已经可以开始使用了。文档提到可以进入 Redwood 控制台做快速查询:

yarn rw c

然后在 Node REPL 中 require 模型:

const { User } = require('./api/src/models')

并执行增删改查:

await User.all()
const newUser = await User.create({ name: 'Rob', email: 'rob@redwoodjs.com' })
newUser.name = 'Robert'
await newUser.save()
await User.find(1)
await User.findBy({ email: 'rob@redwoodjs.com' })
await newUser.destroy()

注意:文档中的 TODO 说明,当时控制台环境中模型读取属性会返回 undefined(加载与抓取记录可用,但读取属性有问题),因此实验版本建议直接在应用代码中测试 RedwoodRecord。

初始化新记录:build()

要在内存中构建一条尚未落库的新记录,使用 build():

const user = User.build({ firstName: 'David', lastName: 'Price' })

build 只在内存中构造记录,因此不是异步的;而其他会与 Prisma / 数据库交互的模型方法都是异步的。从 Core.js 源码看,build 先 new this() 创建实例,再把属性整体写入 record.attributes,随后由 RedwoodRecord.build 调用 RelationProxy.addRelations 把关系代理挂到实例上。build 之后要落库,见下文 save()。

错误处理:errors、hasError 与 isValid

当记录无法保存时(无论是数据库错误还是验证错误),errors 属性会装填错误消息:

const user = User.build({ name: 'Rob Cameron' })
await user.save() // => false
user.hasError   // => true
user.errors     // => { base: [], email: ['must not be null'] }
user.errors.email // => ['must not be null']

其中 base 是 errors 对象中的特殊键,用来存放不针对单一属性的错误,例如删除一条已被他人删除的记录:

user.errors.base // => ['User record to destroy not found']

errors、hasError 与 isValid 的实现位于 ValidationMixin.js:

  • errors 是 _errors 的只读 getter(默认结构为 { base: [] });
  • hasError 是 getter,只检查当前 _errors 中是否有非空数组,不重新运行验证,因此会保留手动添加的错误;
  • isValid 是 getter,先运行 validate() 再返回 !hasError,因此会清空之前手动 addError() 的错误。

在修改记录前可以用 isValid 预检(只能拦截验证层能捕获的错误):

const user = User.build({ name: 'Rob Cameron' })
user.isValid       // => false
user.errors.email  // => ['must be formatted like an email address']

底层错误机制在 Core.js 的 _saveErrorHandler 中:它识别 Record to update not found、must not be null、is missing 等 Prisma 错误消息,将其转换为 base 或具体属性上的错误,并在传入 { throw: true } 时抛出 errors.js 中定义的 RedwoodRecordNotFoundError、RedwoodRecordNullAttributeError、RedwoodRecordMissingAttributeError 或 RedwoodRecordUncaughtError。

验证:static validates

记录在落库前可以通过验证规则检查数据合法性,规则类型与 Service Validations 保持一致(如 absence 等验证类型):

export default class User extends RedwoodRecord {
  static validates = {
    email: { presence: true, email: true },
    username: { length: { min: 2, max: 50 } }
  }
}

const user = User.build({ username: 'r' })
await user.save() // => false
user.errors.email // => ['must be present']
user.errors.username // => ['must be at least 2 characters']
user.email = 'rob@redwoodjs.com'
user.username = 'rob'
await user.save()

实现上,RedwoodRecord.save 会先调用 validate():验证通过才继续走 Core 的保存逻辑,否则直接返回 false。而 ValidationMixin.validate 会先 _clearErrors(),再遍历 static validates,逐字段调用 @redwoodjs/api 导出的 validate 函数;任何失败都会写入 errors,并在 { throw: true } 时抛出对应验证异常。验证规则本身(presence、email、length 等)由 @redwoodjs/api 提供,这也解释了 @redwoodjs/record 依赖 @redwoodjs/api 的原因。

查找记录

有时需要一次取回多条记录,有时只需要唯一一条(例如按邮箱定位用户)。RedwoodRecord 提供了如下查找方法。

where()

用于查找多条记录,返回模型记录数组。第一个参数是通常传给 Prisma findMany() 中 where 的属性;第二个可选参数是附加属性(如排序、限制):

await User.where() // 返回所有记录
await User.where({ emailPreference: 'weekly' })
await User.where({ theme: 'dark' }, { orderBy: { createdAt: 'desc' } })

all()

all() 是 where() 的同义词,但语义更明确——“我要取全部记录”(可选排序)。唯一的参数现在是附加属性:

await User.all()
await User.all({ orderBy: { lastName: 'asc' } })

从 Core.js 看,all(args) 就是 where({}, args) 的别名;而 where() 内部调用 this.accessor.findMany({ where: attributes, ...options }),并把每条结果 build 成模型实例后以 Promise.all 返回。

find()

按主键查找单条记录。默认主键是 id,可通过类定义覆盖:

export default class User extends RedwoodRecord {
  static primaryKey = 'ident'
}

该调用在记录不存在时会抛错——既然你按 ID 找用户,就默认它应该存在,不存在属于异常情况。底层使用 Prisma 的 findFirst() 实现,见 Core.find(未找到时抛出 RedwoodRecordNotFoundError):

await User.find(123)

findBy()

按条件查找单条记录。与 where() 类似,但只返回第一条匹配记录。第一个参数是传给 Prisma findFirst() 的 where 值;第二个可选参数是在选取前应用的附加属性:

await User.findBy({ email: 'rob@redwoodjs.com' })
await User.findBy({ email: { endsWith: { 'redwoodjs.com' } } }, { orderBy: { lastName: 'asc' }, take: 10 })

若没有匹配记录,返回 null。对应实现 Core.findBy 调用了 this.accessor.findFirst({ where: attributes, ...options })。

first()

first() 是 findBy() 的别名,用在代码中表达“我只要可能多条匹配记录里的第一条”:

const randomCoreMember = await User.first({ email: { endsWith: { 'redwoodjs.com' } } })

创建记录

create()

初始化一条新记录并保存。保存失败时 create 返回 false 而不是记录实例;如果即使在保存失败时也需要拿到实例,请使用上面的 build() 版本。

第一个参数是传给 Prisma create() 的数据;第二个可选参数会透传给 Prisma:

await User.create({ name: 'Tom Preston-Werner' })
await User.create({ firstName: 'Rob', email: 'rob@redwoodjs.com' }, { select: ['email'] })

从 Core.create 看,create 就是 build(attributes) 后调用 record.save(options)。

save()

对尚未落库的记录调用 save() 会新建一条记录;保存失败返回 false。也可以传入 { throw: true } 让它改为抛错。失败时可检查记录的 errors:

const user = User.build({ firstName: 'Peter', lastName: 'Pistorius' })
await user.save()
// 或
await user.save({ throw: true })
// 检查错误
user.hasError // => true
user.errors.email // => ['can't be null']

save 的判定逻辑在 Core.save:若记录已带主键则走 accessor.update,否则走 accessor.create;成功后会用数据库返回的最新属性覆盖本地 attributes,以防其他并发修改造成脏读;失败则进入 _saveErrorHandler。注意 hasError 在源码中是 getter 属性(无需括号调用)。

更新记录

更新有两种方式:1)在 update() 调用中列出所有要改的属性;2)手动逐属性赋值后调用 save()。

update()

在记录上调用 update(),第一个参数是要变更的属性;第二个可选参数是透传给 Prisma 的属性(也支持 { throw: true })。保存失败返回 false,成功则返回自身(已带上新保存的属性):

const user = await User.find(123)
await user.update({ email: 'rob.cameron@redwoodjs.com' })
// 或
await user.update({ email: 'rob.cameron@redwoodjs.com' }, { throw: true })

实现见 Core.update:先 Object.assign 合并属性到 #attributes,再复用 save()。

save()

保存对记录做出的修改。第一个可选参数包含透传给 Prisma 的属性,以及失败时抛错开关:

const user = await User.find(123)
user.email = 'rob.cameron@redwoodjs.com'
await user.save()
// 或
await user.save({ throw: true })

删除记录

当前实验版本只能先实例化再删除;文档预告后续会加入无需实例化模型的类级批量删除函数。

destroy()

在记录上调用 destroy() 删除数据库中的记录。第一个可选参数是透传给 Prisma 删除操作的属性及抛错开关。删除失败返回 false,成功返回记录自身:

const user = await User.find(123)
await user.destroy()
// 或
await user.destroy({ throw: true })

对应实现 Core.destroy 调用 accessor.delete({ where: { [primaryKey]: attributes.id }, ...rest }),并把“记录不存在”这类错误归入 base。

关系:通过 RelationProxy 访问关联数据

如背景与术语部分所述,RedwoodRecord 提供了一条从关联模型取数据的途径。要取得某个用户的所有帖子,通过关系代理(relation proxy):

const user = await User.find(123)
const posts = await user.posts.all()

这里 posts 就是代理。模型上所有常规查找方法(where()、all()、find()、findBy())都可以在关系代理上调用。不仅如此,还可以通过代理创建记录,并自动关联到父记录:

const user = await User.find(123)
const post = await user.posts.create({ title: 'Related post!' })
post.userId // => 123

从 RelationProxy.js 源码看:

  • addRelations 通过 Reflection 解析出 hasMany 与 belongsTo 两类关系,并分别用 Object.defineProperty 定义到记录实例上;
  • 一对多(hasMany)代理会把父记录主键合并进 where(如 { userId: 123 }),隐式多对多则使用 { 关系名: { some: { 主键: ... } } } 与 connect 形式的 create(见 RelationProxy.js);
  • 代理上的 where/findBy/find 都会把关系约束与调用参数合并后转发给目标模型,create 则把关系约束合并进创建数据,因此子记录会被自动打上外键。

关系发现逻辑在 Reflection.js:#parseHasMany 识别 schema 中 isList 的字段(同时从对侧模型反查外键名,foreignKey 为 null 时表示隐式多对多);#parseBelongsTo 识别带有 relationFromFields 的字段。若 schema 中定义了关系但缺少对应的 Redwood 模型类,代理会输出警告并跳过该关系。

一对多(One-to-many)

“多”的一侧通过关系代理访问:

const user = await User.find(123)
const post = await user.posts.first()
const comments = await post.comments.all()

也可以通过代理创建记录:

const user = await User.find(123)
const post = await user.posts.create({ title: 'Related post!' })

属于(Belongs-to)

belongs-to 表示持有子记录、想取父记录。由于父记录永远只有一条,因此不需要关系代理属性——只会返回唯一一条记录:

const post = await Post.first()
const user = await post.user

目前还不能通过父记录反向创建 belongs-to 记录,官方正在规划相应语法。从 RelationProxy.js 看,belongs-to 属性是一个 async get(),内部调用 model.findBy({ [primaryKey]: record[foreignKey] }),所以 await post.user 的写法成立。

多对多(Many-to-many)

隐式多对多的访问方式与一对多一致:

const product = await Product.find(123)
const categories = await product.categories.all()

显式多对多需要当作两步请求处理:先取连接表的一对多关系,再取目标数据的 belongs-to 关系:

Product -> one-to-many -> ProductCategories -> belongs-to -> Category
const product = await Product.find(123)
const productCategories = await product.productCategories.all()
const categories = await Promise.all(productCategories.map(async (pc) => await pc.category))

若要通过这种方式创建记录,需要在两侧记录都已创建/获取后,再创建连接表记录:

const product = await Product.find(123)
const category = await Category.find(234)
await ProductCategory.create({ productId: product.id, categoryId: category.id })

官方正在改进该语法,目标是让显式多对多的交互像隐式版本一样简单。

即将推出:生命周期回调(Lifecycle Callbacks)

以下能力尚在开发中,不在当前实验版提供。规划中的用法示例:为新创建的用户设置默认偏好,用 afterCreate 回调:

export default class User extends RedwoodRecord {
  static afterCreate = async (user) => {
    await user.preferences.create({ email: 'weekly' })
  }
}

或在用户注销前确保其已转移数据所有权,用 beforeDestroy 回调:

export default class User extends RedwoodRecord {
  static beforeDestroy = async (user) => {
    if (await user.teams.count() !== 0) {
      throw new Error('Please transfer ownership of your teams first')
    }
  }
}

(上述回调语法尚未定稿。)

源码结构与可进一步阅读的线索

想要深入理解 RedwoodRecord,可阅读 packages/record 包,它由 5 个类组成:

  1. Core:单一模型的核心数据库访问,提供 CRUD 能力(Core.js);
  2. Reflection:解析 Prisma datamodel,判断模型与其他模型的关系(Reflection.js);
  3. RelationProxy:通过 Reflection 暴露的关联,提供访问关联模型的能力(RelationProxy.js);
  4. ValidationMixin:增加验证支持并填充错误消息(ValidationMixin.js);
  5. RedwoodRecord:将以上四者组合成所有模型应继承的标准基类(RedwoodRecord.js)。

另有一个 errors.js 存放 RedwoodRecord 可能抛出的全部错误类型。单元测试位于 packages/record/src/redwoodrecord/tests/,其中覆盖了 reflect()、build() 挂载关系代理、save() 失败返回 false / 抛错 / 写入 errors.email 等关键行为,是理解行为边界的良好参考。

任务说明(来自包内 README):yarn rw record init 的任务需要在你新建模型、或修改 schema.prisma 从而增删了与其他模型的关系时手动重新运行。官方计划未来让该任务自动监听 schema.prisma 或 models 目录的变化,当前版本仍需手动触发。

【免费下载链接】redwood RedwoodGraphQL 【免费下载链接】redwood 项目地址: https://gitcode.com/gh_mirrors/re/redwood

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值