如何使用 graphql 将 ID 列表作为参数发送

How to send list of ids as param with graphql

我正在使用 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 以及如何在后端获取它?

有什么想法吗?

问题是因为 ids 的类型是 String

在你的 schema 中,参数 ids 的类型是 String,所以为了能够有类似 ['3692', '3695', '3704'] 的东西,你必须定义参数转换为 StringsList

类似于:

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
    }
  }
`;