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

时间:2019-07-10 21:37:53

标签: graphql apollo-server

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

这在graphql游乐场(棱镜)中有效,但是我不确定如何在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是数据库ORM,然后我在其上运行了Apollo-Server 2服务器。不幸的是,堆栈溢出还认为这篇文章中的代码太多,因此由于他们的系统无法处理,我将不得不浪费一些乱码。

2 个答案:

答案 0 :(得分: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();
    }
  }
}

了解有关解决{s {3}}中棱镜关系的更多信息

答案 1 :(得分:0)

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

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