1

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

根据 gql 游乐场,有一个突变可以这样做,它需要一个 CheckoutCreateInput 对象作为它的参数。

这是一个在操场上运行良好的示例突变。

示例 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.
4

1 回答 1

2

看起来我大部分时间都在那里,我只是传递一个单行对象而不是它们的数组。正确的代码如下:

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)
}
于 2019-06-04T09:27:21.567 回答