prisma-binding 到 Nexus
概述
注意:本指南尚未完全更新,因为它目前使用 已弃用的 版本的
nexus-plugin-prisma
。虽然这仍然可以使用,但建议使用新的nexus-prisma
库或替代的代码优先 GraphQL 库,如 Pothos 继续进行开发。如果您有任何问题,请加入我们的 Discord。
本升级指南描述了如何迁移基于 Prisma 1 且使用 prisma-binding
来实现 GraphQL 服务器的 Node.js 项目。
代码将迁移到 @nexus/schema
和 nexus-plugin-prisma
。与使用 prisma-binding
的SDL-first 方法相反,Nexus 遵循代码优先的方法来构建 GraphQL schema。您可以在这篇文章中了解这两种方法的主要区别。如果您想继续使用 SDL-first 方法,您可以按照指南从 prisma-binding
升级到 SDL-first 设置。
本指南还解释了如何从 JavaScript 迁移到 TypeScript,因此基本上假设对您现有的应用程序进行完全重写。如果您想继续在 JavaScript 中运行您的应用程序,您可以忽略与 TypeScript 设置相关的说明,并像以前一样继续使用 JavaScript。
本指南假设您已经阅读了用于升级 Prisma ORM 层的指南。这意味着您已经
- 安装了 Prisma ORM 2.0 CLI
- 创建了您的 Prisma ORM 2.0 schema
- 内省了您的数据库并解决了潜在的 schema 不兼容性
- 安装并生成了 Prisma Client
本指南进一步假设您有一个类似于以下的文件设置
.
├── README.md
├── package.json
├── prisma
│ └── schema.prisma
├── prisma1
│ ├── datamodel.prisma
│ └── prisma.yml
└── src
├── generated
│ └── prisma.graphql
├── index.js
└── schema.graphql
重要的部分是
- 一个名为
prisma
的文件夹,其中包含您的 Prisma ORM 2.0 schema - 一个名为
src
的文件夹,其中包含您的应用程序代码和一个名为schema.graphql
的 schema
如果您的项目结构不是这样的,您需要调整指南中的说明以匹配您自己的设置。
1. 安装和配置 Nexus
1.1. 安装 Nexus 依赖项
第一步是在您的项目中安装 Nexus 依赖项
npm install @nexus/schema
接下来,安装 Nexus 的 Prisma ORM 插件,这将允许您在您的 GraphQL API 中公开 Prisma 模型
npm install nexus-plugin-prisma
nexus-plugin-prisma
依赖项捆绑了所有必需的 Prisma ORM 依赖项。因此,您应该删除在升级应用程序的 Prisma ORM 层时安装的依赖项
npm uninstall @prisma/cli @prisma/client
但请注意,您仍然可以使用熟悉的命令调用 Prisma ORM 2.0 CLI
npx prisma
1.2. 配置 TypeScript
由于您将在本指南中使用 TypeScript,因此您需要添加所需的依赖项
npm install typescript ts-node-dev --save-dev
在您的项目根目录中创建一个名为 tsconfig.json
的新文件
touch tsconfig.json
现在将以下内容添加到新文件中
{
"compilerOptions": {
"skipLibCheck": true,
"strict": true,
"rootDir": "src",
"noEmit": true
},
"include": ["src/**/*"]
}
1.3. 创建您的基本 Nexus 设置
在 src
目录内创建您的 API 的根源文件,名为 index.ts
touch src/index.ts
请注意,在本指南中,您将在 index.ts
中编写整个应用程序。在实践中,您可能希望将您的 GraphQL 类型拆分到不同的文件中,如这个示例中所示。
对于一些基本设置,将此代码添加到 index.ts
import { queryType, makeSchema } from '@nexus/schema'
import { nexusSchemaPrisma } from 'nexus-plugin-prisma/schema'
import { GraphQLServer } from 'graphql-yoga'
import { createContext } from './context'
const Query = queryType({
definition(t) {
t.string('hello', () => {
return 'Hello Nexus!'
})
},
})
export const schema = makeSchema({
types: [Query],
plugins: [nexusSchemaPrisma({ experimentalCRUD: true })],
outputs: {
schema: __dirname + '/../schema.graphql',
typegen: __dirname + '/generated/nexus.ts',
},
typegenAutoConfig: {
contextType: 'Context.Context',
sources: [
{
source: '@prisma/client',
alias: 'prisma',
},
{
source: require.resolve('./context'),
alias: 'Context',
},
],
},
})
new GraphQLServer({ schema, context: createContext() }).start(() =>
console.log(`Server ready at: https://127.0.0.1:4000`)
)
请注意,此设置已经包含 Nexus 的 Prisma ORM 插件的配置。这将启用 t.model
和 t.crud
功能,您将在本指南的后面了解这些功能。
在 typegenAutoConfig
设置中,您正在提供额外的类型,以帮助您的编辑器在您开发应用程序时提供自动完成功能。现在它引用了一个名为 context.ts
的文件,该文件在您的项目中尚不存在。此文件将包含您的 context
对象的类型,该对象将传递到您的 GraphQL 解析器链中。
在 src
目录中创建新的 context.ts
文件
touch src/context.ts
现在将以下代码添加到其中
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export interface Context {
prisma: PrismaClient
}
export function createContext(): Context {
return { prisma }
}
接下来,调整您的 package.json
中的 scripts
部分,以包含以下命令
{
"scripts": {
"start": "node dist/server",
"clean": "rm -rf dist",
"build": "npm -s run clean && npm -s run generate && tsc",
"generate": "npm -s run generate:prisma && npm -s run generate:nexus",
"generate:prisma": "prisma generate",
"generate:nexus": "ts-node --transpile-only src/schema",
"dev": "ts-node-dev --no-notify --respawn --transpile-only src"
}
}
dev
脚本启动一个开发服务器,您在开发应用程序时始终应在后台运行该服务器。这很重要,因为 Nexus 在后台执行代码生成。
您可以使用以下命令启动开发服务器
npm run dev
您应该看到以下 CLI 输出
Server ready at: https://127.0.0.1:4000
您的 GraphQL 服务器现在正在 https://127.0.0.1:4000 上运行。到目前为止,它实现了一个 GraphQL 查询,您可以按如下方式发送该查询
{
hello
}
在接下来的步骤中,我们将解释如何将您现有的 SDL-first GraphQL schema(使用 prisma-binding
实现)迁移到使用 Nexus 的等效设置。
2. 创建您的 GraphQL 类型
升级过程的下一步是创建您的GraphQL 类型。在这种情况下,您的 GraphQL 类型将镜像 Prisma 模型(就像您的 prisma-binding
设置中可能也是这种情况一样)。如果 GraphQL 类型偏离 Prisma 模型,您将可以使用 Nexus API 轻松调整公开的 GraphQL 类型。
为了本指南的目的,您将把所有代码保存在单个文件中。但是,您可以根据自己的个人喜好构建文件并相应地 import
。
在 Nexus 中,GraphQL 类型通过 objectType
函数定义。导入 objectType
,然后从您的第一个 GraphQL 类型的框架开始。在本例中,我们首先将 Prisma schema 的 User
模型映射到 GraphQL
import { objectType } from 'nexus'
const User = objectType({
name: 'User',
definition(t) {
// the fields of the type will be defined here
},
})
有了这段代码,您可以开始逐个公开 User
模型的字段。您可以使用编辑器的自动完成功能来节省一些打字时间。在 definition
函数的主体内部,键入 t.model.
,然后按 CTRL+SPACE。这将弹出自动完成功能,并建议在 User
模型上定义的所有字段
请注意,t
上的 model
属性由 nexus-plugin-prisma
提供。它利用来自您的 Prisma schema 的类型信息,并允许您通过 GraphQL 公开您的 Prisma 模型。
以这种方式,您可以开始完成您的对象类型定义,直到您公开了模型的所有字段
const User = objectType({
name: 'User',
definition(t) {
t.model.id()
t.model.email()
t.model.name()
t.model.jsonData()
t.model.role()
t.model.profile()
t.model.posts()
},
})
此时,任何关系字段都可能给您 TypeScript 错误(在本例中,这将是 profile
和 posts
,它们都指向其他对象类型)。这是预期的,在您添加剩余类型后,这些错误将自动解决。
注意:请务必始终运行您使用
npm run dev
启动的 Nexus 开发服务器。它会不断更新生成的 Nexus 类型,这些类型在您保存文件时在后台启用自动完成功能。
请注意,t.model.posts
关系公开了一个 Post
对象的列表。默认情况下,Nexus 仅公开该列表的分页属性——如果您还想为该关系添加排序和过滤,则需要显式启用这些
const User = objectType({
name: 'User',
definition(t) {
t.model.id()
t.model.email()
t.model.name()
t.model.jsonData()
t.model.role()
t.model.profile()
t.model.posts({
filtering: true,
ordering: true,
})
},
})
在使用 objectType
函数定义类型后,您还需要手动将其添加到您正在使用 Nexus 构建的 GraphQL schema 中。您可以通过将其添加到作为 makeSchema
函数的选项提供的 types
中来完成此操作
export const schema = makeSchema({
types: [Query, User],
plugins: [nexusSchemaPrisma()],
outputs: {
schema: __dirname + '/../schema.graphql',
typegen: __dirname + '/generated/nexus.ts',
},
typegenAutoConfig: {
sources: [
{
source: '@prisma/client',
alias: 'prisma',
},
],
},
})
完成第一个类型后,您可以开始定义剩余的类型。
展开以查看示例数据模型的完整版本
要使用 Nexus 公开所有示例 Prisma 模型,需要以下代码
const User = objectType({
name: 'User',
definition(t) {
t.model.id()
t.model.email()
t.model.name()
t.model.jsonData()
t.model.role()
t.model.profile()
t.model.posts({
filtering: true,
ordering: true,
})
},
})
const Post = objectType({
name: 'Post',
definition(t) {
t.model.id()
t.model.createdAt()
t.model.updatedAt()
t.model.title()
t.model.content()
t.model.published()
t.model.author()
t.model.authorId()
t.model.categories({
filtering: true,
ordering: true,
})
},
})
const Profile = objectType({
name: 'Profile',
definition(t) {
t.model.id()
t.model.bio()
t.model.userId()
t.model.user()
},
})
const Category = objectType({
name: 'Category',
definition(t) {
t.model.id()
t.model.name()
t.model.posts({
filtering: true,
ordering: true,
})
},
})
请务必将所有新定义的类型包含在提供给 makeSchema
的 types
选项中
export const schema = makeSchema({
types: [Query, User, Post, Profile, Category],
plugins: [nexusSchemaPrisma()],
outputs: {
schema: __dirname + '/../schema.graphql',
typegen: __dirname + '/generated/nexus.ts',
},
typegenAutoConfig: {
sources: [
{
source: '@prisma/client',
alias: 'prisma',
},
],
},
})
您可以在 ./schema.graphql
中生成的 GraphQL schema 文件中以 SDL 格式查看当前版本的 GraphQL schema。
3. 迁移 GraphQL 操作
下一步,您可以开始将所有 GraphQL queries 和 mutations 从“之前的”GraphQL API 迁移到使用 Nexus 构建的新 API。
对于本指南,将使用以下示例 GraphQL schema
# import Post from './generated/prisma.graphql'
# import User from './generated/prisma.graphql'
# import Category from './generated/prisma.graphql'
input UserUniqueInput {
id: String
email: String
}
type Query {
posts(searchString: String): [Post!]!
user(userUniqueInput: UserUniqueInput!): User
users(where: UserWhereInput, orderBy: Enumerable<UserOrderByInput>, skip: Int, after: String, before: String, first: Int, last: Int): [User]!
}
type Mutation {
createUser(data: UserCreateInput!): User!
createDraft(title: String!, content: String, authorId: ID!): Post
updateBio(userUniqueInput: UserUniqueInput!, bio: String!): User
addPostToCategories(postId: String!, categoryIds: [String!]!): Post
}
3.1. 迁移 GraphQL 查询
在本节中,您将从 prisma-binding
迁移所有 GraphQL queries 到 Nexus。
3.1.1. 迁移 users
查询(使用 forwardTo
)
在我们的示例 API 中,示例 GraphQL schema 中的 users
查询定义和实现如下。
使用 prisma-binding
的 SDL schema 定义
type Query {
users(where: UserWhereInput, orderBy: Enumerable<UserOrderByInput>, skip: Int, after: String, before: String, first: Int, last: Int): [User]!
# ... other queries
}
使用 prisma-binding
的解析器实现
const resolvers = {
Query: {
users: forwardTo('prisma'),
// ... other resolvers
},
}
为了使用 Nexus 镜像相同的行为,您可以使用 definition
函数内部 t
变量上的 crud
属性。
与 model
类似,此属性可用,因为您正在使用 nexus-prisma-plugin
,它利用来自您的 Prisma 模型的类型信息,并在后台自动生成解析器。crud
属性还支持自动完成功能,因此您可以再次在编辑器中探索所有可用的查询
使用 nexus-prisma-plugin
转发查询
要将 users
查询添加到您的 GraphQL API,请将以下行添加到查询类型定义中
const Query = queryType({
definition(t) {
t.crud.users({
filtering: true,
ordering: true,
})
},
})
如果您正在运行 Nexus 开发服务器,您可以保存该文件,并且您的 GraphQL API 将更新以公开新的 users
查询。您还可以通过查看生成的 schema.graphql
文件中的 Query
类型来观察到这一点
type Query {
users(after: UserWhereUniqueInput, before: UserWhereUniqueInput, first: Int, last: Int, orderBy: Enumerable<UserOrderByInput>, skip: Int, where: UserWhereInput): [User!]!
}
您现在可以针对新 API 编写您的第一个查询,例如
{
users {
id
name
profile {
id
bio
}
posts {
id
title
categories {
id
name
}
}
}
}
如果您的应用程序使用 forwardTo
公开来自 Prisma ORM 的所有 CRUD 操作,您现在可以继续使用相同的方法通过 t.crud
添加所有剩余的操作。要了解如何使用 Nexus 定义和解析“自定义”查询,请继续阅读下一节。
3.1.2. 迁移 posts(searchString: String): [Post!]!
查询
posts
查询定义和实现如下。
使用 prisma-binding
的 SDL schema 定义
type Query {
posts(searchString: String): [Post!]!
# ... other queries
}
使用 prisma-binding
的解析器实现
const resolvers = {
Query: {
posts: (_, args, context, info) => {
return context.prisma.query.posts(
{
where: {
OR: [
{ title_contains: args.searchString },
{ content_contains: args.searchString },
],
},
},
info
)
},
// ... other resolvers
},
}
使用 nexus
的代码优先 schema 定义
要使用 Nexus 获得相同的行为,您需要在 queryType
中添加一个 t.field
定义
const Query = queryType({
definition(t) {
// ... previous queries
t.list.field('posts', {
type: 'Post',
nullable: false,
args: { searchString: stringArg() },
})
},
})
虽然这段代码可能在您的编辑器中给您一个类型错误,但您已经可以查看 schema.graphql
内部生成的 GraphQL schema 的 SDL 版本。您会注意到,这已经为您的 GraphQL schema 添加了正确的定义
type Query {
posts(searchString: String): [Post!]!
users(after: UserWhereUniqueInput, before: UserWhereUniqueInput, first: Int, last: Int, orderBy: Enumerable<UserOrderByInput>, skip: Int, where: UserWhereInput): [User!]!
}
但是,代码缺少实际的解析器逻辑。这就是您接下来要添加的内容。
使用 nexus
的解析器实现
您可以使用 Nexus 添加解析器,如下所示
const Query = queryType({
definition(t) {
// ... previous queries
t.list.field('posts', {
type: 'Post',
nullable: false,
args: { searchString: stringArg() },
resolve: (_, args, context) => {
return context.prisma.post.findMany({
where: {
OR: [
{
title: { contains: args.searchString },
},
{
content: { contains: args.searchString },
},
],
},
})
},
})
},
})
为了验证实现,您现在可以例如向您的 GraphQL 服务器发送以下示例查询
{
posts {
id
title
author {
id
name
}
}
}
3.1.2. 迁移 user(uniqueInput: UserUniqueInput): User
查询
在我们的示例应用程序中,user
查询定义和实现如下。
使用 prisma-binding
的 SDL schema 定义
type Query {
user(userUniqueInput: UserUniqueInput): User
# ... other queries
}
input UserUniqueInput {
id: String
email: String
}
请注意,这是一个有点牵强的示例,用于演示 input
类型与 Nexus 的用法。
使用 prisma-binding
的解析器实现
const resolvers = {
Query: {
user: (_, args, context, info) => {
return context.prisma.query.user(
{
where: args.userUniqueInput,
},
info
)
},
// ... other resolvers
},
}
使用 nexus
的代码优先 schema 定义
要使用 Nexus 获得相同的行为,您需要在 queryType
中添加一个 t.field
定义,并定义一个 inputObjectType
,其中包含您的 User
模型的两个 @unique
字段
import { inputObjectType, arg } from '@nexus/schema'
const UserUniqueInput = inputObjectType({
name: 'UserUniqueInput',
definition(t) {
t.string('id')
t.string('email')
},
})
const Query = queryType({
definition(t) {
// ... previous queries
t.field('user', {
type: 'User',
args: {
userUniqueInput: arg({
type: 'UserUniqueInput',
nullable: false,
}),
},
})
},
})
由于 UserUniqueInput
是您的 GraphQL schema 中的新类型,您需要再次将其添加到传递给 makeSchema
的 types
选项中
export const schema = makeSchema({
types: [Query, User, Post, Profile, Category, UserUniqueInput],
plugins: [nexusSchemaPrisma()],
outputs: {
schema: __dirname + '/../schema.graphql',
typegen: __dirname + '/generated/nexus.ts',
},
typegenAutoConfig: {
sources: [
{
source: '@prisma/client',
alias: 'prisma',
},
],
},
})
如果您查看 schema.graphql
内部生成的 GraphQL schema 的 SDL 版本,您会注意到此更改已经为您的 GraphQL schema 添加了正确的定义
type Query {
posts(searchString: String): [Post!]
user(userUniqueInput: UserUniqueInput!): User
users(after: UserWhereUniqueInput, before: UserWhereUniqueInput, first: Int, last: Int, orderBy: Enumerable<UserOrderByInput>, skip: Int, where: UserWhereInput): [User!]!
}
input UserUniqueInput {
email: String
id: String
}
您甚至可以通过 GraphQL Playground 发送相应的查询
{
user(userUniqueInput: { email: "[email protected]" }) {
id
name
}
}
但是,由于解析器尚未实现,您将不会获得任何数据返回。
使用 nexus
的代码优先解析器实现
那是因为您仍然缺少该查询的解析器实现。您可以使用 Nexus 添加解析器,如下所示
const UserUniqueInput = inputObjectType({
name: 'UserUniqueInput',
definition(t) {
t.string('id')
t.string('email')
},
})
const Query = queryType({
definition(t) {
// ... previous queries
t.field('user', {
type: 'User',
nullable: true,
args: {
userUniqueInput: arg({
type: 'UserUniqueInput',
nullable: false,
}),
},
resolve: (_, args, context) => {
return context.prisma.user.findUnique({
where: {
id: args.userUniqueInput?.id,
email: args.userUniqueInput?.email,
},
})
},
})
},
})
如果您重新发送之前发送的相同查询,您会发现它现在返回实际数据。
3.2. 迁移 GraphQL mutations
在本节中,您将从示例 schema 迁移 GraphQL mutations 到 Nexus。
3.2.1. 定义 Mutation
类型
迁移任何 mutations 的第一步是定义您的 GraphQL API 的 Mutation
类型。完成此操作后,您可以逐步向其添加操作。将以下定义添加到 index.ts
import { mutationType } from '@nexus/schema'
const Mutation = mutationType({
definition(t) {
// your GraphQL mutations + resolvers will be defined here
},
})
为了确保新的 Mutation
类型被 Nexus 选中,您需要将其添加到提供给 makeSchema
的 types
中
export const schema = makeSchema({
types: [Query, User, Post, Profile, Category, UserUniqueInput, Mutation],
plugins: [nexusSchemaPrisma()],
outputs: {
schema: __dirname + '/../schema.graphql',
typegen: __dirname + '/generated/nexus.ts',
},
typegenAutoConfig: {
sources: [
{
source: '@prisma/client',
alias: 'prisma',
},
],
},
})
3.2.2. 迁移 createUser
mutation(使用 forwardTo
)
在示例应用程序中,示例 GraphQL schema 中的 createUser
mutation 定义和实现如下。
使用 prisma-binding
的 SDL schema 定义
type Mutation {
createUser(data: UserCreateInput!): User!
# ... other mutations
}
使用 prisma-binding
的解析器实现
const resolvers = {
Mutation: {
createUser: forwardTo('prisma'),
// ... other resolvers
},
}
与转发 GraphQL 查询类似,您可以使用 definition
函数内部 t
变量上的 crud
属性,以便公开 Prisma 模型的完整 CRUD 功能。
与 model
类似,此属性可用,因为您正在使用 nexus-prisma-plugin
,它利用来自您的 Prisma 模型的类型信息,并在后台自动生成解析器。crud
属性在定义 mutations 时也支持自动完成功能,因此您可以再次在编辑器中探索所有可用的操作
使用 nexus-prisma-plugin
转发 mutation
要将 createUser
mutation 添加到您的 GraphQL API,请将以下行添加到查询类型定义中
const Mutation = mutationType({
definition(t) {
t.crud.createOneUser({
alias: 'createUser',
})
},
})
请注意,您的 GraphQL schema 中 mutation 的默认名称是 createOneUser
(以 t.crud
公开的函数命名)。为了将其重命名为 createUser
,您需要提供 alias
属性。
如果您正在运行 Nexus 开发服务器,您可以保存该文件,并且您的 GraphQL API 将更新以公开新的 createUser
mutation。您还可以通过查看生成的 schema.graphql
文件中的 Mutation
类型来观察到这一点
type Mutation {
createUser(data: UserCreateInput!): User!
}
您现在可以针对新 API 编写您的第一个 mutation,例如
mutation {
createUser(data: { name: "Alice", email: "[email protected]" }) {
id
}
}
如果您的应用程序使用 forwardTo
公开来自 Prisma Client 的所有 CRUD 操作,您现在可以继续使用相同的方法通过 t.crud
添加所有剩余的操作。要了解如何使用 Nexus 定义和解析“自定义” mutations,请继续阅读下一节。
3.2.3. 迁移 createDraft(title: String!, content: String, authorId: String!): Post!
查询
在示例应用程序中,createDraft
mutation 定义和实现如下。
使用 prisma-binding
的 SDL schema 定义
type Mutation {
createDraft(title: String!, content: String, authorId: String!): Post!
# ... other mutations
}
使用 prisma-binding
的解析器实现
const resolvers = {
Mutation: {
createDraft: (_, args, context, info) => {
return context.prisma.mutation.createPost(
{
data: {
title: args.title,
content: args.content,
author: {
connect: {
id: args.authorId,
},
},
},
},
info
)
},
// ... other resolvers
},
}
使用 nexus
的代码优先 schema 定义
要使用 Nexus 获得相同的行为,您需要在 mutationType
中添加一个 t.field
定义
const Mutation = mutationType({
definition(t) {
// ... previous mutations
t.field('createDraft', {
type: 'Post',
args: {
title: stringArg({ nullable: false }),
content: stringArg(),
authorId: stringArg({ nullable: false }),
},
})
},
})
如果您查看 schema.graphql
内部生成的 GraphQL schema 的 SDL 版本,您会注意到,这已经为您的 GraphQL schema 添加了正确的定义
type Mutation {
createUser(data: UserCreateInput!): User!
createDraft(title: String!, content: String, authorId: String!): Post!
}
您甚至可以通过 GraphQL Playground 发送相应的 mutation
mutation {
createDraft(title: "Hello World", authorId: "__AUTHOR_ID__") {
id
published
author {
id
name
}
}
}
但是,由于解析器尚未实现,因此不会创建新的 Post
记录,并且您不会在响应中获得任何数据返回。
使用 nexus
的解析器实现
那是因为您仍然缺少该 mutation 的解析器实现。您可以使用 Nexus 添加解析器,如下所示
const Mutation = mutationType({
definition(t) {
// ... previous mutations
t.field('createDraft', {
type: 'Post',
args: {
title: stringArg({ nullable: false }),
content: stringArg(),
authorId: stringArg({ nullable: false }),
},
resolve: (_, args, context) => {
return context.prisma.post.create({
data: {
title: args.title,
content: args.content,
author: {
connect: { id: args.authorId },
},
},
})
},
})
},
})
如果您重新发送之前发送的相同查询,您会发现它现在创建了一个新的 Post
记录并返回有效数据。
3.2.4. 迁移 updateBio(bio: String, userUniqueInput: UserUniqueInput!): User
mutation
在示例应用程序中,updateBio
mutation 定义和实现如下。
使用 prisma-binding
的 SDL schema 定义
type Mutation {
updateBio(bio: String!, userUniqueInput: UserUniqueInput!): User
# ... other mutations
}
使用 prisma-binding
的解析器实现
const resolvers = {
Mutation: {
updateBio: (_, args, context, info) => {
return context.prisma.mutation.updateUser(
{
data: {
profile: {
update: { bio: args.bio },
},
},
where: { id: args.userId },
},
info
)
},
// ... other resolvers
},
}
使用 nexus
的代码优先 schema 定义
要使用 Nexus 获得相同的行为,您需要在 mutationType
中添加一个 t.field
定义
const Mutation = mutationType({
definition(t) {
// ... previous mutations
t.field('updateBio', {
type: 'User',
args: {
userUniqueInput: arg({
type: 'UserUniqueInput',
nullable: false,
}),
bio: stringArg({ nullable: false }),
},
})
},
})
如果您查看 schema.graphql
内部生成的 GraphQL schema 的 SDL 版本,您会注意到,这已经为您的 GraphQL schema 添加了正确的定义
type Mutation {
createUser(data: UserCreateInput!): User!
createDraft(title: String!, content: String, authorId: String!): Post!
updateBio(bio: String!, userUniqueInput: UserUniqueInput!): User
}
您甚至可以通过 GraphQL Playground 发送相应的 mutation
mutation {
updateBio(
userUniqueInput: { email: "[email protected]" }
bio: "I like turtles"
) {
id
name
profile {
id
bio
}
}
}
但是,由于解析器尚未实现,因此数据库中不会更新任何内容,并且您不会在响应中获得任何数据返回。
使用 nexus
的解析器实现
那是因为您仍然缺少该查询的解析器实现。您可以使用 Nexus 添加解析器,如下所示
const Mutation = mutationType({
definition(t) {
// ... previous mutations
t.field('updateBio', {
type: 'User',
args: {
userUniqueInput: arg({
type: 'UserUniqueInput',
nullable: false
}),
bio: stringArg()
},
resolve: (_, args, context) => {
return context.prisma.user.update({
where: {
id: args.userUniqueInput?.id,
email: args.userUniqueInput?.email
},
data: {
profile: {
create: { bio: args.bio }
}
}
})
}
}
}
})
如果您重新发送之前发送的相同查询,您会发现它现在返回实际数据而不是 null
。
3.2.5. 迁移 addPostToCategories(postId: String!, categoryIds: [String!]!): Post
mutation
在我们的示例应用程序中,addPostToCategories
mutation 定义和实现如下。
使用 prisma-binding
的 SDL schema 定义
type Mutation {
addPostToCategories(postId: String!, categoryIds: [String!]!): Post
# ... other mutations
}
使用 prisma-binding
的解析器实现
const resolvers = {
Mutation: {
addPostToCategories: (_, args, context, info) => {
const ids = args.categoryIds.map((id) => ({ id }))
return context.prisma.mutation.updatePost(
{
data: {
categories: {
connect: ids,
},
},
where: {
id: args.postId,
},
},
info
)
},
// ... other resolvers
},
}
使用 nexus
的代码优先 schema 定义
要使用 Nexus 获得相同的行为,您需要在 mutationType
中添加一个 t.field
定义
const Mutation = mutationType({
definition(t) {
// ... mutations from before
t.field('addPostToCategories', {
type: 'Post',
args: {
postId: stringArg({ nullable: false }),
categoryIds: stringArg({
list: true,
nullable: false,
}),
},
})
},
})
如果您查看 schema.graphql
内部生成的 GraphQL schema 的 SDL 版本,您会注意到,这已经为您的 GraphQL schema 添加了正确的定义
type Mutation {
createUser(data: UserCreateInput!): User!
createDraft(title: String!, content: String, authorId: String!): Post!
updateBio(bio: String, userUniqueInput: UserUniqueInput!): User
addPostToCategories(postId: String!, categoryIds: [String!]!): Post
}
您甚至可以通过 GraphQL Playground 发送相应的查询
mutation {
addPostToCategories(
postId: "__AUTHOR_ID__"
categoryIds: ["__CATEGORY_ID_1__", "__CATEGORY_ID_2__"]
) {
id
title
categories {
id
name
}
}
}
但是,由于解析器尚未实现,因此数据库中不会更新任何内容,并且您不会在响应中获得任何数据返回。
使用 nexus
的解析器实现
那是因为您仍然缺少该查询的解析器实现。您可以使用 Nexus 添加解析器,如下所示
const Mutation = mutationType({
definition(t) {
// ... mutations from before
t.field('addPostToCategories', {
type: 'Post',
args: {
postId: stringArg({ nullable: false }),
categoryIds: stringArg({
list: true,
nullable: false,
}),
},
resolve: (_, args, context) => {
const ids = args.categoryIds.map((id) => ({ id }))
return context.prisma.post.update({
where: {
id: args.postId,
},
data: {
categories: { connect: ids },
},
})
},
})
},
})
如果您重新发送之前发送的相同查询,您会发现它现在返回实际数据而不是 null
。
4. 清理
由于整个应用程序现在已升级到 Prisma ORM 2.0 和 Nexus,您可以删除所有不必要的文件并删除不再需要的依赖项。
4.1. 清理 npm 依赖项
您可以从删除与 Prisma 1 设置相关的 npm 依赖项开始
npm uninstall graphql-cli prisma-binding prisma1
4.2. 删除未使用的文件
接下来,删除您的 Prisma 1 设置的文件
rm prisma1/datamodel.prisma prisma1/prisma.yml
您还可以删除任何剩余的 .js
文件、旧的 schema.graphql
和 prisma.graphql
文件。
4.3. 停止 Prisma ORM 服务器
最后,您可以停止运行您的 Prisma ORM 服务器。