【问题标题】:Lighthouse GraphQL - how to pass array as variable?Lighthouse GraphQL - 如何将数组作为变量传递?
【发布时间】:2021-03-06 17:23:37
【问题描述】:

我正在构建一个简单的 Facebook 克隆,以增强我对 GraphQL 的了解。我在 Laravel 之上使用 lighthouse-php 来提供我的数据。本质上,一个用户有很多朋友,我知道这是可行的,因为在 tinker 控制台中,我可以使用 $user->friends()->get() 之类的东西返回正确的数据。我正在努力弄清楚如何传递一组数据。

在我的前端,我有一个 Vuetify 组合框(基本上是一个选择下拉菜单),它构建了一系列电子邮件,这就是我试图传递给我的后端突变的内容。

如何构造类型和突变,以便它接受电子邮件数组?

user.graphql:

extend type Mutation @guard(with: ["api"]) {
    addFriends(input: [AddFriendsInput]! @spread): [User]! @field(resolver: "UserMutator@addFriends")
}

type User {
    id: ID!
    email: String!
    password: String!
    first_name: String
    last_name: String
    created_at: DateTime!
    updated_at: DateTime!

    friends: [User]! @belongsToMany(relation: "friends")
}

input AddFriendsInput {
    email: String!
}

addFriend.gql:

mutation AddFriends($friends: [AddFriendsInput]!) {
  addFriends(input: { email:[$friends] }){
    id
    email
  }
}

【问题讨论】:

  • 只需mutation AddFriends($friends: [AddFriendsInput]!) { addFriends(input: $friends){ ...定义变量类型(匹配BE签名)并将其作为一个整体对象使用
  • 这似乎更接近了!我的 GraphQL Playground 控制台出现错误:Uncaught Error: Introspection must provide input type for arguments, but received: [User]!,当我运行突变时,我收到错误 "Variable \"$friends\" got invalid value [{\"email\":\"test@gmail.com\"}]; Field value[0].friends of required type [User]! was not provided."
  • 这是关于查询/graphql 部分 ... IDK 灯塔 - 错误的 args 定义/指令(因为传递的值匹配/对此输入类型有效)?....返回类型混合到问题中(变异解析器不返回用户数组)
  • 我的意思是我认为它仍然与 graphql 定义有关,不是吗?在这一点上,它甚至还没有到达解析器。
  • 我的意思是@spread 没有意义,因为只有一种 arg 和数组类型...您可以统一 arg/vars 命名:mutation AddFriends($input: [AddFriendsInput]!) { addFriends(input: $input){ ...并且只返回一些布尔“成功”到单独的问题...探索 graphiql/playground 文档,检查输入类型,在编码 FE 之前使用查询变量测试突变

标签: graphql laravel-lighthouse


【解决方案1】:

好吧,终于弄明白了。

将输入修改为:

input AddFriendsInput {
  email: String!
  # friends: [User]
}

并将我的 Mutation 更改为:

mutation AddFriends($friends: [AddFriendsInput]!) {
  addFriends(input: $friends) {
    id
    email
  }
}

这让我现在可以将一组电子邮件传递给我的解析器。

【讨论】:

  • 你说得对哈哈,我一直在搞这么多小改动,我发帖的时候没想到原来是这样的。感谢您的帮助!
猜你喜欢
  • 2022-01-03
  • 2017-03-25
  • 2019-07-12
  • 2018-12-01
  • 2020-05-05
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 2021-05-30
相关资源
最近更新 更多