【问题标题】:how can I fetch data from graphql in my resolver如何在解析器中从 graphql 获取数据
【发布时间】:2019-07-12 05:34:09
【问题描述】:

在我的解析器中,我似乎无法获取连接的数据

这在 graphql 游乐场 (prisma) 中有效,但我不确定如何在 apollo 服务器中形成解析器的语法

// my typedef for activity is

type Activity {
    id: ID! @id
    ActivityType: ActivityType!
    title: String!
    date: DateTime
    user: User!
    distance: Float!
    distance_unit: Unit!
    duration: Float!
    elevation: Float
    elevation_unit: Unit
    createdAt: DateTime! @createdAt
    updatedAt: DateTime! @updatedAt

// and my resolver currently looks like this

async activity(parent, args, ctx, info) {
        const foundActivity = await ctx.db.query.activity({
            where: {
                id: args.id
            }
        });
        // todo fetch user data from query
        console.log(foundActivity);
    }

// where db has been placed onto the ctx (context)
// the CL gives all of the data for Activity apart from the user

// in the playground I would do something like this

query activity {
  activity(where: {
    id: "cjxxow7c8si4o0b5314f9ibek"
  }){
    title
    user {
      id
      name
    }
  }
}

// but I do not know how to specify what is returned in my resolver.

console.log(foundActivity) gives:

{ id: 'cjxxpuh1bsq750b53psd2c77d',
  ActivityType: 'CYCLING',
  title: 'Test Activity',
  date: '2019-07-10T20:21:27.681Z',
  distance: 13.4,
  distance_unit: 'KM',
  duration: 90030,
  elevation: 930,
  elevation_unit: 'METERS',
  createdAt: '2019-07-10T20:48:50.879Z',
  updatedAt: '2019-07-10T20:48:50.879Z' }

Prisma 是 DB ORM,然后我有一个 Apollo-Server 2 服务器在其上运行。不幸的是,堆栈溢出也认为这篇文章中的代码太多,所以我将不得不讨论一些无关紧要的乱码,因为他们的系统无法处理它。

【问题讨论】:

    标签: graphql apollo-server


    【解决方案1】:

    您必须为Activity.user 实施解析器。不幸的是,您的实体似乎不包含对用户的引用。首先,将用户连接添加到您的 Prisma 数据模型。然后为Activity.user 实现解析器。我对 Prisma 1 不是很熟悉,但是这个幼稚的实现应该已经可以满足您的需求了:

    let resolvers = {
      Query: {
        // ...
      },
      Activity: {
        user(parent, args, ctx) {
          return ctx.db.query.activity({ id: parent.id }).user();
        }
      }
    }
    

    详细了解如何在 Prisma here 中解决关系

    【讨论】:

    • 非常感谢您的帮助和抽出宝贵时间。我找到了一条不同的路线,如下所示,但你让我走上了这条路。
    【解决方案2】:

    所以答案非常简单: 我只是在查询中添加了第二个参数(在“where”之后,带有要返回的数据形状的 gql 标记,所以我的代码现在看起来像:

    const foundActivity = await ctx.db.query.activity(
            {
                where: {
                    id: args.id
                }
            },
            `{id title user { id name }}`
        );
    

    【讨论】:

    • 同样可以通过提供 info 参数(解析器的第 4 个参数)作为 DB 调用的第 2 个参数来实现。这只会在初始请求中实际请求用户时获取用户。
    猜你喜欢
    • 2021-06-17
    • 2020-09-11
    • 2018-11-05
    • 2019-12-02
    • 1970-01-01
    • 2018-06-16
    • 2018-06-08
    • 1970-01-01
    相关资源
    最近更新 更多