如何将对象数组传递给Query?

时间:2019-08-05 14:13:30

标签: javascript reactjs graphql apollo

我试图弄清楚如何将一组对象传递到我的GraphQL查询中,但是我发现文档对此不太清楚。我正在与FE的Apollo,BE的Graphql-yoga一起使用,并使用Prisma作为数据库及其API。

这是我的查询,其中对对象数组进行了硬编码:

const USERS = gql`

  query USERS(
    $userId: ID
  ) {
    users(
      where: {
        id_not: $userId
        hasProducts_some: {
          OR: [
            { itemId: 1 },
            { itemId: 2 }
          ]
        }
      }
    ) {
      firstName
    }
  }
`;

上面的查询返回了我想要的东西,但让我有点卡住的是如何获取此数组:

[
  { itemId: 1 },
  { itemId: 2 }
]

作为查询的变量传入。从网上可以找到的地方,我可能需要在客户端创建一个GraphQLObjectType才能传递对象定义。这是我的实现方式:

import { GraphQLObjectType, GraphQLString } from 'graphql';

const ProductName = new GraphQLObjectType({
  name: 'ProductName',
  fields: () => ({
    itemId: {
      type: GraphQLString,
    },
  })
});

const USERS = gql`

  query USERS(
    $userId: ID,
    $hasProducts: [ProductName]
  ) {
    users(
      where: {
        id_not: $userId
        hasProducts_some: {
          OR: $hasProducts
        }
      }
    ) {
      firstName
    }
  }
`;

以上返回我以下错误:

  

未知类型“ ProductName”

我是否采用了正确的方法来传递对象数组,如果是的话,我的实现有什么问题?

3 个答案:

答案 0 :(得分:0)

类型已创建,并在创建模式服务器端时使用。创建架构后,无法在运行时对其进行修改-该架构具有创建时指定的任何类型和指令。换句话说,在客户端定义 new 类型是没有意义的-由于服务器不知道该类型,因此不能在发送给服务器的任何查询中使用它。

如果将变量(例如$hasProducts)传递给参数(例如hasProducts_some),则该变量的类型必须与参数的类型匹配。此类型可以是标量(例如StringInt),也可以是输入对象类型。确切的类型取决于模式本身。要确定要使用的类型,可以在GraphQL Playground(或GraphiQL)中打开架构的文档,然后搜索相关字段(在本例中为hasProducts_some)。

请注意,您也可以只为整个where字段传递一个变量。

答案 1 :(得分:-1)

由于gql函数需要模板文字,因此您应该像这样转义产品对象:

const USERS = gql`

  query USERS(
    $userId: ID,
    $hasProducts: [${ProductName}]
  ) {
    users(
      where: {
        id_not: $userId
        hasProducts_some: {
          OR: $hasProducts
        }
      }
    ) {
      firstName
    }
  }
`;

答案 2 :(得分:-1)

graphql的新功能。但是想知道这是否可以解决它。

const USERS = gql`
 query USERS(
    $userId: ID,
    $hasProducts: GraphQLList(ProductName) 
  ) {
    users(
      where: {
        id_not: $userId
        hasProducts_some: {
          OR: $hasProducts
        }
      }
    ) {
      firstName
    }
  }
`;

较小的更改,但无权发表评论。因此,将其发布为答案。