forked from crowetic/commerce
Remove updated hooks
This commit is contained in:
parent
7aa9019ada
commit
c82f2c5e61
@ -1,40 +0,0 @@
|
||||
import { parseCartItem } from '../../utils/parse-item'
|
||||
import getCartCookie from '../../utils/get-cart-cookie'
|
||||
import type { CartHandlers } from '..'
|
||||
|
||||
// Return current cart info
|
||||
const addItem: CartHandlers['addItem'] = async ({
|
||||
res,
|
||||
body: { cartId, item },
|
||||
config,
|
||||
}) => {
|
||||
if (!item) {
|
||||
return res.status(400).json({
|
||||
data: null,
|
||||
errors: [{ message: 'Missing item' }],
|
||||
})
|
||||
}
|
||||
if (!item.quantity) item.quantity = 1
|
||||
|
||||
const options = {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
line_items: [parseCartItem(item)],
|
||||
...(!cartId && config.storeChannelId
|
||||
? { channel_id: config.storeChannelId }
|
||||
: {}),
|
||||
}),
|
||||
}
|
||||
const { data } = cartId
|
||||
? await config.storeApiFetch(`/v3/carts/${cartId}/items`, options)
|
||||
: await config.storeApiFetch('/v3/carts', options)
|
||||
|
||||
// Create or update the cart cookie
|
||||
res.setHeader(
|
||||
'Set-Cookie',
|
||||
getCartCookie(config.cartCookie, data.id, config.cartCookieMaxAge)
|
||||
)
|
||||
res.status(200).json({ data })
|
||||
}
|
||||
|
||||
export default addItem
|
@ -1,77 +0,0 @@
|
||||
import isAllowedMethod from './utils/is-allowed-method'
|
||||
import createApiHandler, {
|
||||
BigcommerceApiHandler,
|
||||
} from './utils/create-api-handler'
|
||||
import { BigcommerceApiError } from './utils/errors'
|
||||
|
||||
const METHODS = ['GET']
|
||||
const fullCheckout = true
|
||||
|
||||
// TODO: a complete implementation should have schema validation for `req.body`
|
||||
const checkoutApi: BigcommerceApiHandler<any> = async (req, res, config) => {
|
||||
if (!isAllowedMethod(req, res, METHODS)) return
|
||||
|
||||
const { cookies } = req
|
||||
const cartId = cookies[config.cartCookie]
|
||||
|
||||
try {
|
||||
if (!cartId) {
|
||||
res.redirect('/cart')
|
||||
return
|
||||
}
|
||||
|
||||
const { data } = await config.storeApiFetch(
|
||||
`/v3/carts/${cartId}/redirect_urls`,
|
||||
{
|
||||
method: 'POST',
|
||||
}
|
||||
)
|
||||
|
||||
if (fullCheckout) {
|
||||
res.redirect(data.checkout_url)
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: make the embedded checkout work too!
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Checkout</title>
|
||||
<script src="https://checkout-sdk.bigcommerce.com/v1/loader.js"></script>
|
||||
<script>
|
||||
window.onload = function() {
|
||||
checkoutKitLoader.load('checkout-sdk').then(function (service) {
|
||||
service.embedCheckout({
|
||||
containerId: 'checkout',
|
||||
url: '${data.embedded_checkout_url}'
|
||||
});
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="checkout"></div>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
res.status(200)
|
||||
res.setHeader('Content-Type', 'text/html')
|
||||
res.write(html)
|
||||
res.end()
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
|
||||
const message =
|
||||
error instanceof BigcommerceApiError
|
||||
? 'An unexpected error ocurred with the Bigcommerce API'
|
||||
: 'An unexpected error ocurred'
|
||||
|
||||
res.status(500).json({ data: null, errors: [{ message }] })
|
||||
}
|
||||
}
|
||||
|
||||
export default createApiHandler(checkoutApi, {}, {})
|
@ -1,113 +0,0 @@
|
||||
export const productPrices = /* GraphQL */ `
|
||||
fragment productPrices on Prices {
|
||||
price {
|
||||
value
|
||||
currencyCode
|
||||
}
|
||||
salePrice {
|
||||
value
|
||||
currencyCode
|
||||
}
|
||||
retailPrice {
|
||||
value
|
||||
currencyCode
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export const swatchOptionFragment = /* GraphQL */ `
|
||||
fragment swatchOption on SwatchOptionValue {
|
||||
isDefault
|
||||
hexColors
|
||||
}
|
||||
`
|
||||
|
||||
export const multipleChoiceOptionFragment = /* GraphQL */ `
|
||||
fragment multipleChoiceOption on MultipleChoiceOption {
|
||||
values {
|
||||
edges {
|
||||
node {
|
||||
label
|
||||
...swatchOption
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
${swatchOptionFragment}
|
||||
`
|
||||
|
||||
export const productInfoFragment = /* GraphQL */ `
|
||||
fragment productInfo on Product {
|
||||
entityId
|
||||
name
|
||||
path
|
||||
brand {
|
||||
entityId
|
||||
}
|
||||
description
|
||||
prices {
|
||||
...productPrices
|
||||
}
|
||||
images {
|
||||
edges {
|
||||
node {
|
||||
urlOriginal
|
||||
altText
|
||||
isDefault
|
||||
}
|
||||
}
|
||||
}
|
||||
variants {
|
||||
edges {
|
||||
node {
|
||||
entityId
|
||||
defaultImage {
|
||||
urlOriginal
|
||||
altText
|
||||
isDefault
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
productOptions {
|
||||
edges {
|
||||
node {
|
||||
__typename
|
||||
entityId
|
||||
displayName
|
||||
...multipleChoiceOption
|
||||
}
|
||||
}
|
||||
}
|
||||
localeMeta: metafields(namespace: $locale, keys: ["name", "description"])
|
||||
@include(if: $hasLocale) {
|
||||
edges {
|
||||
node {
|
||||
key
|
||||
value
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
${productPrices}
|
||||
${multipleChoiceOptionFragment}
|
||||
`
|
||||
|
||||
export const productConnectionFragment = /* GraphQL */ `
|
||||
fragment productConnnection on ProductConnection {
|
||||
pageInfo {
|
||||
startCursor
|
||||
endCursor
|
||||
}
|
||||
edges {
|
||||
cursor
|
||||
node {
|
||||
...productInfo
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
${productInfoFragment}
|
||||
`
|
@ -1,88 +0,0 @@
|
||||
import type { RequestInit } from '@vercel/fetch'
|
||||
import type { CommerceAPIConfig } from '../../commerce/api'
|
||||
import fetchGraphqlApi from './utils/fetch-graphql-api'
|
||||
import fetchStoreApi from './utils/fetch-store-api'
|
||||
|
||||
export interface BigcommerceConfig extends CommerceAPIConfig {
|
||||
// Indicates if the returned metadata with translations should be applied to the
|
||||
// data or returned as it is
|
||||
applyLocale?: boolean
|
||||
storeApiUrl: string
|
||||
storeApiToken: string
|
||||
storeApiClientId: string
|
||||
storeChannelId?: string
|
||||
storeApiFetch<T>(endpoint: string, options?: RequestInit): Promise<T>
|
||||
}
|
||||
|
||||
const API_URL = process.env.BIGCOMMERCE_STOREFRONT_API_URL
|
||||
const API_TOKEN = process.env.BIGCOMMERCE_STOREFRONT_API_TOKEN
|
||||
const STORE_API_URL = process.env.BIGCOMMERCE_STORE_API_URL
|
||||
const STORE_API_TOKEN = process.env.BIGCOMMERCE_STORE_API_TOKEN
|
||||
const STORE_API_CLIENT_ID = process.env.BIGCOMMERCE_STORE_API_CLIENT_ID
|
||||
const STORE_CHANNEL_ID = process.env.BIGCOMMERCE_CHANNEL_ID
|
||||
|
||||
if (!API_URL) {
|
||||
throw new Error(
|
||||
`The environment variable BIGCOMMERCE_STOREFRONT_API_URL is missing and it's required to access your store`
|
||||
)
|
||||
}
|
||||
|
||||
if (!API_TOKEN) {
|
||||
throw new Error(
|
||||
`The environment variable BIGCOMMERCE_STOREFRONT_API_TOKEN is missing and it's required to access your store`
|
||||
)
|
||||
}
|
||||
|
||||
if (!(STORE_API_URL && STORE_API_TOKEN && STORE_API_CLIENT_ID)) {
|
||||
throw new Error(
|
||||
`The environment variables BIGCOMMERCE_STORE_API_URL, BIGCOMMERCE_STORE_API_TOKEN, BIGCOMMERCE_STORE_API_CLIENT_ID have to be set in order to access the REST API of your store`
|
||||
)
|
||||
}
|
||||
|
||||
export class Config {
|
||||
private config: BigcommerceConfig
|
||||
|
||||
constructor(config: Omit<BigcommerceConfig, 'customerCookie'>) {
|
||||
this.config = {
|
||||
...config,
|
||||
// The customerCookie is not customizable for now, BC sets the cookie and it's
|
||||
// not important to rename it
|
||||
customerCookie: 'SHOP_TOKEN',
|
||||
}
|
||||
}
|
||||
|
||||
getConfig(userConfig: Partial<BigcommerceConfig> = {}) {
|
||||
return Object.entries(userConfig).reduce<BigcommerceConfig>(
|
||||
(cfg, [key, value]) => Object.assign(cfg, { [key]: value }),
|
||||
{ ...this.config }
|
||||
)
|
||||
}
|
||||
|
||||
setConfig(newConfig: Partial<BigcommerceConfig>) {
|
||||
Object.assign(this.config, newConfig)
|
||||
}
|
||||
}
|
||||
|
||||
const ONE_DAY = 60 * 60 * 24
|
||||
const config = new Config({
|
||||
commerceUrl: API_URL,
|
||||
apiToken: API_TOKEN,
|
||||
cartCookie: process.env.BIGCOMMERCE_CART_COOKIE ?? 'bc_cartId',
|
||||
cartCookieMaxAge: ONE_DAY * 30,
|
||||
fetch: fetchGraphqlApi,
|
||||
applyLocale: true,
|
||||
// REST API only
|
||||
storeApiUrl: STORE_API_URL,
|
||||
storeApiToken: STORE_API_TOKEN,
|
||||
storeApiClientId: STORE_API_CLIENT_ID,
|
||||
storeChannelId: STORE_CHANNEL_ID,
|
||||
storeApiFetch: fetchStoreApi,
|
||||
})
|
||||
|
||||
export function getConfig(userConfig?: Partial<BigcommerceConfig>) {
|
||||
return config.getConfig(userConfig)
|
||||
}
|
||||
|
||||
export function setConfig(newConfig: Partial<BigcommerceConfig>) {
|
||||
return config.setConfig(newConfig)
|
||||
}
|
@ -1,132 +0,0 @@
|
||||
import type {
|
||||
GetAllProductsQuery,
|
||||
GetAllProductsQueryVariables,
|
||||
} from '../../schema'
|
||||
import type { RecursivePartial, RecursiveRequired } from '../utils/types'
|
||||
import filterEdges from '../utils/filter-edges'
|
||||
import setProductLocaleMeta from '../utils/set-product-locale-meta'
|
||||
import { productConnectionFragment } from '../fragments/product'
|
||||
import { BigcommerceConfig, getConfig } from '..'
|
||||
|
||||
export const getAllProductsQuery = /* GraphQL */ `
|
||||
query getAllProducts(
|
||||
$hasLocale: Boolean = false
|
||||
$locale: String = "null"
|
||||
$entityIds: [Int!]
|
||||
$first: Int = 10
|
||||
$products: Boolean = false
|
||||
$featuredProducts: Boolean = false
|
||||
$bestSellingProducts: Boolean = false
|
||||
$newestProducts: Boolean = false
|
||||
) {
|
||||
site {
|
||||
products(first: $first, entityIds: $entityIds) @include(if: $products) {
|
||||
...productConnnection
|
||||
}
|
||||
featuredProducts(first: $first) @include(if: $featuredProducts) {
|
||||
...productConnnection
|
||||
}
|
||||
bestSellingProducts(first: $first) @include(if: $bestSellingProducts) {
|
||||
...productConnnection
|
||||
}
|
||||
newestProducts(first: $first) @include(if: $newestProducts) {
|
||||
...productConnnection
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
${productConnectionFragment}
|
||||
`
|
||||
|
||||
export type ProductEdge = NonNullable<
|
||||
NonNullable<GetAllProductsQuery['site']['products']['edges']>[0]
|
||||
>
|
||||
|
||||
export type ProductNode = ProductEdge['node']
|
||||
|
||||
export type GetAllProductsResult<
|
||||
T extends Record<keyof GetAllProductsResult, any[]> = {
|
||||
products: ProductEdge[]
|
||||
}
|
||||
> = T
|
||||
|
||||
const FIELDS = [
|
||||
'products',
|
||||
'featuredProducts',
|
||||
'bestSellingProducts',
|
||||
'newestProducts',
|
||||
]
|
||||
|
||||
export type ProductTypes =
|
||||
| 'products'
|
||||
| 'featuredProducts'
|
||||
| 'bestSellingProducts'
|
||||
| 'newestProducts'
|
||||
|
||||
export type ProductVariables = { field?: ProductTypes } & Omit<
|
||||
GetAllProductsQueryVariables,
|
||||
ProductTypes | 'hasLocale'
|
||||
>
|
||||
|
||||
async function getAllProducts(opts?: {
|
||||
variables?: ProductVariables
|
||||
config?: BigcommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<GetAllProductsResult>
|
||||
|
||||
async function getAllProducts<
|
||||
T extends Record<keyof GetAllProductsResult, any[]>,
|
||||
V = any
|
||||
>(opts: {
|
||||
query: string
|
||||
variables?: V
|
||||
config?: BigcommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<GetAllProductsResult<T>>
|
||||
|
||||
async function getAllProducts({
|
||||
query = getAllProductsQuery,
|
||||
variables: { field = 'products', ...vars } = {},
|
||||
config,
|
||||
}: {
|
||||
query?: string
|
||||
variables?: ProductVariables
|
||||
config?: BigcommerceConfig
|
||||
preview?: boolean
|
||||
} = {}): Promise<GetAllProductsResult> {
|
||||
config = getConfig(config)
|
||||
|
||||
const locale = vars.locale || config.locale
|
||||
const variables: GetAllProductsQueryVariables = {
|
||||
...vars,
|
||||
locale,
|
||||
hasLocale: !!locale,
|
||||
}
|
||||
|
||||
if (!FIELDS.includes(field)) {
|
||||
throw new Error(
|
||||
`The field variable has to match one of ${FIELDS.join(', ')}`
|
||||
)
|
||||
}
|
||||
|
||||
variables[field] = true
|
||||
|
||||
// RecursivePartial forces the method to check for every prop in the data, which is
|
||||
// required in case there's a custom `query`
|
||||
const { data } = await config.fetch<RecursivePartial<GetAllProductsQuery>>(
|
||||
query,
|
||||
{ variables }
|
||||
)
|
||||
const edges = data.site?.[field]?.edges
|
||||
const products = filterEdges(edges as RecursiveRequired<typeof edges>)
|
||||
|
||||
if (locale && config.applyLocale) {
|
||||
products.forEach((product: RecursivePartial<ProductEdge>) => {
|
||||
if (product.node) setProductLocaleMeta(product.node)
|
||||
})
|
||||
}
|
||||
|
||||
return { products }
|
||||
}
|
||||
|
||||
export default getAllProducts
|
@ -1,87 +0,0 @@
|
||||
import type { RecursivePartial, RecursiveRequired } from '../utils/types'
|
||||
import { definitions } from '../definitions/wishlist'
|
||||
import { BigcommerceConfig, getConfig } from '..'
|
||||
import getAllProducts, { ProductEdge } from './get-all-products'
|
||||
|
||||
export type Wishlist = Omit<definitions['wishlist_Full'], 'items'> & {
|
||||
items?: WishlistItem[]
|
||||
}
|
||||
|
||||
export type WishlistItem = NonNullable<
|
||||
definitions['wishlist_Full']['items']
|
||||
>[0] & {
|
||||
product?: ProductEdge['node']
|
||||
}
|
||||
|
||||
export type GetCustomerWishlistResult<
|
||||
T extends { wishlist?: any } = { wishlist?: Wishlist }
|
||||
> = T
|
||||
|
||||
export type GetCustomerWishlistVariables = {
|
||||
customerId: number
|
||||
}
|
||||
|
||||
async function getCustomerWishlist(opts: {
|
||||
variables: GetCustomerWishlistVariables
|
||||
config?: BigcommerceConfig
|
||||
includeProducts?: boolean
|
||||
}): Promise<GetCustomerWishlistResult>
|
||||
|
||||
async function getCustomerWishlist<
|
||||
T extends { wishlist?: any },
|
||||
V = any
|
||||
>(opts: {
|
||||
url: string
|
||||
variables: V
|
||||
config?: BigcommerceConfig
|
||||
includeProducts?: boolean
|
||||
}): Promise<GetCustomerWishlistResult<T>>
|
||||
|
||||
async function getCustomerWishlist({
|
||||
config,
|
||||
variables,
|
||||
includeProducts,
|
||||
}: {
|
||||
url?: string
|
||||
variables: GetCustomerWishlistVariables
|
||||
config?: BigcommerceConfig
|
||||
includeProducts?: boolean
|
||||
}): Promise<GetCustomerWishlistResult> {
|
||||
config = getConfig(config)
|
||||
|
||||
const { data = [] } = await config.storeApiFetch<
|
||||
RecursivePartial<{ data: Wishlist[] }>
|
||||
>(`/v3/wishlists?customer_id=${variables.customerId}`)
|
||||
const wishlist = data[0]
|
||||
|
||||
if (includeProducts && wishlist?.items?.length) {
|
||||
const entityIds = wishlist.items
|
||||
?.map((item) => item?.product_id)
|
||||
.filter((id): id is number => !!id)
|
||||
|
||||
if (entityIds?.length) {
|
||||
const graphqlData = await getAllProducts({
|
||||
variables: { first: 100, entityIds },
|
||||
config,
|
||||
})
|
||||
// Put the products in an object that we can use to get them by id
|
||||
const productsById = graphqlData.products.reduce<{
|
||||
[k: number]: ProductEdge
|
||||
}>((prods, p) => {
|
||||
prods[p.node.entityId] = p
|
||||
return prods
|
||||
}, {})
|
||||
// Populate the wishlist items with the graphql products
|
||||
wishlist.items.forEach((item) => {
|
||||
const product = item && productsById[item.product_id!]
|
||||
if (item && product) {
|
||||
item.product = product.node
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return { wishlist: wishlist as RecursiveRequired<typeof wishlist> }
|
||||
}
|
||||
|
||||
export default getCustomerWishlist
|
@ -1,118 +0,0 @@
|
||||
import type { GetProductQuery, GetProductQueryVariables } from '../../schema'
|
||||
import setProductLocaleMeta from '../utils/set-product-locale-meta'
|
||||
import { productInfoFragment } from '../fragments/product'
|
||||
import { BigcommerceConfig, getConfig } from '..'
|
||||
|
||||
export const getProductQuery = /* GraphQL */ `
|
||||
query getProduct(
|
||||
$hasLocale: Boolean = false
|
||||
$locale: String = "null"
|
||||
$path: String!
|
||||
) {
|
||||
site {
|
||||
route(path: $path) {
|
||||
node {
|
||||
__typename
|
||||
... on Product {
|
||||
...productInfo
|
||||
variants {
|
||||
edges {
|
||||
node {
|
||||
entityId
|
||||
defaultImage {
|
||||
urlOriginal
|
||||
altText
|
||||
isDefault
|
||||
}
|
||||
prices {
|
||||
...productPrices
|
||||
}
|
||||
inventory {
|
||||
aggregated {
|
||||
availableToSell
|
||||
warningLevel
|
||||
}
|
||||
isInStock
|
||||
}
|
||||
productOptions {
|
||||
edges {
|
||||
node {
|
||||
__typename
|
||||
entityId
|
||||
displayName
|
||||
...multipleChoiceOption
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
${productInfoFragment}
|
||||
`
|
||||
|
||||
export type ProductNode = Extract<
|
||||
GetProductQuery['site']['route']['node'],
|
||||
{ __typename: 'Product' }
|
||||
>
|
||||
|
||||
export type GetProductResult<
|
||||
T extends { product?: any } = { product?: ProductNode }
|
||||
> = T
|
||||
|
||||
export type ProductVariables = { locale?: string } & (
|
||||
| { path: string; slug?: never }
|
||||
| { path?: never; slug: string }
|
||||
)
|
||||
|
||||
async function getProduct(opts: {
|
||||
variables: ProductVariables
|
||||
config?: BigcommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<GetProductResult>
|
||||
|
||||
async function getProduct<T extends { product?: any }, V = any>(opts: {
|
||||
query: string
|
||||
variables: V
|
||||
config?: BigcommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<GetProductResult<T>>
|
||||
|
||||
async function getProduct({
|
||||
query = getProductQuery,
|
||||
variables: { slug, ...vars },
|
||||
config,
|
||||
}: {
|
||||
query?: string
|
||||
variables: ProductVariables
|
||||
config?: BigcommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<GetProductResult> {
|
||||
config = getConfig(config)
|
||||
|
||||
const locale = vars.locale || config.locale
|
||||
const variables: GetProductQueryVariables = {
|
||||
...vars,
|
||||
locale,
|
||||
hasLocale: !!locale,
|
||||
path: slug ? `/${slug}/` : vars.path!,
|
||||
}
|
||||
const { data } = await config.fetch<GetProductQuery>(query, { variables })
|
||||
const product = data.site?.route?.node
|
||||
|
||||
if (product?.__typename === 'Product') {
|
||||
if (locale && config.applyLocale) {
|
||||
setProductLocaleMeta(product)
|
||||
}
|
||||
return { product }
|
||||
}
|
||||
|
||||
return {}
|
||||
}
|
||||
|
||||
export default getProduct
|
@ -1,106 +0,0 @@
|
||||
import type { GetSiteInfoQuery, GetSiteInfoQueryVariables } from '../../schema'
|
||||
import type { RecursivePartial, RecursiveRequired } from '../utils/types'
|
||||
import filterEdges from '../utils/filter-edges'
|
||||
import { BigcommerceConfig, getConfig } from '..'
|
||||
import { categoryTreeItemFragment } from '../fragments/category-tree'
|
||||
|
||||
// Get 3 levels of categories
|
||||
export const getSiteInfoQuery = /* GraphQL */ `
|
||||
query getSiteInfo {
|
||||
site {
|
||||
categoryTree {
|
||||
...categoryTreeItem
|
||||
children {
|
||||
...categoryTreeItem
|
||||
children {
|
||||
...categoryTreeItem
|
||||
}
|
||||
}
|
||||
}
|
||||
brands {
|
||||
pageInfo {
|
||||
startCursor
|
||||
endCursor
|
||||
}
|
||||
edges {
|
||||
cursor
|
||||
node {
|
||||
entityId
|
||||
name
|
||||
defaultImage {
|
||||
urlOriginal
|
||||
altText
|
||||
}
|
||||
pageTitle
|
||||
metaDesc
|
||||
metaKeywords
|
||||
searchKeywords
|
||||
path
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
${categoryTreeItemFragment}
|
||||
`
|
||||
|
||||
export type CategoriesTree = NonNullable<
|
||||
GetSiteInfoQuery['site']['categoryTree']
|
||||
>
|
||||
|
||||
export type BrandEdge = NonNullable<
|
||||
NonNullable<GetSiteInfoQuery['site']['brands']['edges']>[0]
|
||||
>
|
||||
|
||||
export type Brands = BrandEdge[]
|
||||
|
||||
export type GetSiteInfoResult<
|
||||
T extends { categories: any[]; brands: any[] } = {
|
||||
categories: CategoriesTree
|
||||
brands: Brands
|
||||
}
|
||||
> = T
|
||||
|
||||
async function getSiteInfo(opts?: {
|
||||
variables?: GetSiteInfoQueryVariables
|
||||
config?: BigcommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<GetSiteInfoResult>
|
||||
|
||||
async function getSiteInfo<
|
||||
T extends { categories: any[]; brands: any[] },
|
||||
V = any
|
||||
>(opts: {
|
||||
query: string
|
||||
variables?: V
|
||||
config?: BigcommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<GetSiteInfoResult<T>>
|
||||
|
||||
async function getSiteInfo({
|
||||
query = getSiteInfoQuery,
|
||||
variables,
|
||||
config,
|
||||
}: {
|
||||
query?: string
|
||||
variables?: GetSiteInfoQueryVariables
|
||||
config?: BigcommerceConfig
|
||||
preview?: boolean
|
||||
} = {}): Promise<GetSiteInfoResult> {
|
||||
config = getConfig(config)
|
||||
// RecursivePartial forces the method to check for every prop in the data, which is
|
||||
// required in case there's a custom `query`
|
||||
const { data } = await config.fetch<RecursivePartial<GetSiteInfoQuery>>(
|
||||
query,
|
||||
{ variables }
|
||||
)
|
||||
const categories = data.site?.categoryTree
|
||||
const brands = data.site?.brands?.edges
|
||||
|
||||
return {
|
||||
categories: (categories as RecursiveRequired<typeof categories>) ?? [],
|
||||
brands: filterEdges(brands as RecursiveRequired<typeof brands>),
|
||||
}
|
||||
}
|
||||
|
||||
export default getSiteInfo
|
@ -1,37 +0,0 @@
|
||||
import getCustomerId from '../../operations/get-customer-id'
|
||||
import getCustomerWishlist from '../../operations/get-customer-wishlist'
|
||||
import type { Wishlist, WishlistHandlers } from '..'
|
||||
|
||||
// Return wishlist info
|
||||
const getWishlist: WishlistHandlers['getWishlist'] = async ({
|
||||
res,
|
||||
body: { customerToken, includeProducts },
|
||||
config,
|
||||
}) => {
|
||||
let result: { data?: Wishlist } = {}
|
||||
|
||||
if (customerToken) {
|
||||
const customerId =
|
||||
customerToken && (await getCustomerId({ customerToken, config }))
|
||||
|
||||
if (!customerId) {
|
||||
// If the customerToken is invalid, then this request is too
|
||||
return res.status(404).json({
|
||||
data: null,
|
||||
errors: [{ message: 'Wishlist not found' }],
|
||||
})
|
||||
}
|
||||
|
||||
const { wishlist } = await getCustomerWishlist({
|
||||
variables: { customerId },
|
||||
includeProducts,
|
||||
config,
|
||||
})
|
||||
|
||||
result = { data: wishlist }
|
||||
}
|
||||
|
||||
res.status(200).json({ data: result.data ?? null })
|
||||
}
|
||||
|
||||
export default getWishlist
|
@ -1,103 +0,0 @@
|
||||
import isAllowedMethod from '../utils/is-allowed-method'
|
||||
import createApiHandler, {
|
||||
BigcommerceApiHandler,
|
||||
BigcommerceHandler,
|
||||
} from '../utils/create-api-handler'
|
||||
import { BigcommerceApiError } from '../utils/errors'
|
||||
import type {
|
||||
Wishlist,
|
||||
WishlistItem,
|
||||
} from '../operations/get-customer-wishlist'
|
||||
import getWishlist from './handlers/get-wishlist'
|
||||
import addItem from './handlers/add-item'
|
||||
import removeItem from './handlers/remove-item'
|
||||
|
||||
export type { Wishlist, WishlistItem }
|
||||
|
||||
export type ItemBody = {
|
||||
productId: number
|
||||
variantId: number
|
||||
}
|
||||
|
||||
export type AddItemBody = { item: ItemBody }
|
||||
|
||||
export type RemoveItemBody = { itemId: string }
|
||||
|
||||
export type WishlistBody = {
|
||||
customer_id: number
|
||||
is_public: number
|
||||
name: string
|
||||
items: any[]
|
||||
}
|
||||
|
||||
export type AddWishlistBody = { wishlist: WishlistBody }
|
||||
|
||||
export type WishlistHandlers = {
|
||||
getWishlist: BigcommerceHandler<
|
||||
Wishlist,
|
||||
{ customerToken?: string; includeProducts?: boolean }
|
||||
>
|
||||
addItem: BigcommerceHandler<
|
||||
Wishlist,
|
||||
{ customerToken?: string } & Partial<AddItemBody>
|
||||
>
|
||||
removeItem: BigcommerceHandler<
|
||||
Wishlist,
|
||||
{ customerToken?: string } & Partial<RemoveItemBody>
|
||||
>
|
||||
}
|
||||
|
||||
const METHODS = ['GET', 'POST', 'DELETE']
|
||||
|
||||
// TODO: a complete implementation should have schema validation for `req.body`
|
||||
const wishlistApi: BigcommerceApiHandler<Wishlist, WishlistHandlers> = async (
|
||||
req,
|
||||
res,
|
||||
config,
|
||||
handlers
|
||||
) => {
|
||||
if (!isAllowedMethod(req, res, METHODS)) return
|
||||
|
||||
const { cookies } = req
|
||||
const customerToken = cookies[config.customerCookie]
|
||||
|
||||
try {
|
||||
// Return current wishlist info
|
||||
if (req.method === 'GET') {
|
||||
const body = {
|
||||
customerToken,
|
||||
includeProducts: req.query.products === '1',
|
||||
}
|
||||
return await handlers['getWishlist']({ req, res, config, body })
|
||||
}
|
||||
|
||||
// Add an item to the wishlist
|
||||
if (req.method === 'POST') {
|
||||
const body = { ...req.body, customerToken }
|
||||
return await handlers['addItem']({ req, res, config, body })
|
||||
}
|
||||
|
||||
// Remove an item from the wishlist
|
||||
if (req.method === 'DELETE') {
|
||||
const body = { ...req.body, customerToken }
|
||||
return await handlers['removeItem']({ req, res, config, body })
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
|
||||
const message =
|
||||
error instanceof BigcommerceApiError
|
||||
? 'An unexpected error ocurred with the Bigcommerce API'
|
||||
: 'An unexpected error ocurred'
|
||||
|
||||
res.status(500).json({ data: null, errors: [{ message }] })
|
||||
}
|
||||
}
|
||||
|
||||
export const handlers = {
|
||||
getWishlist,
|
||||
addItem,
|
||||
removeItem,
|
||||
}
|
||||
|
||||
export default createApiHandler(wishlistApi, handlers, {})
|
@ -1,51 +0,0 @@
|
||||
import { useCallback } from 'react'
|
||||
import { HookFetcher } from '../../commerce/utils/types'
|
||||
import useCartRemoveItem from '../../commerce/cart/use-remove-item'
|
||||
import type { RemoveItemBody } from '../api/cart'
|
||||
import useCart, { Cart } from './use-cart'
|
||||
|
||||
const defaultOpts = {
|
||||
url: '/api/bigcommerce/cart',
|
||||
method: 'DELETE',
|
||||
}
|
||||
|
||||
export type RemoveItemInput = {
|
||||
id: string
|
||||
}
|
||||
|
||||
export const fetcher: HookFetcher<Cart | null, RemoveItemBody> = (
|
||||
options,
|
||||
{ itemId },
|
||||
fetch
|
||||
) => {
|
||||
return fetch({
|
||||
...defaultOpts,
|
||||
...options,
|
||||
body: { itemId },
|
||||
})
|
||||
}
|
||||
|
||||
export function extendHook(customFetcher: typeof fetcher) {
|
||||
const useRemoveItem = (item?: any) => {
|
||||
const { mutate } = useCart()
|
||||
const fn = useCartRemoveItem<Cart | null, RemoveItemBody>(
|
||||
defaultOpts,
|
||||
customFetcher
|
||||
)
|
||||
|
||||
return useCallback(
|
||||
async function removeItem(input: RemoveItemInput) {
|
||||
const data = await fn({ itemId: input.id ?? item?.id })
|
||||
await mutate(data, false)
|
||||
return data
|
||||
},
|
||||
[fn, mutate]
|
||||
)
|
||||
}
|
||||
|
||||
useRemoveItem.extend = extendHook
|
||||
|
||||
return useRemoveItem
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
2064
lib/bigcommerce/schema.d.ts
vendored
2064
lib/bigcommerce/schema.d.ts
vendored
File diff suppressed because it is too large
Load Diff
@ -1,57 +0,0 @@
|
||||
import { useCallback } from 'react'
|
||||
import { HookFetcher } from '../../commerce/utils/types'
|
||||
import { CommerceError } from '../../commerce/utils/errors'
|
||||
import useWishlistAddItem from '../../commerce/wishlist/use-add-item'
|
||||
import type { ItemBody, AddItemBody } from '../api/wishlist'
|
||||
import useCustomer from '../use-customer'
|
||||
import useWishlist, { UseWishlistOptions, Wishlist } from './use-wishlist'
|
||||
|
||||
const defaultOpts = {
|
||||
url: '/api/bigcommerce/wishlist',
|
||||
method: 'POST',
|
||||
}
|
||||
|
||||
export type AddItemInput = ItemBody
|
||||
|
||||
export const fetcher: HookFetcher<Wishlist, AddItemBody> = (
|
||||
options,
|
||||
{ item },
|
||||
fetch
|
||||
) => {
|
||||
// TODO: add validations before doing the fetch
|
||||
return fetch({
|
||||
...defaultOpts,
|
||||
...options,
|
||||
body: { item },
|
||||
})
|
||||
}
|
||||
|
||||
export function extendHook(customFetcher: typeof fetcher) {
|
||||
const useAddItem = (opts?: UseWishlistOptions) => {
|
||||
const { data: customer } = useCustomer()
|
||||
const { revalidate } = useWishlist(opts)
|
||||
const fn = useWishlistAddItem(defaultOpts, customFetcher)
|
||||
|
||||
return useCallback(
|
||||
async function addItem(input: AddItemInput) {
|
||||
if (!customer) {
|
||||
// A signed customer is required in order to have a wishlist
|
||||
throw new CommerceError({
|
||||
message: 'Signed customer not found',
|
||||
})
|
||||
}
|
||||
|
||||
const data = await fn({ item: input })
|
||||
await revalidate()
|
||||
return data
|
||||
},
|
||||
[fn, revalidate, customer]
|
||||
)
|
||||
}
|
||||
|
||||
useAddItem.extend = extendHook
|
||||
|
||||
return useAddItem
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
@ -1,61 +0,0 @@
|
||||
import { useCallback } from 'react'
|
||||
import { HookFetcher } from '../../commerce/utils/types'
|
||||
import { CommerceError } from '../../commerce/utils/errors'
|
||||
import useWishlistRemoveItem from '../../commerce/wishlist/use-remove-item'
|
||||
import type { RemoveItemBody } from '../api/wishlist'
|
||||
import useCustomer from '../use-customer'
|
||||
import useWishlist, { UseWishlistOptions, Wishlist } from './use-wishlist'
|
||||
|
||||
const defaultOpts = {
|
||||
url: '/api/bigcommerce/wishlist',
|
||||
method: 'DELETE',
|
||||
}
|
||||
|
||||
export type RemoveItemInput = {
|
||||
id: string | number
|
||||
}
|
||||
|
||||
export const fetcher: HookFetcher<Wishlist | null, RemoveItemBody> = (
|
||||
options,
|
||||
{ itemId },
|
||||
fetch
|
||||
) => {
|
||||
return fetch({
|
||||
...defaultOpts,
|
||||
...options,
|
||||
body: { itemId },
|
||||
})
|
||||
}
|
||||
|
||||
export function extendHook(customFetcher: typeof fetcher) {
|
||||
const useRemoveItem = (opts?: UseWishlistOptions) => {
|
||||
const { data: customer } = useCustomer()
|
||||
const { revalidate } = useWishlist(opts)
|
||||
const fn = useWishlistRemoveItem<Wishlist | null, RemoveItemBody>(
|
||||
defaultOpts,
|
||||
customFetcher
|
||||
)
|
||||
|
||||
return useCallback(
|
||||
async function removeItem(input: RemoveItemInput) {
|
||||
if (!customer) {
|
||||
// A signed customer is required in order to have a wishlist
|
||||
throw new CommerceError({
|
||||
message: 'Signed customer not found',
|
||||
})
|
||||
}
|
||||
|
||||
const data = await fn({ itemId: String(input.id) })
|
||||
await revalidate()
|
||||
return data
|
||||
},
|
||||
[fn, revalidate, customer]
|
||||
)
|
||||
}
|
||||
|
||||
useRemoveItem.extend = extendHook
|
||||
|
||||
return useRemoveItem
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
@ -1,76 +0,0 @@
|
||||
import { HookFetcher } from '../../commerce/utils/types'
|
||||
import { SwrOptions } from '../../commerce/utils/use-data'
|
||||
import useCommerceWishlist from '../../commerce/wishlist/use-wishlist'
|
||||
import type { Wishlist } from '../api/wishlist'
|
||||
import useCustomer from '../use-customer'
|
||||
|
||||
const defaultOpts = {
|
||||
url: '/api/bigcommerce/wishlist',
|
||||
method: 'GET',
|
||||
}
|
||||
|
||||
export type { Wishlist }
|
||||
|
||||
export interface UseWishlistOptions {
|
||||
includeProducts?: boolean
|
||||
}
|
||||
|
||||
export interface UseWishlistInput extends UseWishlistOptions {
|
||||
customerId?: number
|
||||
}
|
||||
|
||||
export const fetcher: HookFetcher<Wishlist | null, UseWishlistInput> = (
|
||||
options,
|
||||
{ customerId, includeProducts },
|
||||
fetch
|
||||
) => {
|
||||
if (!customerId) return null
|
||||
|
||||
// Use a dummy base as we only care about the relative path
|
||||
const url = new URL(options?.url ?? defaultOpts.url, 'http://a')
|
||||
|
||||
if (includeProducts) url.searchParams.set('products', '1')
|
||||
|
||||
return fetch({
|
||||
url: url.pathname + url.search,
|
||||
method: options?.method ?? defaultOpts.method,
|
||||
})
|
||||
}
|
||||
|
||||
export function extendHook(
|
||||
customFetcher: typeof fetcher,
|
||||
swrOptions?: SwrOptions<Wishlist | null, UseWishlistInput>
|
||||
) {
|
||||
const useWishlist = ({ includeProducts }: UseWishlistOptions = {}) => {
|
||||
const { data: customer } = useCustomer()
|
||||
const response = useCommerceWishlist(
|
||||
defaultOpts,
|
||||
[
|
||||
['customerId', customer?.entityId],
|
||||
['includeProducts', includeProducts],
|
||||
],
|
||||
customFetcher,
|
||||
{
|
||||
revalidateOnFocus: false,
|
||||
...swrOptions,
|
||||
}
|
||||
)
|
||||
|
||||
// Uses a getter to only calculate the prop when required
|
||||
// response.data is also a getter and it's better to not trigger it early
|
||||
Object.defineProperty(response, 'isEmpty', {
|
||||
get() {
|
||||
return (response.data?.items?.length || 0) <= 0
|
||||
},
|
||||
set: (x) => x,
|
||||
})
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
useWishlist.extend = extendHook
|
||||
|
||||
return useWishlist
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
@ -1,24 +0,0 @@
|
||||
// Core fetcher added by CommerceProvider
|
||||
export type Fetcher<T> = (options: FetcherOptions) => T | Promise<T>
|
||||
|
||||
export type FetcherOptions = {
|
||||
url?: string
|
||||
query?: string
|
||||
method?: string
|
||||
variables?: any
|
||||
body?: any
|
||||
}
|
||||
|
||||
export type HookFetcher<Result, Input = null> = (
|
||||
options: HookFetcherOptions | null,
|
||||
input: Input,
|
||||
fetch: <T = Result>(options: FetcherOptions) => Promise<T>
|
||||
) => Result | Promise<Result>
|
||||
|
||||
export type HookFetcherOptions = {
|
||||
query?: string
|
||||
url?: string
|
||||
method?: string
|
||||
}
|
||||
|
||||
export type HookInput = [string, string | number | boolean | undefined][]
|
Loading…
x
Reference in New Issue
Block a user