本文属使用Prisma构建GraphQL服务系列。
本教程概述了使用graphql-yoga
和Prisma
实现GraphQL服务器时可能遇到的常见情况。
注意,本教程中的所有场景均基于typescript-basic GraphQL样板项目。
场景:向数据模型(data model)添加一个新字段,并将其公开(expose)在API中
添加address
字段到数据库中的User
类型中,以便将其公开在应用程序API中。
说明
1.添加字段到数据模型
在database/datamodel.graphql
中:
type User {
id: ID! @unique
email: String! @unique
password: String!
name: String!
posts: [Post!]!
+ address: String
}
2.部署更新的数据模型
prisma deploy
这将:
- 将新数据库结构部署到本地服务
- 将数据库的新GraphQL schema下载到``database/schema.graphql`
3.将该字段添加到application schema
在src/schema.graphql
:
type User {
id: ID!
email: String!
name: String!
posts: [Post!]!
+ address: String
}
场景:添加新的解析器
假设我们想添加一个自定义解析器来删除一个Post
。
说明
在src/schema.graphql
中为突变(Mutation)类型添加一个新的delete
字段
type Mutation {
createDraft(title: String!, text: String): Post
publish(id: ID!): Post
+ delete(id: ID!): Post
}
将delete
解析器添加到src/index.js
的Mutation部分
delete(parent, { id }, ctx, info) {
return ctx.db.mutation.deletePost(
{
where: { id }
},
info
);
}
运行yarn start
.
如此,在GraphQL Playground中可运行如下的突变(mutation)用以删除Post
:
mutation {
delete(id: "__POST_ID__") {
id
}
}
网友评论