【问题标题】:How to send list of ids as param with graphql如何使用graphql发送ID列表作为参数
【发布时间】:2019-08-10 20:07:42
【问题描述】:

我正在使用 React、Graphql 和 Apollo。

我的功能如下:

updateSlots(updateSlots, data){
        const {slotIds, refetch} = this.props;
        const {disabled, printEntry, toggleSlotForm} = data;

        updateSlots({variables: {disabled: disabled, printEntry: printEntry, ids: slotIds}})
            .then(res => {
                if (res.data.updateSlots.ok) {

                    refetch();
                    this.setState({hasError: false, errorMessage: "", saved: true, slot: initialSlot()}, () => {
                        setTimeout(() => toggleSlotForm(), 3000)
                    });
                }
            })
            .catch(err => {
                debugger;
                let error_msg = err.message.replace("GraphQL error: ", '');
                this.setState({hasError: true, saved: false, errorMessage: error_msg});
                throw(error_msg);
            })

    }

而mutation如下:

const UPDATE_SLOTS = gql`
  mutation updateSlots($disabled: Boolean!, $printEntry: Boolean!, $ids: String!) {
    updateSlots(disabled: $disabled, printEntry: $printEntry, ids: $ids) {
        ok
    }
  }
`;

在后端我使用 graphene 并且突变如下:

class UpdateSlots(graphene.Mutation):
    class Arguments:
        disabled = graphene.Boolean(required=True)
        printEntry = graphene.Boolean(required=True)
        ids = graphene.String(required=True)

    ok = graphene.Boolean()

    @staticmethod
    def mutate(root, info, disabled, printEntry, ids):
        pdb.set_trace()
        ok = False

        try:
            ok = True
            for id in ids:
                print(id)
        except Exception as e:
            ok = False
            raise GraphQLError(str(e))

但我在ids variable 中得到字符串如下:

"['3692', '3695', '3704']"

而不是:

['3692', '3695', '3704']

如何发送 id 数组以及如何在后端获取它?

有什么想法吗?

【问题讨论】:

    标签: reactjs graphql apollo react-apollo graphene-python


    【解决方案1】:

    问题是因为ids 的类型是String。

    在您的schema 中,参数ids 的类型是String,因此为了能够拥有类似['3692', '3695', '3704'] 的内容,您必须将参数定义为List 的Strings .

    类似:

    class UpdateSlots(graphene.Mutation):
        class Arguments:
            disabled = graphene.Boolean(required=True)
            printEntry = graphene.Boolean(required=True)
            ids = graphene.List(graphene.String(required=True))
    

    在突变中,您还必须将参数 ids 更新为:

    const UPDATE_SLOTS = gql`
      mutation updateSlots($disabled: Boolean!, $printEntry: Boolean!, $ids: [String]!) {
        updateSlots(disabled: $disabled, printEntry: $printEntry, ids: $ids) {
            ok
        }
      }
    `;
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-01
      • 2011-04-10
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 2021-07-07
      • 2011-07-15
      • 2021-03-30
      相关资源
      最近更新 更多