如何在GraphQL中将params传递给子属性

时间:2018-06-02 14:51:22

标签: graphql apollo apollo-server prisma prisma-graphql

我是GraphQL的新手,成为了一个巨大的粉丝:)

但是,有些事情我不清楚。我正在使用Prisma和GraphQL-Yoga与Prisma绑定。

我不知道如何将我的graphQL服务器中的params传递给子属性。不知道这是否清楚,但我会用代码显示它,希望更容易:)

这些是我的类型

type User {
  id: ID! @unique
  name: String!
  posts: [Post!]!
}

type Post {
  id: ID! @unique
  title: String!
  content: String!
  published: Boolean! @default(value: "false")
  author: User!
}

我的schema.graphql

type Query {
  hello: String
  posts(searchString: String): [Post]
  users(searchString: String, searchPostsTitle: String): [User]
  me(id: ID): User
}

和我的用户解析器:

import { Context } from "../../utils";

export const user = {
  hello: () => "world",
  users: (parent, args, ctx: Context, info) => {
    return ctx.db.query.users(
      {
        where: {
          OR: [
            {
              name_contains: args.searchString
            },
            {
              posts_some: { title_contains: args.searchPostsTitle }
            }
          ]
        }
      },
      info
    );
  },
  me: (parent, args, ctx: Context, info) => {
    console.log("parent", parent);
    console.log("args", args);
    console.log("info", info);
    console.log("end_________________");
    return ctx.db.query.user({ where: { id: args.id } }, info);
  }
};

和我的帖子解析器

import { Context } from "../../utils";

export const post = {
  posts: (parent, args, ctx: Context, info) => {
    return ctx.db.query.posts(
      {
        where: {
          OR: [
            {
              title_contains: args.searchString
            },
            {
              content_contains: args.searchString
            }
          ]
        }
      },
      info
    );
  }
};

所以,现在:)

当我在我的prisma服务的GraphQL游乐场时,我可以执行以下操作:

{
  user(where: {id: "cjhrx5kaplbu50b751a3at99d"}) {
    id
    name
    posts(first: 1, after: "cjhweuosv5nsq0b75yc18wb2v") {
      id
      title
      content
    }
  }
}

但我不能在服务器上这样做,如果我做那样的事情......我收到错误:

"error": "Response not successful: Received status code 400"

这就是我想要的:

{
  me(id: "cjhrx5kaplbu50b751a3at99d") {
    id
    name
    posts(first:1) {
      id
      title
      content
    }
  }
}

有人知道我该怎么做吗?

1 个答案:

答案 0 :(得分:1)

因为我有一个自定义类型的用户,所以帖子没有像生成的那样的参数。要么我使用生成的,要么修改它看起来像这样:

type User {
  id: ID!
  name: String!
  posts(where: PostWhereInput, orderBy: PostOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [Post!]
}

编辑2018年6月4日

# import Post from './generated/prisma.graphql'

type Query {
  hello: String
  posts(searchString: String): [Post]
  users(searchString: String, where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [User]
  me(id: ID): User
}

type Mutation {
  createUser(name: String!): User
  createPost(
    title: String!
    content: String!
    published: Boolean!
    userId: ID!
  ): Post
}

我手动从prisma.graphql复制了params。