Vue Apollo:如何使用对象作为输入参数来查询GraphQL?

时间:2019-06-04 08:17:37

标签: vue.js graphql vue-apollo saleor

我想通过Saleor电子商务平台提供的GraphQL API创建一个Checkout对象。

根据gql游乐场,需要做一个变异,以CheckoutCreateInput对象作为参数。

这是一个示例示例,在操场上效果很好。

example gql

这是我尝试过的当前代码(我正在vuex动作中执行此操作)

export const actions = {
  addToCart({ commit, dispatch }, cartItem) {
    const currentCartItems = this.state.cartItems
    // Check to see if we already have a checkout object
    if (this.state.checkoutId !== '') {
      // Create a new checkout ID
      console.log('creating new checkout object')
      try {
        this.app.apolloProvider.defaultClient
          .mutate({
            mutation: CREATE_CART_MUTATION,
            variables: {
              checkoutInput: {
                lines: { quantity: 10, variantId: 'UHJvZHVjdFZhcmlhbnQ6NQ==' },
                email: 'test@test.com'
              }
            }
          })
          .then(({ data }) => {
            console.log(data)
          })
      } catch (e) {
        console.log(e)
      }
    } else {
      console.log('checkout id already set')
    }

    // TODO: Check to see if the cart already contains the current Cart Item

    commit('ADD_CART_ITEM', cartItem)
  }

这是CREATE_CART_MUTATION:

import gql from 'graphql-tag'

export const CREATE_CART_MUTATION = gql`
  mutation($checkoutInput: CheckoutCreateInput!) {
    checkoutCreate(input: $checkoutInput) {
      checkout {
        id
        created
        lastChange
        lines {
          id
          variant {
            id
            name
          }
          quantity
          totalPrice {
            gross {
              localized
            }
            net {
              localized
            }
          }
        }
        totalPrice {
          gross {
            localized
          }
          net {
            localized
          }
        }
      }
    }
  }
`

在服务器上,它返回以下错误:

graphql.error.base.GraphQLError: Variable "$checkoutInput" got invalid value {"email": "test@test.com", "lines": {"quantity": 10, "variantId": "UHJvZHVjdFZhcmlhbnQ6NQ=="}}.
In field "lines": In element #0: Expected "CheckoutLineInput", found not an object.

1 个答案:

答案 0 :(得分:1)

好像是我的大部分工作,我只是传递单个行对象而不是它们的数组。正确的代码如下:

try {
  this.app.apolloProvider.defaultClient
    .mutate({
      mutation: CREATE_CART_MUTATION,
      variables: {
        checkoutInput: {
          lines: [
            { quantity: cartItem.quantity, variantId: cartItem.variantId }
          ],
          email: 'test@test.com'
        }
      }
    })
    .then(({ data }) => {
      console.log('mutation done!')
      commit('SET_CHECKOUT_OBJECT', data.checkoutCreate.checkout)
    })
} catch (e) {
  console.log('error:')
  console.log(e)
}