美文网首页我爱编程
解析器模式(Resolver Patterns)

解析器模式(Resolver Patterns)

作者: guog | 来源:发表于2018-05-02 00:27 被阅读237次

    本文属使用Prisma构建GraphQL服务系列。

    本教程概述了使用graphql-yogaPrisma实现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
      }
    }
    

    相关文章

      网友评论

        本文标题:解析器模式(Resolver Patterns)

        本文链接:https://www.haomeiwen.com/subject/sjqqrftx.html