{"size": 1739, "ext": "js", "max_stars_repo_path": "src/context/CheckoutContext.js", "max_stars_repo_name": "dennislee-dev/gatsby-tailwind", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/context/CheckoutContext.js", "max_issues_repo_name": "dennislee-dev/gatsby-tailwind", "max_issues_repo_issues_event_min_datetime": "2021-03-11T03:20:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T09:04:11.000Z", "max_forks_repo_path": "src/context/CheckoutContext.js", "max_forks_repo_name": "dennislee-dev/gatsby-tailwind", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 7, "max_forks_count": null, "avg_line_length": 21.4691358025, "max_line_length": 76, "alphanum_fraction": 0.5974698102}
import React, { useContext, createContext } from 'react'

import { MoltinContext } from '.'

let CheckoutContext

const { Provider, Consumer } = (CheckoutContext = createContext())

function CheckoutProvider({ cartId: initialCartId, children, ...props }) {
  const { moltin } = useContext(MoltinContext)

  async function checkout(
    cartId = initialCartId,
    { customer, shipping_address, billing_address = shipping_address }
  ) {
    const createCustomer = customer && customer.password
    let customerId

    if (createCustomer) {
      const { data: newCustomer } = await moltin.post(`customers`, {
        type: 'customer',
        ...customer
      })

      customerId = newCustomer.id
    }

    const { data: order } = await moltin.post(`carts/${cartId}/checkout`, {
      ...(createCustomer ? { customer: { id: customerId } } : { customer }),
      shipping_address,
      billing_address
    })

    return order
  }

  async function pay({ gateway, method, orderId, ...rest }) {
    try {
      const { data } = await moltin.post(`orders/${orderId}/payments`, {
        gateway,
        method,
        ...rest
      })

      return data
    } catch (err) {
      throw new Error(err.message || 'Payment failed')
    }
  }

  async function confirmTransaction({
    gateway,
    orderId,
    payment,
    transactionId
  }) {
    await moltin.post(
      `orders/${orderId}/transactions/${transactionId}/confirm`,
      {
        payment,
        gateway
      }
    )
  }

  return (
    <Provider
      value={{
        ...props,
        checkout,
        pay,
        confirmTransaction
      }}
    >
      {children}
    </Provider>
  )
}

export { CheckoutProvider, Consumer as CheckoutConsumer, CheckoutContext }
