繁体   English   中英

如何从解析器中的 graphql 获取数据

[英]how can I fetch data from graphql in my resolver

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

这适用于 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 服务器运行在它之上。 不幸的是,堆栈溢出也认为这篇文章中有太多代码,所以我将不得不因为他们的系统无法处理这些无关紧要的胡言乱语而胡思乱想。

您必须为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 关系的更多信息

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM