prisma-binding 到 SDL-first
概述
本升级指南介绍如何迁移基于 Prisma 1 并使用 prisma-binding
实现 GraphQL 服务器的 Node.js 项目。
代码将保留 SDL-first 方法 来构建 GraphQL 模式。从 prisma-binding
迁移到 Prisma Client 时,主要区别在于 info
对象不能再用于自动解析关系,而是需要实现您自己的类型解析器以确保关系正确解析。
本指南假设您已完成 升级 Prisma ORM 层的指南。这意味着您已经
- 安装了 Prisma ORM 2 CLI
- 创建了您的 Prisma ORM 2 模式
- 内省了您的数据库并解决了潜在的模式不兼容性
- 安装并生成了 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 模式 - 一个名为
src
的文件夹,其中包含您的应用程序代码和一个名为schema.graphql
的模式
如果您的项目结构与此不同,则需要调整指南中的说明以匹配您自己的设置。
1. 调整您的 GraphQL 模式
使用 prisma-binding
,定义 GraphQL 模式(有时称为 应用程序模式)的方法是基于从生成的 prisma.graphql
文件(在 Prisma 1 中,这通常称为 Prisma GraphQL 模式)导入 GraphQL 类型。这些类型反映了您 Prisma 1 数据模型中的类型,并作为您 GraphQL API 的基础。
在 Prisma ORM 2 中,不再有可以从中导入的 prisma.graphql
文件。因此,您必须在 schema.graphql
文件中直接拼写出 GraphQL 模式的所有类型。
最简单的方法是从 GraphQL Playground 下载完整的 GraphQL 模式。为此,请打开模式选项卡,然后单击右上角的下载按钮,然后选择SDL
或者,您可以使用 GraphQL CLI 的 get-schema
命令下载完整的模式
npx graphql get-schema --endpoint __GRAPHQL_YOGA_ENDPOINT__ --output schema.graphql --no-all
注意:使用上述命令,您需要将
__GRAPHQL_YOGA_ENDPOINT__
占位符替换为您 GraphQL Yoga 服务器的实际端点。
获得 schema.graphql
文件后,将 src/schema.graphql
中的当前版本替换为新内容。请注意,这两个模式在 100% 等效,只是新模式不使用 graphql-import
从其他文件导入类型。相反,它在一个文件中拼写出所有类型。
以下是我们将在此指南中迁移的两个版本的示例 GraphQL 模式的比较(您可以使用选项卡在两个版本之间切换)
- 之前(使用 graphql-import)
- 之后(使用 Prisma 2)
# import Post from './generated/prisma.graphql'
# import User from './generated/prisma.graphql'
# import Category from './generated/prisma.graphql'
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]!
allCategories: [Category!]!
}
input UserUniqueInput {
id: String
email: String
}
type Mutation {
createDraft(authorId: ID!, title: String!, content: String!): Post
publish(id: ID!): Post
deletePost(id: ID!): Post
signup(name: String!, email: String!): User!
updateBio(userId: String!, bio: String!): User
addPostToCategories(postId: String!, categoryIds: [String!]!): Post
}
type Query {
posts(searchString: String): [Post!]!
user(id: ID!): User
users(where: UserWhereInput, orderBy: Enumerable<UserOrderByInput>, skip: Int, after: String, before: String, first: Int, last: Int): [User]!
allCategories: [Category!]!
}
type Category implements Node {
id: ID!
name: String!
posts(where: PostWhereInput, orderBy: Enumerable<PostOrderByInput>, skip: Int, after: String, before: String, first: Int, last: Int): [Post!]
}
input CategoryCreateManyWithoutPostsInput {
create: [CategoryCreateWithoutPostsInput!]
connect: [CategoryWhereUniqueInput!]
}
input CategoryCreateWithoutPostsInput {
id: ID
name: String!
}
enum CategoryOrderByInput {
id_ASC
id_DESC
name_ASC
name_DESC
}
input CategoryWhereInput {
"""Logical AND on all given filters."""
AND: [CategoryWhereInput!]
"""Logical OR on all given filters."""
OR: [CategoryWhereInput!]
"""Logical NOT on all given filters combined by AND."""
NOT: [CategoryWhereInput!]
id: ID
"""All values that are not equal to given value."""
id_not: ID
"""All values that are contained in given list."""
id_in: [ID!]
"""All values that are not contained in given list."""
id_not_in: [ID!]
"""All values less than the given value."""
id_lt: ID
"""All values less than or equal the given value."""
id_lte: ID
"""All values greater than the given value."""
id_gt: ID
"""All values greater than or equal the given value."""
id_gte: ID
"""All values containing the given string."""
id_contains: ID
"""All values not containing the given string."""
id_not_contains: ID
"""All values starting with the given string."""
id_starts_with: ID
"""All values not starting with the given string."""
id_not_starts_with: ID
"""All values ending with the given string."""
id_ends_with: ID
"""All values not ending with the given string."""
id_not_ends_with: ID
name: String
"""All values that are not equal to given value."""
name_not: String
"""All values that are contained in given list."""
name_in: [String!]
"""All values that are not contained in given list."""
name_not_in: [String!]
"""All values less than the given value."""
name_lt: String
"""All values less than or equal the given value."""
name_lte: String
"""All values greater than the given value."""
name_gt: String
"""All values greater than or equal the given value."""
name_gte: String
"""All values containing the given string."""
name_contains: String
"""All values not containing the given string."""
name_not_contains: String
"""All values starting with the given string."""
name_starts_with: String
"""All values not starting with the given string."""
name_not_starts_with: String
"""All values ending with the given string."""
name_ends_with: String
"""All values not ending with the given string."""
name_not_ends_with: String
posts_every: PostWhereInput
posts_some: PostWhereInput
posts_none: PostWhereInput
}
input CategoryWhereUniqueInput {
id: ID
}
scalar DateTime
"""Raw JSON value"""
scalar Json
"""An object with an ID"""
interface Node {
"""The id of the object."""
id: ID!
}
type Post implements Node {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
title: String!
content: String
published: Boolean!
author: User
categories(where: CategoryWhereInput, orderBy: Enumerable<CategoryOrderByInput>, skip: Int, after: String, before: String, first: Int, last: Int): [Category!]
}
input PostCreateManyWithoutAuthorInput {
create: [PostCreateWithoutAuthorInput!]
connect: [PostWhereUniqueInput!]
}
input PostCreateWithoutAuthorInput {
id: ID
title: String!
content: String
published: Boolean
categories: CategoryCreateManyWithoutPostsInput
}
enum PostOrderByInput {
id_ASC
id_DESC
createdAt_ASC
createdAt_DESC
updatedAt_ASC
updatedAt_DESC
title_ASC
title_DESC
content_ASC
content_DESC
published_ASC
published_DESC
}
input PostWhereInput {
"""Logical AND on all given filters."""
AND: [PostWhereInput!]
"""Logical OR on all given filters."""
OR: [PostWhereInput!]
"""Logical NOT on all given filters combined by AND."""
NOT: [PostWhereInput!]
id: ID
"""All values that are not equal to given value."""
id_not: ID
"""All values that are contained in given list."""
id_in: [ID!]
"""All values that are not contained in given list."""
id_not_in: [ID!]
"""All values less than the given value."""
id_lt: ID
"""All values less than or equal the given value."""
id_lte: ID
"""All values greater than the given value."""
id_gt: ID
"""All values greater than or equal the given value."""
id_gte: ID
"""All values containing the given string."""
id_contains: ID
"""All values not containing the given string."""
id_not_contains: ID
"""All values starting with the given string."""
id_starts_with: ID
"""All values not starting with the given string."""
id_not_starts_with: ID
"""All values ending with the given string."""
id_ends_with: ID
"""All values not ending with the given string."""
id_not_ends_with: ID
createdAt: DateTime
"""All values that are not equal to given value."""
createdAt_not: DateTime
"""All values that are contained in given list."""
createdAt_in: [DateTime!]
"""All values that are not contained in given list."""
createdAt_not_in: [DateTime!]
"""All values less than the given value."""
createdAt_lt: DateTime
"""All values less than or equal the given value."""
createdAt_lte: DateTime
"""All values greater than the given value."""
createdAt_gt: DateTime
"""All values greater than or equal the given value."""
createdAt_gte: DateTime
updatedAt: DateTime
"""All values that are not equal to given value."""
updatedAt_not: DateTime
"""All values that are contained in given list."""
updatedAt_in: [DateTime!]
"""All values that are not contained in given list."""
updatedAt_not_in: [DateTime!]
"""All values less than the given value."""
updatedAt_lt: DateTime
"""All values less than or equal the given value."""
updatedAt_lte: DateTime
"""All values greater than the given value."""
updatedAt_gt: DateTime
"""All values greater than or equal the given value."""
updatedAt_gte: DateTime
title: String
"""All values that are not equal to given value."""
title_not: String
"""All values that are contained in given list."""
title_in: [String!]
"""All values that are not contained in given list."""
title_not_in: [String!]
"""All values less than the given value."""
title_lt: String
"""All values less than or equal the given value."""
title_lte: String
"""All values greater than the given value."""
title_gt: String
"""All values greater than or equal the given value."""
title_gte: String
"""All values containing the given string."""
title_contains: String
"""All values not containing the given string."""
title_not_contains: String
"""All values starting with the given string."""
title_starts_with: String
"""All values not starting with the given string."""
title_not_starts_with: String
"""All values ending with the given string."""
title_ends_with: String
"""All values not ending with the given string."""
title_not_ends_with: String
content: String
"""All values that are not equal to given value."""
content_not: String
"""All values that are contained in given list."""
content_in: [String!]
"""All values that are not contained in given list."""
content_not_in: [String!]
"""All values less than the given value."""
content_lt: String
"""All values less than or equal the given value."""
content_lte: String
"""All values greater than the given value."""
content_gt: String
"""All values greater than or equal the given value."""
content_gte: String
"""All values containing the given string."""
content_contains: String
"""All values not containing the given string."""
content_not_contains: String
"""All values starting with the given string."""
content_starts_with: String
"""All values not starting with the given string."""
content_not_starts_with: String
"""All values ending with the given string."""
content_ends_with: String
"""All values not ending with the given string."""
content_not_ends_with: String
published: Boolean
"""All values that are not equal to given value."""
published_not: Boolean
author: UserWhereInput
categories_every: CategoryWhereInput
categories_some: CategoryWhereInput
categories_none: CategoryWhereInput
}
input PostWhereUniqueInput {
id: ID
}
type Profile implements Node {
id: ID!
bio: String
user: User!
}
input ProfileCreateOneWithoutUserInput {
create: ProfileCreateWithoutUserInput
connect: ProfileWhereUniqueInput
}
input ProfileCreateWithoutUserInput {
id: ID
bio: String
}
input ProfileWhereInput {
"""Logical AND on all given filters."""
AND: [ProfileWhereInput!]
"""Logical OR on all given filters."""
OR: [ProfileWhereInput!]
"""Logical NOT on all given filters combined by AND."""
NOT: [ProfileWhereInput!]
id: ID
"""All values that are not equal to given value."""
id_not: ID
"""All values that are contained in given list."""
id_in: [ID!]
"""All values that are not contained in given list."""
id_not_in: [ID!]
"""All values less than the given value."""
id_lt: ID
"""All values less than or equal the given value."""
id_lte: ID
"""All values greater than the given value."""
id_gt: ID
"""All values greater than or equal the given value."""
id_gte: ID
"""All values containing the given string."""
id_contains: ID
"""All values not containing the given string."""
id_not_contains: ID
"""All values starting with the given string."""
id_starts_with: ID
"""All values not starting with the given string."""
id_not_starts_with: ID
"""All values ending with the given string."""
id_ends_with: ID
"""All values not ending with the given string."""
id_not_ends_with: ID
bio: String
"""All values that are not equal to given value."""
bio_not: String
"""All values that are contained in given list."""
bio_in: [String!]
"""All values that are not contained in given list."""
bio_not_in: [String!]
"""All values less than the given value."""
bio_lt: String
"""All values less than or equal the given value."""
bio_lte: String
"""All values greater than the given value."""
bio_gt: String
"""All values greater than or equal the given value."""
bio_gte: String
"""All values containing the given string."""
bio_contains: String
"""All values not containing the given string."""
bio_not_contains: String
"""All values starting with the given string."""
bio_starts_with: String
"""All values not starting with the given string."""
bio_not_starts_with: String
"""All values ending with the given string."""
bio_ends_with: String
"""All values not ending with the given string."""
bio_not_ends_with: String
user: UserWhereInput
}
input ProfileWhereUniqueInput {
id: ID
}
enum Role {
ADMIN
CUSTOMER
}
type User implements Node {
id: ID!
email: String
name: String!
posts(where: PostWhereInput, orderBy: Enumerable<PostOrderByInput>, skip: Int, after: String, before: String, first: Int, last: Int): [Post!]
role: Role!
profile: Profile
jsonData: Json
}
input UserCreateInput {
id: ID
email: String
name: String!
role: Role
jsonData: Json
posts: PostCreateManyWithoutAuthorInput
profile: ProfileCreateOneWithoutUserInput
}
enum UserOrderByInput {
id_ASC
id_DESC
email_ASC
email_DESC
name_ASC
name_DESC
role_ASC
role_DESC
jsonData_ASC
jsonData_DESC
}
input UserWhereInput {
"""Logical AND on all given filters."""
AND: [UserWhereInput!]
"""Logical OR on all given filters."""
OR: [UserWhereInput!]
"""Logical NOT on all given filters combined by AND."""
NOT: [UserWhereInput!]
id: ID
"""All values that are not equal to given value."""
id_not: ID
"""All values that are contained in given list."""
id_in: [ID!]
"""All values that are not contained in given list."""
id_not_in: [ID!]
"""All values less than the given value."""
id_lt: ID
"""All values less than or equal the given value."""
id_lte: ID
"""All values greater than the given value."""
id_gt: ID
"""All values greater than or equal the given value."""
id_gte: ID
"""All values containing the given string."""
id_contains: ID
"""All values not containing the given string."""
id_not_contains: ID
"""All values starting with the given string."""
id_starts_with: ID
"""All values not starting with the given string."""
id_not_starts_with: ID
"""All values ending with the given string."""
id_ends_with: ID
"""All values not ending with the given string."""
id_not_ends_with: ID
email: String
"""All values that are not equal to given value."""
email_not: String
"""All values that are contained in given list."""
email_in: [String!]
"""All values that are not contained in given list."""
email_not_in: [String!]
"""All values less than the given value."""
email_lt: String
"""All values less than or equal the given value."""
email_lte: String
"""All values greater than the given value."""
email_gt: String
"""All values greater than or equal the given value."""
email_gte: String
"""All values containing the given string."""
email_contains: String
"""All values not containing the given string."""
email_not_contains: String
"""All values starting with the given string."""
email_starts_with: String
"""All values not starting with the given string."""
email_not_starts_with: String
"""All values ending with the given string."""
email_ends_with: String
"""All values not ending with the given string."""
email_not_ends_with: String
name: String
"""All values that are not equal to given value."""
name_not: String
"""All values that are contained in given list."""
name_in: [String!]
"""All values that are not contained in given list."""
name_not_in: [String!]
"""All values less than the given value."""
name_lt: String
"""All values less than or equal the given value."""
name_lte: String
"""All values greater than the given value."""
name_gt: String
"""All values greater than or equal the given value."""
name_gte: String
"""All values containing the given string."""
name_contains: String
"""All values not containing the given string."""
name_not_contains: String
"""All values starting with the given string."""
name_starts_with: String
"""All values not starting with the given string."""
name_not_starts_with: String
"""All values ending with the given string."""
name_ends_with: String
"""All values not ending with the given string."""
name_not_ends_with: String
role: Role
"""All values that are not equal to given value."""
role_not: Role
"""All values that are contained in given list."""
role_in: [Role!]
"""All values that are not contained in given list."""
role_not_in: [Role!]
posts_every: PostWhereInput
posts_some: PostWhereInput
posts_none: PostWhereInput
profile: ProfileWhereInput
}
您会注意到,新版本的 GraphQL 模式不仅定义了直接导入的模型,还定义了之前模式中不存在的其他类型(例如 input
类型)。
2. 设置您的 PrismaClient
实例
PrismaClient
是您在 Prisma ORM 2 中与数据库交互的新接口。它允许您调用各种方法,这些方法构建 SQL 查询并将它们发送到数据库,并将结果作为纯 JavaScript 对象返回。
PrismaClient
查询 API 的灵感来自最初的 prisma-binding
API,因此使用 Prisma Client 发送的大多数查询都会感觉很熟悉。
与 Prisma 1 中的 prisma-binding
实例类似,您也希望将 Prisma ORM 2 中的 PrismaClient
附加到 GraphQL 的 context
,以便可以在解析器中访问它
const { PrismaClient } = require('@prisma/client')
// ...
const server = new GraphQLServer({
typeDefs: 'src/schema.graphql',
resolvers,
context: (req) => ({
...req,
prisma: new Prisma({
typeDefs: 'src/generated/prisma.graphql',
endpoint: 'https://127.0.0.1:4466',
}),
prisma: new PrismaClient(),
}),
})
在上面的代码块中,红色行是要从您的当前设置中删除的行,绿色行是要添加的行。当然,您之前的设置可能与此不同(例如,如果您在生产环境中运行 API,则您的 Prisma ORM endpoint
不太可能是 https://127.0.0.1:4466
),这只是一个示例,说明它可能是什么样子。
现在,当您在解析器内部访问 context.prisma
时,您就可以访问 Prisma Client 查询。
2. 编写您的 GraphQL 类型解析器
prisma-binding
能够神奇地解析 GraphQL 模式中的关系。但是,在不使用 prisma-binding
的情况下,您需要使用所谓的类型解析器显式地解析关系。
注意 您可以在这篇文章中详细了解类型解析器的概念以及它们为何必要:GraphQL 服务器基础:GraphQL 模式、类型定义和解析器详解
2.1. 为 User
类型实现类型解析器
示例 GraphQL 模式中的 User
类型定义如下
type User implements Node {
id: ID!
email: String
name: String!
posts(
where: PostWhereInput
orderBy: Enumerable<PostOrderByInput>
skip: Int
after: String
before: String
first: Int
last: Int
): [Post!]
role: Role!
profile: Profile
jsonData: Json
}
此类型有两个关系
posts
字段表示与Post
的 1-n 关系profile
字段表示与Profile
的 1-1 关系
由于您不再使用 prisma-binding
,因此您现在需要在类型解析器中“手动”解析这些关系。
您可以通过向解析器映射添加 User
字段并实现 posts
和 profile
关系的解析器来做到这一点
const resolvers = {
Query: {
// ... your query resolvers
},
Mutation: {
// ... your mutation resolvers
},
User: {
posts: (parent, args, context) => {
return context.prisma.user
.findUnique({
where: { id: parent.id },
})
.posts()
},
profile: (parent, args, context) => {
return context.prisma.user
.findUnique({
where: { id: parent.id },
})
.profile()
},
},
}
在这些解析器内部,您使用新的 PrismaClient
对数据库执行查询。在 posts
解析器内部,数据库查询加载指定 author
(其 id
包含在 parent
对象中)的所有 Post
记录。在 profile
解析器内部,数据库查询加载指定 user
(其 id
包含在 parent
对象中)的 Profile
记录。
由于这些额外的解析器,您现在可以在 GraphQL 查询/突变中嵌套关系,无论何时您在查询中请求有关 User
类型的的信息,例如
{
users {
id
name
posts {
# fetching this relation is enabled by the new type resolver
id
title
}
profile {
# fetching this relation is enabled by the new type resolver
id
bio
}
}
}
2.2. 为 Post
类型实现类型解析器
示例 GraphQL 模式中的 Post
类型定义如下
type Post implements Node {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
title: String!
content: String
published: Boolean!
author: User
categories(
where: CategoryWhereInput
orderBy: Enumerable<CategoryOrderByInput>
skip: Int
after: String
before: String
first: Int
last: Int
): [Category!]
}
此类型有两个关系
author
字段表示与User
的 1-n 关系categories
字段表示与Category
的 m-n 关系
由于您不再使用 prisma-binding
,因此您现在需要在类型解析器中“手动”解析这些关系。
您可以通过在您的解析器映射中添加一个Post
字段,并按如下方式实现author
和categories
关系的解析器来做到这一点。
const resolvers = {
Query: {
// ... your query resolvers
},
Mutation: {
// ... your mutation resolvers
},
User: {
// ... your type resolvers for `User` from before
},
Post: {
author: (parent, args, context) => {
return context.prisma.post
.findUnique({
where: { id: parent.id },
})
.author()
},
categories: (parent, args, context) => {
return context.prisma.post
.findUnique({
where: { id: parent.id },
})
.categories()
},
},
}
在这些解析器内部,您使用新的PrismaClient
对数据库执行查询。在author
解析器中,数据库查询加载表示Post
作者的User
记录。在categories
解析器中,数据库查询加载指定post
(其id
包含在parent
对象中)的所有Category
记录。
由于这些额外的解析器,您现在可以在 GraphQL 查询/突变中嵌套关系,无论何时您在查询中请求有关 User
类型的的信息,例如
{
posts {
id
title
author {
# fetching this relation is enabled by the new type resolver
id
name
}
categories {
# fetching this relation is enabled by the new type resolver
id
name
}
}
}
2.3. 实现Profile
类型的类型解析器
我们示例GraphQL模式中的Profile
类型定义如下:
type Profile implements Node {
id: ID!
bio: String
user: User!
}
此类型具有一种关系:user
字段表示与User
的1-n关系。
由于您不再使用prisma-binding
,因此您现在需要在类型解析器中“手动”解析此关系。
您可以通过在您的解析器映射中添加一个Profile
字段,并按如下方式实现owner
关系的解析器来做到这一点。
const resolvers = {
Query: {
// ... your query resolvers
},
Mutation: {
// ... your mutation resolvers
},
User: {
// ... your type resolvers for `User` from before
},
Post: {
// ... your type resolvers for `Post` from before
},
Profile: {
user: (parent, args, context) => {
return context.prisma.profile
.findUnique({
where: { id: parent.id },
})
.owner()
},
},
}
在此解析器内部,您使用新的PrismaClient
对数据库执行查询。在user
解析器中,数据库查询加载指定profile
(其id
包含在parent
对象中)的所有User
记录。
由于此额外的解析器,您现在可以在GraphQL查询/突变中嵌套关系,只要您在查询中请求有关Profile
类型的信息。
2.4. 实现Category
类型的类型解析器
我们示例GraphQL模式中的Category
类型定义如下:
type Category implements Node {
id: ID!
name: String!
posts(
where: PostWhereInput
orderBy: Enumerable<PostOrderByInput>
skip: Int
after: String
before: String
first: Int
last: Int
): [Post!]
}
此类型具有一种关系:posts
字段表示与Post
的m-n关系。
由于您不再使用prisma-binding
,因此您现在需要在类型解析器中“手动”解析此关系。
您可以通过在您的解析器映射中添加一个Category
字段,并按如下方式实现posts
和profile
关系的解析器来做到这一点。
const resolvers = {
Query: {
// ... your query resolvers
},
Mutation: {
// ... your mutation resolvers
},
User: {
// ... your type resolvers for `User` from before
},
Post: {
// ... your type resolvers for `Post` from before
},
Profile: {
// ... your type resolvers for `User` from before
},
Category: {
posts: (parent, args, context) => {
return context.prisma
.findUnique({
where: { id: parent.id },
})
.posts()
},
},
}
在此解析器内部,您使用新的PrismaClient
对数据库执行查询。在posts
解析器中,数据库查询加载指定categories
(其id
包含在parent
对象中)的所有Post
记录。
由于此额外的解析器,您现在可以在GraphQL查询/突变中嵌套关系,只要您在查询中请求有关Category
类型的信息。
所有类型解析器就位后,您可以开始迁移实际的GraphQL API操作。
3. 迁移GraphQL操作
3.1. 迁移GraphQL查询
在本节中,您将把所有GraphQL查询从prisma-binding
迁移到Prisma Client。
3.1.1. 迁移users
查询(使用forwardTo
)
在我们的示例API中,示例GraphQL模式中的users
查询定义和实现如下。
使用prisma-binding
的SDL模式定义
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
},
}
使用Prisma Client实现users
解析器
要重新实现以前使用forwardTo
的查询,其思路是将传入的过滤、排序和分页参数传递给PrismaClient
。
const resolvers = {
Query: {
users: (_, args, context, info) => {
// this doesn't work yet
const { where, orderBy, skip, first, last, after, before } = args
return context.prisma.user.findMany({
where,
orderBy,
skip,
first,
last,
after,
before,
})
},
// ... other resolvers
},
}
请注意,此方法尚不能使用,因为传入参数的结构与PrismaClient
期望的结构不同。为了确保结构兼容,您可以使用@prisma/binding-argument-transform
npm包,该包可确保兼容性。
npm install @prisma/binding-argument-transform
您可以按如下方式使用此包:
const {
makeOrderByPrisma2Compatible,
makeWherePrisma2Compatible,
} = require('@prisma/binding-argument-transform')
const resolvers = {
Query: {
users: (_, args, context, info) => {
// this still doesn't entirely work
const { where, orderBy, skip, first, last, after, before } = args
const prisma2Where = makeWherePrisma2Compatible(where)
const prisma2OrderBy = makeOrderByPrisma2Compatible(orderBy)
return context.prisma.user.findMany({
where: prisma2Where,
orderBy: prisma2OrderBy,
skip,
first,
last,
after,
before,
})
},
// ... other resolvers
},
}
剩下的最后一个问题是分页参数。Prisma ORM 2 引入了新的分页API
first
、last
、before
和after
参数已移除。- 新的
cursor
参数替换了before
和after
。 - 新的
take
参数替换了first
和last
。
以下是您可以调整调用以使其符合新的Prisma Client分页API的方式:
const {
makeOrderByPrisma2Compatible,
makeWherePrisma2Compatible,
} = require('@prisma/binding-argument-transform')
const resolvers = {
Query: {
users: (_, args, context) => {
const { where, orderBy, skip, first, last, after, before } = args
const prisma2Where = makeWherePrisma2Compatible(where)
const prisma2OrderBy = makeOrderByPrisma2Compatible(orderBy)
const skipValue = skip || 0
const prisma2Skip = Boolean(before) ? skipValue + 1 : skipValue
const prisma2Take = Boolean(last) ? -last : first
const prisma2Before = { id: before }
const prisma2After = { id: after }
const prisma2Cursor =
!Boolean(before) && !Boolean(after)
? undefined
: Boolean(before)
? prisma2Before
: prisma2After
return context.prisma.user.findMany({
where: prisma2Where,
orderBy: prisma2OrderBy,
skip: prisma2Skip,
cursor: prisma2Cursor,
take: prisma2Take,
})
},
// ... other resolvers
},
}
需要进行计算以确保传入的分页参数正确映射到Prisma Client API中的参数。
3.1.2. 迁移posts(searchString: String): [Post!]!
查询
posts
查询定义和实现如下。
使用prisma-binding
的SDL模式定义
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
},
}
使用Prisma Client实现posts
解析器
要使用新的Prisma Client获得相同的结果,您需要调整解析器实现。
const resolvers = {
Query: {
posts: (_, args, context) => {
return context.prisma.post.findMany({
where: {
OR: [
{ title: { contains: args.searchString } },
{ content: { contains: args.searchString } },
],
},
})
},
// ... other resolvers
},
}
您现在可以在GraphQL Playground中发送相应的查询。
{
posts {
id
title
author {
id
name
}
}
}
3.1.3. 迁移user(uniqueInput: UserUniqueInput): User
查询
在我们的示例应用程序中,user
查询定义和实现如下。
使用prisma-binding
的SDL模式定义
type Query {
user(userUniqueInput: UserUniqueInput): User
# ... other queries
}
input UserUniqueInput {
id: String
email: String
}
使用prisma-binding
的解析器实现
const resolvers = {
Query: {
user: (_, args, context, info) => {
return context.prisma.query.user(
{
where: args.userUniqueInput,
},
info
)
},
// ... other resolvers
},
}
使用Prisma Client实现user
解析器
要使用新的Prisma Client获得相同的结果,您需要调整解析器实现。
const resolvers = {
Query: {
user: (_, args, context) => {
return context.prisma.user.findUnique({
where: args.userUniqueInput,
})
},
// ... other resolvers
},
}
您现在可以通过GraphQL Playground发送相应的查询。
{
user(userUniqueInput: { email: "[email protected]" }) {
id
name
}
}
3.1. 迁移GraphQL突变
在本节中,您将迁移示例模式中的GraphQL突变。
3.1.2. 迁移createUser
突变(使用forwardTo
)
在示例应用程序中,示例GraphQL模式中的createUser
突变定义和实现如下。
使用prisma-binding
的SDL模式定义
type Mutation {
createUser(data: UserCreateInput!): User!
# ... other mutations
}
使用prisma-binding
的解析器实现
const resolvers = {
Mutation: {
createUser: forwardTo('prisma'),
// ... other resolvers
},
}
使用Prisma Client实现createUser
解析器
要使用新的Prisma Client获得相同的结果,您需要调整解析器实现。
const resolvers = {
Mutation: {
createUser: (_, args, context, info) => {
return context.prisma.user.create({
data: args.data,
})
},
// ... other resolvers
},
}
您现在可以针对新API编写第一个突变,例如:
mutation {
createUser(data: { name: "Alice", email: "[email protected]" }) {
id
}
}
3.1.3. 迁移createDraft(title: String!, content: String, authorId: String!): Post!
查询
在示例应用程序中,createDraft
突变定义和实现如下。
使用prisma-binding
的SDL模式定义
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
},
}
使用Prisma Client实现createDraft
解析器
要使用新的Prisma Client获得相同的结果,您需要调整解析器实现。
const resolvers = {
Mutation: {
createDraft: (_, args, context, info) => {
return context.prisma.post.create({
data: {
title: args.title,
content: args.content,
author: {
connect: {
id: args.authorId,
},
},
},
})
},
// ... other resolvers
},
}
您现在可以通过GraphQL Playground发送相应的突变。
mutation {
createDraft(title: "Hello World", authorId: "__AUTHOR_ID__") {
id
published
author {
id
name
}
}
}
3.1.4. 迁移updateBio(bio: String, userUniqueInput: UserUniqueInput!): User
突变
在示例应用程序中,updateBio
突变定义和实现如下。
使用prisma-binding
的SDL模式定义
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
},
}
使用Prisma Client实现updateBio
解析器
要使用Prisma Client获得相同的结果,您需要调整解析器实现。
const resolvers = {
Mutation: {
updateBio: (_, args, context, info) => {
return context.prisma.user.update({
data: {
profile: {
update: { bio: args.bio },
},
},
where: args.userUniqueInput,
})
},
// ... other resolvers
},
}
您现在可以通过GraphQL Playground发送相应的突变。
mutation {
updateBio(
userUniqueInput: { email: "[email protected]" }
bio: "I like turtles"
) {
id
name
profile {
id
bio
}
}
}
3.1.5. 迁移addPostToCategories(postId: String!, categoryIds: [String!]!): Post
突变
在我们的示例应用程序中,addPostToCategories
突变定义和实现如下。
使用prisma-binding
的SDL模式定义
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
},
}
使用 Prisma Client 实现 addPostToCategories
解析器
要使用Prisma Client获得相同的结果,您需要调整解析器实现。
const resolvers = {
Mutation: {
addPostToCategories: (_, args, context, info) => {
const ids = args.categoryIds.map((id) => ({ id }))
return context.prisma.post.update({
where: {
id: args.postId,
},
data: {
categories: { connect: ids },
},
})
},
// ... other resolvers
},
}
您现在可以通过GraphQL Playground发送相应的查询。
mutation {
addPostToCategories(
postId: "__AUTHOR_ID__"
categoryIds: ["__CATEGORY_ID_1__", "__CATEGORY_ID_2__"]
) {
id
title
categories {
id
name
}
}
}
4. 清理
由于整个应用程序现已升级到 Prisma ORM 2,您可以删除所有不必要的文件夹,并移除不再需要的依赖项。
4.1. 清理 npm 依赖项
您可以先移除与 Prisma 1 设置相关的 npm 依赖项。
npm uninstall graphql-cli prisma-binding prisma1
4.2. 删除未使用的文件夹
接下来,删除 Prisma 1 设置的文件夹。
rm prisma1/datamodel.prisma prisma1/prisma.yml
4.3. 停止 Prisma ORM 服务器
最后,您可以停止运行 Prisma ORM 服务器。