【问题标题】:Add custom GraphQL resolvers and types into Prisma/Nexus schema将自定义 GraphQL 解析器和类型添加到 Prisma/Nexus 架构中
【发布时间】:2019-09-29 15:51:01
【问题描述】:

使用:TypeScriptPrismaMySQLGraphQLServerApolloClient、以这种方式构建架构:

const schema = makePrismaSchema({
  // Provide all the GraphQL types we've implemented
  types: [Query, Mutation, User, Post],...

然后:

  const server = new GraphQLServer({
    schema,
    context: { prisma }
  });

如何将其与与 SQL 无关的自定义解析器和类型结合起来?

(我也想通过 GQL 调用一些 REST 端点)

【问题讨论】:

    标签: javascript graphql-js prisma-graphql nexus-prisma


    【解决方案1】:

    虽然nexus 是为了与prisma 一起使用而创建的,但它实际上只是一个模式构建器。您可以轻松地使用它来创建模式,甚至无需使用 Prisma。例如:

    export const User = prismaObjectType({
      name: 'User',
      definition(t) {
        t.list.field('comments', {
          type: 'Comment',
          resolve(root, args, ctx) {
            return getComments();
          },
        });
      },
    })
    
    export const Comment = prismaObjectType({
      name: 'Comment',
      definition(t) {
        t.string('body');
      },
    })
    

    这里getComments 可以返回一个评论对象数组,或者一个解析为一个的 Promise。例如,如果您正在调用其他 API,您通常会返回一个带有调用结果的 Promise。如上所示,解析器公开了父值、字段的参数和上下文对象——您可以使用这些信息中的任何一个来确定如何解析特定字段。

    【讨论】:

    • 对某些人来说不是很明显的一件事是,您需要在创建模式时将其添加到类型中:` makePrismaSchema({ types: [OtherTypes..., Comment], }) `
    猜你喜欢
    • 2019-10-24
    • 1970-01-01
    • 2020-10-04
    • 2020-10-25
    • 2020-02-03
    • 2020-04-05
    • 1970-01-01
    • 2021-09-11
    • 2020-06-13
    相关资源
    最近更新 更多