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

时间:2019-03-20 07:30:04

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

我正在使用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
    }
  }
`;

在后端,我使用石墨烯,其突变如下:

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数组,如何在后端获取它?

有什么主意吗?

1 个答案:

答案 0 :(得分:0)

问题是因为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
    }
  }
`;

希望有帮助。