3

我需要动态更改我的突变文档,以便能够在单个突变中创建多个项目。所以我有这个函数createOrderName,它需要一个整数并能够创建正确的突变文档。例如。createOrderName(2)得到

mutation createOrderMut($input0: AddToOrderMenuItemConnectionInput!, $input1: AddToOrderMenuItemConnectionInput!) {
  input0: addToOrderMenuItemConnection (input:$input0) {
    changedOrderMenuItem {
      id
    }
  }
  input1: addToOrderMenuItemConnection (input:$input1) {
    changedOrderMenuItem {
      id
    }
  }
}

我的容器如下。

const CartContainer = compose(
  graphql(createOrderName(2), {
    props: ({ mutate }) => ({
      addToOrderMenuItem: (menus, orderId) => mutate({
        variables: createOrdersInput(menus, orderId)
      })
    })
  })
)(CartView)

现在我怎样才能将一个整数值传递给这个突变,以便它创建正确的突变文档?目前它修复为 2,但我需要它更灵活,以便我可以创建任意数量的项目......

4

2 回答 2

11

这听起来像是您正在使用的后端的不幸限制。进行批量突变的正确方法是在服务器上设置一个突变字段,该字段接受包含您要插入的所有项目的列表参数。因此,Apollo 并非旨在支持使用标准react-apolloAPI 生成此类动态查询。这是因为我们坚信使用静态查询比在运行时生成字段要好得多:https ://dev-blog.apollodata.com/5-benefits-of-static-graphql-queries-b7fa90b0b69a#.hp710vxe7

但是,鉴于这种情况,动态生成突变字符串听起来是一个不错的选择。您可以通过直接使用 Apollo 而不是通过graphqlHoC 来做到这一点。您可以使用withApolloHoC 执行此操作:http ://dev.apollodata.com/react/higher-order-components.html#withApollo

import { withApollo } from 'react-apollo';

const MyComponent = ({ client }) => {
  function mutate() {
    const dynamicMutationString = // generate mutation string here

    client.mutate({
      mutation: gql`${dynamicMutationString}`,
      variables: { ... },
    }).then(...);
  }

  return <button onClick={mutate}>Click here</button>;
}

const MyComponentWithApollo = withApollo(MyComponent);

我们为此目的构建了这个额外的 API - 当标准的东西还不够时。

这是mutate顺便说一句的文档:http: //dev.apollodata.com/core/apollo-client-api.html#ApolloClient.mutate

于 2017-02-06T05:48:29.280 回答
2

我不确定我是否可以用你当前的实现来回答你的问题,所以我会敦促你重新考虑你的突变定义和使用GraphQLListand GraphQLInputObject

因此,根据您需要改变的字段:

args: {
  input: {
    type: new GraphQLList(new GraphQLInputObjectType({
      name: 'inputObject',
      description: 'Your description here',
      fields: {
        id: { type: GraphQLInt }
      },
    })),
  },
},

通过这种方式,您可以在 mutate 调用中提供 n 个对象,并获取有关您的类型的列表:

{
  mutation myMutation {
    addToOrderMenuItemConnection(input: [{ id: 123 }, { id: 456 }]) {
      id
    }
  }
}

同样,我不是 100% 熟悉您的最终目标,但我认为这也会为您未来的更改/更新提供灵活性,因为您正在处理对象输入而不是单个参数,这也将(希望)使您免受未来的重大变化。

于 2017-02-02T02:56:51.330 回答