mirror of
https://github.com/vercel/commerce.git
synced 2025-06-19 13:41:22 +00:00
Merge branch 'nodejs-provider' of https://github.com/vercel/commerce into shopify-updates
This commit is contained in:
commit
15d6ff6709
@ -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,6 +1,5 @@
|
|||||||
import { Product } from '@commerce/types/product'
|
import { Product } from '@commerce/types/product'
|
||||||
import { ProductsEndpoint } from '.'
|
import { ProductsEndpoint } from '.'
|
||||||
import getAllProducts from '../../../../product/get-all-products'
|
|
||||||
|
|
||||||
const SORT: { [key: string]: string | undefined } = {
|
const SORT: { [key: string]: string | undefined } = {
|
||||||
latest: 'id',
|
latest: 'id',
|
||||||
@ -15,6 +14,7 @@ const getProducts: ProductsEndpoint['handlers']['getProducts'] = async ({
|
|||||||
res,
|
res,
|
||||||
body: { search, category, brand, sort },
|
body: { search, category, brand, sort },
|
||||||
config,
|
config,
|
||||||
|
commerce,
|
||||||
}) => {
|
}) => {
|
||||||
// Use a dummy base as we only care about the relative path
|
// Use a dummy base as we only care about the relative path
|
||||||
const url = new URL('/v3/catalog/products', 'http://a')
|
const url = new URL('/v3/catalog/products', 'http://a')
|
||||||
@ -47,18 +47,18 @@ const getProducts: ProductsEndpoint['handlers']['getProducts'] = async ({
|
|||||||
url.pathname + url.search
|
url.pathname + url.search
|
||||||
)
|
)
|
||||||
|
|
||||||
const entityIds = data.map((p) => p.id)
|
const ids = data.map((p) => String(p.id))
|
||||||
const found = entityIds.length > 0
|
const found = ids.length > 0
|
||||||
|
|
||||||
// We want the GraphQL version of each product
|
// We want the GraphQL version of each product
|
||||||
const graphqlData = await getAllProducts({
|
const graphqlData = await commerce.getAllProducts({
|
||||||
variables: { first: LIMIT, entityIds },
|
variables: { first: LIMIT, ids },
|
||||||
config,
|
config,
|
||||||
})
|
})
|
||||||
|
|
||||||
// Put the products in an object that we can use to get them by id
|
// Put the products in an object that we can use to get them by id
|
||||||
const productsById = graphqlData.products.reduce<{
|
const productsById = graphqlData.products.reduce<{
|
||||||
[k: number]: Product
|
[k: string]: Product
|
||||||
}>((prods, p) => {
|
}>((prods, p) => {
|
||||||
prods[Number(p.id)] = p
|
prods[Number(p.id)] = p
|
||||||
return prods
|
return prods
|
||||||
@ -68,7 +68,7 @@ const getProducts: ProductsEndpoint['handlers']['getProducts'] = async ({
|
|||||||
|
|
||||||
// Populate the products array with the graphql products, in the order
|
// Populate the products array with the graphql products, in the order
|
||||||
// assigned by the list of entity ids
|
// assigned by the list of entity ids
|
||||||
entityIds.forEach((id) => {
|
ids.forEach((id) => {
|
||||||
const product = productsById[id]
|
const product = productsById[id]
|
||||||
if (product) products.push(product)
|
if (product) products.push(product)
|
||||||
})
|
})
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import type { GetAPISchema } from '@commerce/api'
|
import { GetAPISchema, createEndpoint } from '@commerce/api'
|
||||||
|
import productsEndpoint from '@commerce/api/endpoints/catalog/products'
|
||||||
import type { ProductsSchema } from '../../../../types/product'
|
import type { ProductsSchema } from '../../../../types/product'
|
||||||
import type { BigcommerceAPI } from '../../..'
|
import type { BigcommerceAPI } from '../../..'
|
||||||
import getProducts from './get-products'
|
import getProducts from './get-products'
|
||||||
@ -7,4 +8,11 @@ export type ProductsAPI = GetAPISchema<BigcommerceAPI, ProductsSchema>
|
|||||||
|
|
||||||
export type ProductsEndpoint = ProductsAPI['endpoint']
|
export type ProductsEndpoint = ProductsAPI['endpoint']
|
||||||
|
|
||||||
export const handlers = { getProducts }
|
export const handlers: ProductsEndpoint['handlers'] = { getProducts }
|
||||||
|
|
||||||
|
const productsApi = createEndpoint<ProductsAPI>({
|
||||||
|
handler: productsEndpoint,
|
||||||
|
handlers,
|
||||||
|
})
|
||||||
|
|
||||||
|
export default productsApi
|
||||||
|
62
framework/bigcommerce/api/endpoints/checkout/checkout.ts
Normal file
62
framework/bigcommerce/api/endpoints/checkout/checkout.ts
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
import type { CheckoutEndpoint } from '.'
|
||||||
|
|
||||||
|
const fullCheckout = true
|
||||||
|
|
||||||
|
const checkout: CheckoutEndpoint['handlers']['checkout'] = async ({
|
||||||
|
req,
|
||||||
|
res,
|
||||||
|
config,
|
||||||
|
}) => {
|
||||||
|
const { cookies } = req
|
||||||
|
const cartId = cookies[config.cartCookie]
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
|
export default checkout
|
18
framework/bigcommerce/api/endpoints/checkout/index.ts
Normal file
18
framework/bigcommerce/api/endpoints/checkout/index.ts
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import { GetAPISchema, createEndpoint } from '@commerce/api'
|
||||||
|
import checkoutEndpoint from '@commerce/api/endpoints/checkout'
|
||||||
|
import type { CheckoutSchema } from '../../../types/checkout'
|
||||||
|
import type { BigcommerceAPI } from '../..'
|
||||||
|
import checkout from './checkout'
|
||||||
|
|
||||||
|
export type CheckoutAPI = GetAPISchema<BigcommerceAPI, CheckoutSchema>
|
||||||
|
|
||||||
|
export type CheckoutEndpoint = CheckoutAPI['endpoint']
|
||||||
|
|
||||||
|
export const handlers: CheckoutEndpoint['handlers'] = { checkout }
|
||||||
|
|
||||||
|
const checkoutApi = createEndpoint<CheckoutAPI>({
|
||||||
|
handler: checkoutEndpoint,
|
||||||
|
handlers,
|
||||||
|
})
|
||||||
|
|
||||||
|
export default checkoutApi
|
@ -1,4 +1,4 @@
|
|||||||
import getCustomerWishlist from '../../../customer/get-customer-wishlist'
|
import getCustomerWishlist from '../../operations/get-customer-wishlist'
|
||||||
import { parseWishlistItem } from '../../utils/parse-item'
|
import { parseWishlistItem } from '../../utils/parse-item'
|
||||||
import getCustomerId from './utils/get-customer-id'
|
import getCustomerId from './utils/get-customer-id'
|
||||||
import type { WishlistEndpoint } from '.'
|
import type { WishlistEndpoint } from '.'
|
||||||
@ -8,6 +8,7 @@ const addItem: WishlistEndpoint['handlers']['addItem'] = async ({
|
|||||||
res,
|
res,
|
||||||
body: { customerToken, item },
|
body: { customerToken, item },
|
||||||
config,
|
config,
|
||||||
|
commerce,
|
||||||
}) => {
|
}) => {
|
||||||
if (!item) {
|
if (!item) {
|
||||||
return res.status(400).json({
|
return res.status(400).json({
|
||||||
@ -26,7 +27,7 @@ const addItem: WishlistEndpoint['handlers']['addItem'] = async ({
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const { wishlist } = await getCustomerWishlist({
|
const { wishlist } = await commerce.getCustomerWishlist({
|
||||||
variables: { customerId },
|
variables: { customerId },
|
||||||
config,
|
config,
|
||||||
})
|
})
|
||||||
|
@ -1,13 +1,14 @@
|
|||||||
import type { Wishlist } from '../../../types/wishlist'
|
import type { Wishlist } from '../../../types/wishlist'
|
||||||
import type { WishlistEndpoint } from '.'
|
import type { WishlistEndpoint } from '.'
|
||||||
import getCustomerId from './utils/get-customer-id'
|
import getCustomerId from './utils/get-customer-id'
|
||||||
import getCustomerWishlist from '../../../customer/get-customer-wishlist'
|
import getCustomerWishlist from '../../operations/get-customer-wishlist'
|
||||||
|
|
||||||
// Return wishlist info
|
// Return wishlist info
|
||||||
const getWishlist: WishlistEndpoint['handlers']['getWishlist'] = async ({
|
const getWishlist: WishlistEndpoint['handlers']['getWishlist'] = async ({
|
||||||
res,
|
res,
|
||||||
body: { customerToken, includeProducts },
|
body: { customerToken, includeProducts },
|
||||||
config,
|
config,
|
||||||
|
commerce,
|
||||||
}) => {
|
}) => {
|
||||||
let result: { data?: Wishlist } = {}
|
let result: { data?: Wishlist } = {}
|
||||||
|
|
||||||
@ -23,7 +24,7 @@ const getWishlist: WishlistEndpoint['handlers']['getWishlist'] = async ({
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const { wishlist } = await getCustomerWishlist({
|
const { wishlist } = await commerce.getCustomerWishlist({
|
||||||
variables: { customerId },
|
variables: { customerId },
|
||||||
includeProducts,
|
includeProducts,
|
||||||
config,
|
config,
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import type { Wishlist } from '../../../types/wishlist'
|
import type { Wishlist } from '../../../types/wishlist'
|
||||||
import getCustomerWishlist from '../../../customer/get-customer-wishlist'
|
import getCustomerWishlist from '../../operations/get-customer-wishlist'
|
||||||
import getCustomerId from './utils/get-customer-id'
|
import getCustomerId from './utils/get-customer-id'
|
||||||
import type { WishlistEndpoint } from '.'
|
import type { WishlistEndpoint } from '.'
|
||||||
|
|
||||||
@ -8,12 +8,13 @@ const removeItem: WishlistEndpoint['handlers']['removeItem'] = async ({
|
|||||||
res,
|
res,
|
||||||
body: { customerToken, itemId },
|
body: { customerToken, itemId },
|
||||||
config,
|
config,
|
||||||
|
commerce,
|
||||||
}) => {
|
}) => {
|
||||||
const customerId =
|
const customerId =
|
||||||
customerToken && (await getCustomerId({ customerToken, config }))
|
customerToken && (await getCustomerId({ customerToken, config }))
|
||||||
const { wishlist } =
|
const { wishlist } =
|
||||||
(customerId &&
|
(customerId &&
|
||||||
(await getCustomerWishlist({
|
(await commerce.getCustomerWishlist({
|
||||||
variables: { customerId },
|
variables: { customerId },
|
||||||
config,
|
config,
|
||||||
}))) ||
|
}))) ||
|
||||||
|
@ -15,7 +15,7 @@ async function getCustomerId({
|
|||||||
}: {
|
}: {
|
||||||
customerToken: string
|
customerToken: string
|
||||||
config: BigcommerceConfig
|
config: BigcommerceConfig
|
||||||
}): Promise<number | undefined> {
|
}): Promise<string | undefined> {
|
||||||
const { data } = await config.fetch<GetCustomerIdQuery>(
|
const { data } = await config.fetch<GetCustomerIdQuery>(
|
||||||
getCustomerIdQuery,
|
getCustomerIdQuery,
|
||||||
undefined,
|
undefined,
|
||||||
@ -26,7 +26,7 @@ async function getCustomerId({
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
return data?.customer?.entityId
|
return String(data?.customer?.entityId)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default getCustomerId
|
export default getCustomerId
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
import type { NextApiHandler } from 'next'
|
|
||||||
import type { RequestInit } from '@vercel/fetch'
|
import type { RequestInit } from '@vercel/fetch'
|
||||||
import {
|
import {
|
||||||
CommerceAPI,
|
CommerceAPI,
|
||||||
@ -20,6 +19,10 @@ import login from './operations/login'
|
|||||||
import getAllPages from './operations/get-all-pages'
|
import getAllPages from './operations/get-all-pages'
|
||||||
import getPage from './operations/get-page'
|
import getPage from './operations/get-page'
|
||||||
import getSiteInfo from './operations/get-site-info'
|
import getSiteInfo from './operations/get-site-info'
|
||||||
|
import getCustomerWishlist from './operations/get-customer-wishlist'
|
||||||
|
import getAllProductPaths from './operations/get-all-product-paths'
|
||||||
|
import getAllProducts from './operations/get-all-products'
|
||||||
|
import getProduct from './operations/get-product'
|
||||||
|
|
||||||
export interface BigcommerceConfig extends CommerceAPIConfig {
|
export interface BigcommerceConfig extends CommerceAPIConfig {
|
||||||
// Indicates if the returned metadata with translations should be applied to the
|
// Indicates if the returned metadata with translations should be applied to the
|
||||||
@ -57,47 +60,9 @@ if (!(STORE_API_URL && STORE_API_TOKEN && STORE_API_CLIENT_ID)) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
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 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,
|
|
||||||
})
|
|
||||||
|
|
||||||
const config2: BigcommerceConfig = {
|
const config: BigcommerceConfig = {
|
||||||
commerceUrl: API_URL,
|
commerceUrl: API_URL,
|
||||||
apiToken: API_TOKEN,
|
apiToken: API_TOKEN,
|
||||||
customerCookie: 'SHOP_TOKEN',
|
customerCookie: 'SHOP_TOKEN',
|
||||||
@ -113,11 +78,19 @@ const config2: BigcommerceConfig = {
|
|||||||
storeApiFetch: fetchStoreApi,
|
storeApiFetch: fetchStoreApi,
|
||||||
}
|
}
|
||||||
|
|
||||||
export const provider = {
|
const operations = {
|
||||||
config: config2,
|
login,
|
||||||
operations: { login, getAllPages, getPage, getSiteInfo },
|
getAllPages,
|
||||||
|
getPage,
|
||||||
|
getSiteInfo,
|
||||||
|
getCustomerWishlist,
|
||||||
|
getAllProductPaths,
|
||||||
|
getAllProducts,
|
||||||
|
getProduct,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const provider = { config, operations }
|
||||||
|
|
||||||
export type Provider = typeof provider
|
export type Provider = typeof provider
|
||||||
|
|
||||||
export type APIs =
|
export type APIs =
|
||||||
@ -136,11 +109,3 @@ export function getCommerceApi<P extends Provider>(
|
|||||||
): BigcommerceAPI<P> {
|
): BigcommerceAPI<P> {
|
||||||
return commerceApi(customProvider)
|
return commerceApi(customProvider)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getConfig(userConfig?: Partial<BigcommerceConfig>) {
|
|
||||||
return config.getConfig(userConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setConfig(newConfig: Partial<BigcommerceConfig>) {
|
|
||||||
return config.setConfig(newConfig)
|
|
||||||
}
|
|
||||||
|
@ -10,13 +10,13 @@ export default function getAllPagesOperation({
|
|||||||
commerce,
|
commerce,
|
||||||
}: OperationContext<Provider>) {
|
}: OperationContext<Provider>) {
|
||||||
async function getAllPages<T extends GetAllPagesOperation>(opts?: {
|
async function getAllPages<T extends GetAllPagesOperation>(opts?: {
|
||||||
config?: BigcommerceConfig
|
config?: Partial<BigcommerceConfig>
|
||||||
preview?: boolean
|
preview?: boolean
|
||||||
}): Promise<T['data']>
|
}): Promise<T['data']>
|
||||||
|
|
||||||
async function getAllPages<T extends GetAllPagesOperation>(
|
async function getAllPages<T extends GetAllPagesOperation>(
|
||||||
opts: {
|
opts: {
|
||||||
config?: BigcommerceConfig
|
config?: Partial<BigcommerceConfig>
|
||||||
preview?: boolean
|
preview?: boolean
|
||||||
} & OperationOptions
|
} & OperationOptions
|
||||||
): Promise<T['data']>
|
): Promise<T['data']>
|
||||||
@ -26,13 +26,13 @@ export default function getAllPagesOperation({
|
|||||||
preview,
|
preview,
|
||||||
}: {
|
}: {
|
||||||
url?: string
|
url?: string
|
||||||
config?: BigcommerceConfig
|
config?: Partial<BigcommerceConfig>
|
||||||
preview?: boolean
|
preview?: boolean
|
||||||
} = {}): Promise<T['data']> {
|
} = {}): Promise<T['data']> {
|
||||||
config = commerce.getConfig(config)
|
const cfg = commerce.getConfig(config)
|
||||||
// RecursivePartial forces the method to check for every prop in the data, which is
|
// RecursivePartial forces the method to check for every prop in the data, which is
|
||||||
// required in case there's a custom `url`
|
// required in case there's a custom `url`
|
||||||
const { data } = await config.storeApiFetch<
|
const { data } = await cfg.storeApiFetch<
|
||||||
RecursivePartial<{ data: Page[] }>
|
RecursivePartial<{ data: Page[] }>
|
||||||
>('/v3/content/pages')
|
>('/v3/content/pages')
|
||||||
const pages = (data as RecursiveRequired<typeof data>) ?? []
|
const pages = (data as RecursiveRequired<typeof data>) ?? []
|
||||||
|
@ -0,0 +1,66 @@
|
|||||||
|
import type {
|
||||||
|
OperationContext,
|
||||||
|
OperationOptions,
|
||||||
|
} from '@commerce/api/operations'
|
||||||
|
import type { GetAllProductPathsQuery } from '../../schema'
|
||||||
|
import type { GetAllProductPathsOperation } from '../../types/product'
|
||||||
|
import type { RecursivePartial, RecursiveRequired } from '../utils/types'
|
||||||
|
import filterEdges from '../utils/filter-edges'
|
||||||
|
import { BigcommerceConfig, Provider } from '..'
|
||||||
|
|
||||||
|
export const getAllProductPathsQuery = /* GraphQL */ `
|
||||||
|
query getAllProductPaths($first: Int = 100) {
|
||||||
|
site {
|
||||||
|
products(first: $first) {
|
||||||
|
edges {
|
||||||
|
node {
|
||||||
|
path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`
|
||||||
|
|
||||||
|
export default function getAllProductPathsOperation({
|
||||||
|
commerce,
|
||||||
|
}: OperationContext<Provider>) {
|
||||||
|
async function getAllProductPaths<
|
||||||
|
T extends GetAllProductPathsOperation
|
||||||
|
>(opts?: {
|
||||||
|
variables?: T['variables']
|
||||||
|
config?: BigcommerceConfig
|
||||||
|
}): Promise<T['data']>
|
||||||
|
|
||||||
|
async function getAllProductPaths<T extends GetAllProductPathsOperation>(
|
||||||
|
opts: {
|
||||||
|
variables?: T['variables']
|
||||||
|
config?: BigcommerceConfig
|
||||||
|
} & OperationOptions
|
||||||
|
): Promise<T['data']>
|
||||||
|
|
||||||
|
async function getAllProductPaths<T extends GetAllProductPathsOperation>({
|
||||||
|
query = getAllProductPathsQuery,
|
||||||
|
variables,
|
||||||
|
config,
|
||||||
|
}: {
|
||||||
|
query?: string
|
||||||
|
variables?: T['variables']
|
||||||
|
config?: BigcommerceConfig
|
||||||
|
} = {}): Promise<T['data']> {
|
||||||
|
config = commerce.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<GetAllProductPathsQuery>
|
||||||
|
>(query, { variables })
|
||||||
|
const products = data.site?.products?.edges
|
||||||
|
|
||||||
|
return {
|
||||||
|
products: filterEdges(products as RecursiveRequired<typeof products>).map(
|
||||||
|
({ node }) => node
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return getAllProductPaths
|
||||||
|
}
|
135
framework/bigcommerce/api/operations/get-all-products.ts
Normal file
135
framework/bigcommerce/api/operations/get-all-products.ts
Normal file
@ -0,0 +1,135 @@
|
|||||||
|
import type {
|
||||||
|
OperationContext,
|
||||||
|
OperationOptions,
|
||||||
|
} from '@commerce/api/operations'
|
||||||
|
import type {
|
||||||
|
GetAllProductsQuery,
|
||||||
|
GetAllProductsQueryVariables,
|
||||||
|
} from '../../schema'
|
||||||
|
import type { GetAllProductsOperation } from '../../types/product'
|
||||||
|
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, Provider } from '..'
|
||||||
|
import { normalizeProduct } from '../../lib/normalize'
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
function getProductsType(
|
||||||
|
relevance?: GetAllProductsOperation['variables']['relevance']
|
||||||
|
) {
|
||||||
|
switch (relevance) {
|
||||||
|
case 'featured':
|
||||||
|
return 'featuredProducts'
|
||||||
|
case 'best_selling':
|
||||||
|
return 'bestSellingProducts'
|
||||||
|
case 'newest':
|
||||||
|
return 'newestProducts'
|
||||||
|
default:
|
||||||
|
return 'products'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function getAllProductsOperation({
|
||||||
|
commerce,
|
||||||
|
}: OperationContext<Provider>) {
|
||||||
|
async function getAllProducts<T extends GetAllProductsOperation>(opts?: {
|
||||||
|
variables?: T['variables']
|
||||||
|
config?: Partial<BigcommerceConfig>
|
||||||
|
preview?: boolean
|
||||||
|
}): Promise<T['data']>
|
||||||
|
|
||||||
|
async function getAllProducts<T extends GetAllProductsOperation>(
|
||||||
|
opts: {
|
||||||
|
variables?: T['variables']
|
||||||
|
config?: Partial<BigcommerceConfig>
|
||||||
|
preview?: boolean
|
||||||
|
} & OperationOptions
|
||||||
|
): Promise<T['data']>
|
||||||
|
|
||||||
|
async function getAllProducts<T extends GetAllProductsOperation>({
|
||||||
|
query = getAllProductsQuery,
|
||||||
|
variables: vars = {},
|
||||||
|
config: cfg,
|
||||||
|
}: {
|
||||||
|
query?: string
|
||||||
|
variables?: T['variables']
|
||||||
|
config?: Partial<BigcommerceConfig>
|
||||||
|
preview?: boolean
|
||||||
|
} = {}): Promise<T['data']> {
|
||||||
|
const config = commerce.getConfig(cfg)
|
||||||
|
const { locale } = config
|
||||||
|
const field = getProductsType(vars.relevance)
|
||||||
|
const variables: GetAllProductsQueryVariables = {
|
||||||
|
locale,
|
||||||
|
hasLocale: !!locale,
|
||||||
|
}
|
||||||
|
|
||||||
|
variables[field] = true
|
||||||
|
|
||||||
|
if (vars.first) variables.first = vars.first
|
||||||
|
if (vars.ids) variables.entityIds = vars.ids.map((id) => Number(id))
|
||||||
|
|
||||||
|
// 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: products.map(({ node }) => normalizeProduct(node as any)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return getAllProducts
|
||||||
|
}
|
@ -0,0 +1,81 @@
|
|||||||
|
import type {
|
||||||
|
OperationContext,
|
||||||
|
OperationOptions,
|
||||||
|
} from '@commerce/api/operations'
|
||||||
|
import type {
|
||||||
|
GetCustomerWishlistOperation,
|
||||||
|
Wishlist,
|
||||||
|
} from '../../types/wishlist'
|
||||||
|
import type { RecursivePartial, RecursiveRequired } from '../utils/types'
|
||||||
|
import { BigcommerceConfig, Provider } from '..'
|
||||||
|
import getAllProducts, { ProductEdge } from './get-all-products'
|
||||||
|
|
||||||
|
export default function getCustomerWishlistOperation({
|
||||||
|
commerce,
|
||||||
|
}: OperationContext<Provider>) {
|
||||||
|
async function getCustomerWishlist<
|
||||||
|
T extends GetCustomerWishlistOperation
|
||||||
|
>(opts: {
|
||||||
|
variables: T['variables']
|
||||||
|
config?: BigcommerceConfig
|
||||||
|
includeProducts?: boolean
|
||||||
|
}): Promise<T['data']>
|
||||||
|
|
||||||
|
async function getCustomerWishlist<T extends GetCustomerWishlistOperation>(
|
||||||
|
opts: {
|
||||||
|
variables: T['variables']
|
||||||
|
config?: BigcommerceConfig
|
||||||
|
includeProducts?: boolean
|
||||||
|
} & OperationOptions
|
||||||
|
): Promise<T['data']>
|
||||||
|
|
||||||
|
async function getCustomerWishlist<T extends GetCustomerWishlistOperation>({
|
||||||
|
config,
|
||||||
|
variables,
|
||||||
|
includeProducts,
|
||||||
|
}: {
|
||||||
|
url?: string
|
||||||
|
variables: T['variables']
|
||||||
|
config?: BigcommerceConfig
|
||||||
|
includeProducts?: boolean
|
||||||
|
}): Promise<T['data']> {
|
||||||
|
config = commerce.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 ids = wishlist.items
|
||||||
|
?.map((item) => (item?.product_id ? String(item?.product_id) : null))
|
||||||
|
.filter((id): id is string => !!id)
|
||||||
|
|
||||||
|
if (ids?.length) {
|
||||||
|
const graphqlData = await commerce.getAllProducts({
|
||||||
|
variables: { first: 100, ids },
|
||||||
|
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[Number(p.id)] = p as any
|
||||||
|
return prods
|
||||||
|
}, {})
|
||||||
|
// Populate the wishlist items with the graphql products
|
||||||
|
wishlist.items.forEach((item) => {
|
||||||
|
const product = item && productsById[item.product_id!]
|
||||||
|
if (item && product) {
|
||||||
|
// @ts-ignore Fix this type when the wishlist type is properly defined
|
||||||
|
item.product = product
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { wishlist: wishlist as RecursiveRequired<typeof wishlist> }
|
||||||
|
}
|
||||||
|
|
||||||
|
return getCustomerWishlist
|
||||||
|
}
|
@ -11,14 +11,14 @@ export default function getPageOperation({
|
|||||||
}: OperationContext<Provider>) {
|
}: OperationContext<Provider>) {
|
||||||
async function getPage<T extends GetPageOperation>(opts: {
|
async function getPage<T extends GetPageOperation>(opts: {
|
||||||
variables: T['variables']
|
variables: T['variables']
|
||||||
config?: BigcommerceConfig
|
config?: Partial<BigcommerceConfig>
|
||||||
preview?: boolean
|
preview?: boolean
|
||||||
}): Promise<T['data']>
|
}): Promise<T['data']>
|
||||||
|
|
||||||
async function getPage<T extends GetPageOperation>(
|
async function getPage<T extends GetPageOperation>(
|
||||||
opts: {
|
opts: {
|
||||||
variables: T['variables']
|
variables: T['variables']
|
||||||
config?: BigcommerceConfig
|
config?: Partial<BigcommerceConfig>
|
||||||
preview?: boolean
|
preview?: boolean
|
||||||
} & OperationOptions
|
} & OperationOptions
|
||||||
): Promise<T['data']>
|
): Promise<T['data']>
|
||||||
@ -31,13 +31,13 @@ export default function getPageOperation({
|
|||||||
}: {
|
}: {
|
||||||
url?: string
|
url?: string
|
||||||
variables: T['variables']
|
variables: T['variables']
|
||||||
config?: BigcommerceConfig
|
config?: Partial<BigcommerceConfig>
|
||||||
preview?: boolean
|
preview?: boolean
|
||||||
}): Promise<T['data']> {
|
}): Promise<T['data']> {
|
||||||
config = commerce.getConfig(config)
|
const cfg = commerce.getConfig(config)
|
||||||
// RecursivePartial forces the method to check for every prop in the data, which is
|
// RecursivePartial forces the method to check for every prop in the data, which is
|
||||||
// required in case there's a custom `url`
|
// required in case there's a custom `url`
|
||||||
const { data } = await config.storeApiFetch<
|
const { data } = await cfg.storeApiFetch<
|
||||||
RecursivePartial<{ data: Page[] }>
|
RecursivePartial<{ data: Page[] }>
|
||||||
>(url || `/v3/content/pages?id=${variables.id}&include=body`)
|
>(url || `/v3/content/pages?id=${variables.id}&include=body`)
|
||||||
const firstPage = data?.[0]
|
const firstPage = data?.[0]
|
||||||
|
119
framework/bigcommerce/api/operations/get-product.ts
Normal file
119
framework/bigcommerce/api/operations/get-product.ts
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
import type {
|
||||||
|
OperationContext,
|
||||||
|
OperationOptions,
|
||||||
|
} from '@commerce/api/operations'
|
||||||
|
import type { GetProductOperation } from '../../types/product'
|
||||||
|
import type { GetProductQuery, GetProductQueryVariables } from '../../schema'
|
||||||
|
import setProductLocaleMeta from '../utils/set-product-locale-meta'
|
||||||
|
import { productInfoFragment } from '../fragments/product'
|
||||||
|
import { BigcommerceConfig, Provider } from '..'
|
||||||
|
import { normalizeProduct } from '../../lib/normalize'
|
||||||
|
|
||||||
|
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}
|
||||||
|
`
|
||||||
|
|
||||||
|
// TODO: See if this type is useful for defining the Product type
|
||||||
|
// export type ProductNode = Extract<
|
||||||
|
// GetProductQuery['site']['route']['node'],
|
||||||
|
// { __typename: 'Product' }
|
||||||
|
// >
|
||||||
|
|
||||||
|
export default function getAllProductPathsOperation({
|
||||||
|
commerce,
|
||||||
|
}: OperationContext<Provider>) {
|
||||||
|
async function getProduct<T extends GetProductOperation>(opts: {
|
||||||
|
variables: T['variables']
|
||||||
|
config?: Partial<BigcommerceConfig>
|
||||||
|
preview?: boolean
|
||||||
|
}): Promise<T['data']>
|
||||||
|
|
||||||
|
async function getProduct<T extends GetProductOperation>(
|
||||||
|
opts: {
|
||||||
|
variables: T['variables']
|
||||||
|
config?: Partial<BigcommerceConfig>
|
||||||
|
preview?: boolean
|
||||||
|
} & OperationOptions
|
||||||
|
): Promise<T['data']>
|
||||||
|
|
||||||
|
async function getProduct<T extends GetProductOperation>({
|
||||||
|
query = getProductQuery,
|
||||||
|
variables: { slug, ...vars },
|
||||||
|
config: cfg,
|
||||||
|
}: {
|
||||||
|
query?: string
|
||||||
|
variables: T['variables']
|
||||||
|
config?: Partial<BigcommerceConfig>
|
||||||
|
preview?: boolean
|
||||||
|
}): Promise<T['data']> {
|
||||||
|
const config = commerce.getConfig(cfg)
|
||||||
|
const { locale } = config
|
||||||
|
const variables: GetProductQueryVariables = {
|
||||||
|
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: normalizeProduct(product as any) }
|
||||||
|
}
|
||||||
|
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
return getProduct
|
||||||
|
}
|
@ -53,13 +53,13 @@ export default function getSiteInfoOperation({
|
|||||||
commerce,
|
commerce,
|
||||||
}: OperationContext<Provider>) {
|
}: OperationContext<Provider>) {
|
||||||
async function getSiteInfo<T extends GetSiteInfoOperation>(opts?: {
|
async function getSiteInfo<T extends GetSiteInfoOperation>(opts?: {
|
||||||
config?: BigcommerceConfig
|
config?: Partial<BigcommerceConfig>
|
||||||
preview?: boolean
|
preview?: boolean
|
||||||
}): Promise<T['data']>
|
}): Promise<T['data']>
|
||||||
|
|
||||||
async function getSiteInfo<T extends GetSiteInfoOperation>(
|
async function getSiteInfo<T extends GetSiteInfoOperation>(
|
||||||
opts: {
|
opts: {
|
||||||
config?: BigcommerceConfig
|
config?: Partial<BigcommerceConfig>
|
||||||
preview?: boolean
|
preview?: boolean
|
||||||
} & OperationOptions
|
} & OperationOptions
|
||||||
): Promise<T['data']>
|
): Promise<T['data']>
|
||||||
@ -69,15 +69,13 @@ export default function getSiteInfoOperation({
|
|||||||
config,
|
config,
|
||||||
}: {
|
}: {
|
||||||
query?: string
|
query?: string
|
||||||
config?: BigcommerceConfig
|
config?: Partial<BigcommerceConfig>
|
||||||
preview?: boolean
|
preview?: boolean
|
||||||
} = {}): Promise<T['data']> {
|
} = {}): Promise<T['data']> {
|
||||||
config = commerce.getConfig(config)
|
const cfg = commerce.getConfig(config)
|
||||||
// RecursivePartial forces the method to check for every prop in the data, which is
|
// RecursivePartial forces the method to check for every prop in the data, which is
|
||||||
// required in case there's a custom `query`
|
// required in case there's a custom `query`
|
||||||
const { data } = await config.fetch<RecursivePartial<GetSiteInfoQuery>>(
|
const { data } = await cfg.fetch<RecursivePartial<GetSiteInfoQuery>>(query)
|
||||||
query
|
|
||||||
)
|
|
||||||
const categories = data.site?.categoryTree
|
const categories = data.site?.categoryTree
|
||||||
const brands = data.site?.brands?.edges
|
const brands = data.site?.brands?.edges
|
||||||
|
|
||||||
|
@ -1,58 +0,0 @@
|
|||||||
import type { NextApiHandler, NextApiRequest, NextApiResponse } from 'next'
|
|
||||||
import { BigcommerceConfig, getConfig } from '..'
|
|
||||||
|
|
||||||
export type BigcommerceApiHandler<
|
|
||||||
T = any,
|
|
||||||
H extends BigcommerceHandlers = {},
|
|
||||||
Options extends {} = {}
|
|
||||||
> = (
|
|
||||||
req: NextApiRequest,
|
|
||||||
res: NextApiResponse<BigcommerceApiResponse<T>>,
|
|
||||||
config: BigcommerceConfig,
|
|
||||||
handlers: H,
|
|
||||||
// Custom configs that may be used by a particular handler
|
|
||||||
options: Options
|
|
||||||
) => void | Promise<void>
|
|
||||||
|
|
||||||
export type BigcommerceHandler<T = any, Body = null> = (options: {
|
|
||||||
req: NextApiRequest
|
|
||||||
res: NextApiResponse<BigcommerceApiResponse<T>>
|
|
||||||
config: BigcommerceConfig
|
|
||||||
body: Body
|
|
||||||
}) => void | Promise<void>
|
|
||||||
|
|
||||||
export type BigcommerceHandlers<T = any> = {
|
|
||||||
[k: string]: BigcommerceHandler<T, any>
|
|
||||||
}
|
|
||||||
|
|
||||||
export type BigcommerceApiResponse<T> = {
|
|
||||||
data: T | null
|
|
||||||
errors?: { message: string; code?: string }[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function createApiHandler<
|
|
||||||
T = any,
|
|
||||||
H extends BigcommerceHandlers = {},
|
|
||||||
Options extends {} = {}
|
|
||||||
>(
|
|
||||||
handler: BigcommerceApiHandler<T, H, Options>,
|
|
||||||
handlers: H,
|
|
||||||
defaultOptions: Options
|
|
||||||
) {
|
|
||||||
return function getApiHandler({
|
|
||||||
config,
|
|
||||||
operations,
|
|
||||||
options,
|
|
||||||
}: {
|
|
||||||
config?: BigcommerceConfig
|
|
||||||
operations?: Partial<H>
|
|
||||||
options?: Options extends {} ? Partial<Options> : never
|
|
||||||
} = {}): NextApiHandler {
|
|
||||||
const ops = { ...handlers, ...operations }
|
|
||||||
const opts = { ...defaultOptions, ...options }
|
|
||||||
|
|
||||||
return function apiHandler(req, res) {
|
|
||||||
return handler(req, res, getConfig(config), ops, opts)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,15 +1,15 @@
|
|||||||
import { FetcherError } from '@commerce/utils/errors'
|
import { FetcherError } from '@commerce/utils/errors'
|
||||||
import type { GraphQLFetcher } from '@commerce/api'
|
import type { GraphQLFetcher } from '@commerce/api'
|
||||||
import { getConfig } from '..'
|
import { provider } from '..'
|
||||||
import fetch from './fetch'
|
import fetch from './fetch'
|
||||||
|
|
||||||
|
const { config } = provider
|
||||||
const fetchGraphqlApi: GraphQLFetcher = async (
|
const fetchGraphqlApi: GraphQLFetcher = async (
|
||||||
query: string,
|
query: string,
|
||||||
{ variables, preview } = {},
|
{ variables, preview } = {},
|
||||||
fetchOptions
|
fetchOptions
|
||||||
) => {
|
) => {
|
||||||
// log.warn(query)
|
// log.warn(query)
|
||||||
const config = getConfig()
|
|
||||||
const res = await fetch(config.commerceUrl + (preview ? '/preview' : ''), {
|
const res = await fetch(config.commerceUrl + (preview ? '/preview' : ''), {
|
||||||
...fetchOptions,
|
...fetchOptions,
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
@ -1,13 +1,14 @@
|
|||||||
import type { RequestInit, Response } from '@vercel/fetch'
|
import type { RequestInit, Response } from '@vercel/fetch'
|
||||||
import { getConfig } from '..'
|
import { provider } from '..'
|
||||||
import { BigcommerceApiError, BigcommerceNetworkError } from './errors'
|
import { BigcommerceApiError, BigcommerceNetworkError } from './errors'
|
||||||
import fetch from './fetch'
|
import fetch from './fetch'
|
||||||
|
|
||||||
|
const { config } = provider
|
||||||
|
|
||||||
export default async function fetchStoreApi<T>(
|
export default async function fetchStoreApi<T>(
|
||||||
endpoint: string,
|
endpoint: string,
|
||||||
options?: RequestInit
|
options?: RequestInit
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
const config = getConfig()
|
|
||||||
let res: Response
|
let res: Response
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
@ -1,28 +0,0 @@
|
|||||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
|
||||||
|
|
||||||
export default function isAllowedMethod(
|
|
||||||
req: NextApiRequest,
|
|
||||||
res: NextApiResponse,
|
|
||||||
allowedMethods: string[]
|
|
||||||
) {
|
|
||||||
const methods = allowedMethods.includes('OPTIONS')
|
|
||||||
? allowedMethods
|
|
||||||
: [...allowedMethods, 'OPTIONS']
|
|
||||||
|
|
||||||
if (!req.method || !methods.includes(req.method)) {
|
|
||||||
res.status(405)
|
|
||||||
res.setHeader('Allow', methods.join(', '))
|
|
||||||
res.end()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
res.status(200)
|
|
||||||
res.setHeader('Allow', methods.join(', '))
|
|
||||||
res.setHeader('Content-Length', '0')
|
|
||||||
res.end()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
@ -1,4 +1,4 @@
|
|||||||
import type { ProductNode } from '../../product/get-all-products'
|
import type { ProductNode } from '../operations/get-all-products'
|
||||||
import type { RecursivePartial } from './types'
|
import type { RecursivePartial } from './types'
|
||||||
|
|
||||||
export default function setProductLocaleMeta(
|
export default function setProductLocaleMeta(
|
||||||
|
@ -1,56 +0,0 @@
|
|||||||
import type { WishlistHandlers } from '..'
|
|
||||||
import getCustomerId from '../../endpoints/wishlist/utils/get-customer-id'
|
|
||||||
import getCustomerWishlist from '../../../customer/get-customer-wishlist'
|
|
||||||
import { parseWishlistItem } from '../../utils/parse-item'
|
|
||||||
|
|
||||||
// Returns the wishlist of the signed customer
|
|
||||||
const addItem: WishlistHandlers['addItem'] = async ({
|
|
||||||
res,
|
|
||||||
body: { customerToken, item },
|
|
||||||
config,
|
|
||||||
}) => {
|
|
||||||
if (!item) {
|
|
||||||
return res.status(400).json({
|
|
||||||
data: null,
|
|
||||||
errors: [{ message: 'Missing item' }],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const customerId =
|
|
||||||
customerToken && (await getCustomerId({ customerToken, config }))
|
|
||||||
|
|
||||||
if (!customerId) {
|
|
||||||
return res.status(400).json({
|
|
||||||
data: null,
|
|
||||||
errors: [{ message: 'Invalid request' }],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const { wishlist } = await getCustomerWishlist({
|
|
||||||
variables: { customerId },
|
|
||||||
config,
|
|
||||||
})
|
|
||||||
const options = {
|
|
||||||
method: 'POST',
|
|
||||||
body: JSON.stringify(
|
|
||||||
wishlist
|
|
||||||
? {
|
|
||||||
items: [parseWishlistItem(item)],
|
|
||||||
}
|
|
||||||
: {
|
|
||||||
name: 'Wishlist',
|
|
||||||
customer_id: customerId,
|
|
||||||
items: [parseWishlistItem(item)],
|
|
||||||
is_public: false,
|
|
||||||
}
|
|
||||||
),
|
|
||||||
}
|
|
||||||
|
|
||||||
const { data } = wishlist
|
|
||||||
? await config.storeApiFetch(`/v3/wishlists/${wishlist.id}/items`, options)
|
|
||||||
: await config.storeApiFetch('/v3/wishlists', options)
|
|
||||||
|
|
||||||
res.status(200).json({ data })
|
|
||||||
}
|
|
||||||
|
|
||||||
export default addItem
|
|
@ -1,37 +0,0 @@
|
|||||||
import getCustomerId from '../../endpoints/wishlist/utils/get-customer-id'
|
|
||||||
import getCustomerWishlist from '../../../customer/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,39 +0,0 @@
|
|||||||
import getCustomerId from '../../endpoints/wishlist/utils/get-customer-id'
|
|
||||||
import getCustomerWishlist, {
|
|
||||||
Wishlist,
|
|
||||||
} from '../../../customer/get-customer-wishlist'
|
|
||||||
import type { WishlistHandlers } from '..'
|
|
||||||
|
|
||||||
// Return current wishlist info
|
|
||||||
const removeItem: WishlistHandlers['removeItem'] = async ({
|
|
||||||
res,
|
|
||||||
body: { customerToken, itemId },
|
|
||||||
config,
|
|
||||||
}) => {
|
|
||||||
const customerId =
|
|
||||||
customerToken && (await getCustomerId({ customerToken, config }))
|
|
||||||
const { wishlist } =
|
|
||||||
(customerId &&
|
|
||||||
(await getCustomerWishlist({
|
|
||||||
variables: { customerId },
|
|
||||||
config,
|
|
||||||
}))) ||
|
|
||||||
{}
|
|
||||||
|
|
||||||
if (!wishlist || !itemId) {
|
|
||||||
return res.status(400).json({
|
|
||||||
data: null,
|
|
||||||
errors: [{ message: 'Invalid request' }],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await config.storeApiFetch<{ data: Wishlist } | null>(
|
|
||||||
`/v3/wishlists/${wishlist.id}/items/${itemId}`,
|
|
||||||
{ method: 'DELETE' }
|
|
||||||
)
|
|
||||||
const data = result?.data ?? null
|
|
||||||
|
|
||||||
res.status(200).json({ data })
|
|
||||||
}
|
|
||||||
|
|
||||||
export default removeItem
|
|
@ -1,104 +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 '../../customer/get-customer-wishlist'
|
|
||||||
import getWishlist from './handlers/get-wishlist'
|
|
||||||
import addItem from './handlers/add-item'
|
|
||||||
import removeItem from './handlers/remove-item'
|
|
||||||
import type { Product, ProductVariant, Customer } from '@commerce/types'
|
|
||||||
|
|
||||||
export type { Wishlist, WishlistItem }
|
|
||||||
|
|
||||||
export type ItemBody = {
|
|
||||||
productId: Product['id']
|
|
||||||
variantId: ProductVariant['id']
|
|
||||||
}
|
|
||||||
|
|
||||||
export type AddItemBody = { item: ItemBody }
|
|
||||||
|
|
||||||
export type RemoveItemBody = { itemId: Product['id'] }
|
|
||||||
|
|
||||||
export type WishlistBody = {
|
|
||||||
customer_id: Customer['entityId']
|
|
||||||
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,88 +0,0 @@
|
|||||||
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
|
|
||||||
import { definitions } from '../api/definitions/wishlist'
|
|
||||||
import { BigcommerceConfig, getConfig } from '../api'
|
|
||||||
import getAllProducts, { ProductEdge } from '../product/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[Number(p.id)] = p as any
|
|
||||||
return prods
|
|
||||||
}, {})
|
|
||||||
// Populate the wishlist items with the graphql products
|
|
||||||
wishlist.items.forEach((item) => {
|
|
||||||
const product = item && productsById[item.product_id!]
|
|
||||||
if (item && product) {
|
|
||||||
// @ts-ignore Fix this type when the wishlist type is properly defined
|
|
||||||
item.product = product
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { wishlist: wishlist as RecursiveRequired<typeof wishlist> }
|
|
||||||
}
|
|
||||||
|
|
||||||
export default getCustomerWishlist
|
|
@ -1,71 +0,0 @@
|
|||||||
import type {
|
|
||||||
GetAllProductPathsQuery,
|
|
||||||
GetAllProductPathsQueryVariables,
|
|
||||||
} from '../schema'
|
|
||||||
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
|
|
||||||
import filterEdges from '../api/utils/filter-edges'
|
|
||||||
import { BigcommerceConfig, getConfig } from '../api'
|
|
||||||
|
|
||||||
export const getAllProductPathsQuery = /* GraphQL */ `
|
|
||||||
query getAllProductPaths($first: Int = 100) {
|
|
||||||
site {
|
|
||||||
products(first: $first) {
|
|
||||||
edges {
|
|
||||||
node {
|
|
||||||
path
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
`
|
|
||||||
|
|
||||||
export type ProductPath = NonNullable<
|
|
||||||
NonNullable<GetAllProductPathsQuery['site']['products']['edges']>[0]
|
|
||||||
>
|
|
||||||
|
|
||||||
export type ProductPaths = ProductPath[]
|
|
||||||
|
|
||||||
export type { GetAllProductPathsQueryVariables }
|
|
||||||
|
|
||||||
export type GetAllProductPathsResult<
|
|
||||||
T extends { products: any[] } = { products: ProductPaths }
|
|
||||||
> = T
|
|
||||||
|
|
||||||
async function getAllProductPaths(opts?: {
|
|
||||||
variables?: GetAllProductPathsQueryVariables
|
|
||||||
config?: BigcommerceConfig
|
|
||||||
}): Promise<GetAllProductPathsResult>
|
|
||||||
|
|
||||||
async function getAllProductPaths<
|
|
||||||
T extends { products: any[] },
|
|
||||||
V = any
|
|
||||||
>(opts: {
|
|
||||||
query: string
|
|
||||||
variables?: V
|
|
||||||
config?: BigcommerceConfig
|
|
||||||
}): Promise<GetAllProductPathsResult<T>>
|
|
||||||
|
|
||||||
async function getAllProductPaths({
|
|
||||||
query = getAllProductPathsQuery,
|
|
||||||
variables,
|
|
||||||
config,
|
|
||||||
}: {
|
|
||||||
query?: string
|
|
||||||
variables?: GetAllProductPathsQueryVariables
|
|
||||||
config?: BigcommerceConfig
|
|
||||||
} = {}): Promise<GetAllProductPathsResult> {
|
|
||||||
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<GetAllProductPathsQuery>
|
|
||||||
>(query, { variables })
|
|
||||||
const products = data.site?.products?.edges
|
|
||||||
|
|
||||||
return {
|
|
||||||
products: filterEdges(products as RecursiveRequired<typeof products>),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default getAllProductPaths
|
|
@ -1,135 +0,0 @@
|
|||||||
import type {
|
|
||||||
GetAllProductsQuery,
|
|
||||||
GetAllProductsQueryVariables,
|
|
||||||
} from '../schema'
|
|
||||||
import type { Product } from '@commerce/types'
|
|
||||||
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
|
|
||||||
import filterEdges from '../api/utils/filter-edges'
|
|
||||||
import setProductLocaleMeta from '../api/utils/set-product-locale-meta'
|
|
||||||
import { productConnectionFragment } from '../api/fragments/product'
|
|
||||||
import { BigcommerceConfig, getConfig } from '../api'
|
|
||||||
import { normalizeProduct } from '../lib/normalize'
|
|
||||||
|
|
||||||
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<{ products: Product[] }>
|
|
||||||
|
|
||||||
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
|
|
||||||
// TODO: fix the product type here
|
|
||||||
} = {}): Promise<{ products: Product[] | any[] }> {
|
|
||||||
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: products.map(({ node }) => normalizeProduct(node as any)) }
|
|
||||||
}
|
|
||||||
|
|
||||||
export default getAllProducts
|
|
@ -1,121 +0,0 @@
|
|||||||
import type { GetProductQuery, GetProductQueryVariables } from '../schema'
|
|
||||||
import setProductLocaleMeta from '../api/utils/set-product-locale-meta'
|
|
||||||
import { productInfoFragment } from '../api/fragments/product'
|
|
||||||
import { BigcommerceConfig, getConfig } from '../api'
|
|
||||||
import { normalizeProduct } from '../lib/normalize'
|
|
||||||
import type { Product } from '@commerce/types'
|
|
||||||
|
|
||||||
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<Product | {} | any> {
|
|
||||||
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: normalizeProduct(product as any) }
|
|
||||||
}
|
|
||||||
|
|
||||||
return {}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default getProduct
|
|
@ -1,4 +1,2 @@
|
|||||||
export { default as usePrice } from './use-price'
|
export { default as usePrice } from './use-price'
|
||||||
export { default as useSearch } from './use-search'
|
export { default as useSearch } from './use-search'
|
||||||
export { default as getProduct } from './get-product'
|
|
||||||
export { default as getAllProducts } from './get-all-products'
|
|
||||||
|
1
framework/bigcommerce/types/checkout.ts
Normal file
1
framework/bigcommerce/types/checkout.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from '@commerce/types/checkout'
|
@ -1,6 +1,6 @@
|
|||||||
import * as Core from '@commerce/types/wishlist'
|
import * as Core from '@commerce/types/wishlist'
|
||||||
import { definitions } from '../api/definitions/wishlist'
|
import { definitions } from '../api/definitions/wishlist'
|
||||||
import type { ProductEdge } from '../product/get-all-products'
|
import type { ProductEdge } from '../api/operations/get-all-products'
|
||||||
|
|
||||||
export * from '@commerce/types/wishlist'
|
export * from '@commerce/types/wishlist'
|
||||||
|
|
||||||
@ -20,3 +20,4 @@ export type WishlistTypes = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type WishlistSchema = Core.WishlistSchema<WishlistTypes>
|
export type WishlistSchema = Core.WishlistSchema<WishlistTypes>
|
||||||
|
export type GetCustomerWishlistOperation = Core.GetCustomerWishlistOperation<WishlistTypes>
|
||||||
|
35
framework/commerce/api/endpoints/checkout.ts
Normal file
35
framework/commerce/api/endpoints/checkout.ts
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
import type { CheckoutSchema } from '../../types/checkout'
|
||||||
|
import { CommerceAPIError } from '../utils/errors'
|
||||||
|
import isAllowedOperation from '../utils/is-allowed-operation'
|
||||||
|
import type { GetAPISchema } from '..'
|
||||||
|
|
||||||
|
const checkoutEndpoint: GetAPISchema<
|
||||||
|
any,
|
||||||
|
CheckoutSchema
|
||||||
|
>['endpoint']['handler'] = async (ctx) => {
|
||||||
|
const { req, res, handlers } = ctx
|
||||||
|
|
||||||
|
if (
|
||||||
|
!isAllowedOperation(req, res, {
|
||||||
|
GET: handlers['checkout'],
|
||||||
|
})
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body = null
|
||||||
|
return await handlers['checkout']({ ...ctx, body })
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error)
|
||||||
|
|
||||||
|
const message =
|
||||||
|
error instanceof CommerceAPIError
|
||||||
|
? 'An unexpected error ocurred with the Commerce API'
|
||||||
|
: 'An unexpected error ocurred'
|
||||||
|
|
||||||
|
res.status(500).json({ data: null, errors: [{ message }] })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default checkoutEndpoint
|
@ -8,6 +8,7 @@ import type { LogoutSchema } from '../types/logout'
|
|||||||
import type { SignupSchema } from '../types/signup'
|
import type { SignupSchema } from '../types/signup'
|
||||||
import type { ProductsSchema } from '../types/product'
|
import type { ProductsSchema } from '../types/product'
|
||||||
import type { WishlistSchema } from '../types/wishlist'
|
import type { WishlistSchema } from '../types/wishlist'
|
||||||
|
import type { CheckoutSchema } from '../types/checkout'
|
||||||
import {
|
import {
|
||||||
defaultOperations,
|
defaultOperations,
|
||||||
OPERATIONS,
|
OPERATIONS,
|
||||||
@ -23,6 +24,7 @@ export type APISchemas =
|
|||||||
| SignupSchema
|
| SignupSchema
|
||||||
| ProductsSchema
|
| ProductsSchema
|
||||||
| WishlistSchema
|
| WishlistSchema
|
||||||
|
| CheckoutSchema
|
||||||
|
|
||||||
export type GetAPISchema<
|
export type GetAPISchema<
|
||||||
C extends CommerceAPI<any>,
|
C extends CommerceAPI<any>,
|
||||||
|
@ -2,6 +2,12 @@ import type { ServerResponse } from 'http'
|
|||||||
import type { LoginOperation } from '../types/login'
|
import type { LoginOperation } from '../types/login'
|
||||||
import type { GetAllPagesOperation, GetPageOperation } from '../types/page'
|
import type { GetAllPagesOperation, GetPageOperation } from '../types/page'
|
||||||
import type { GetSiteInfoOperation } from '../types/site'
|
import type { GetSiteInfoOperation } from '../types/site'
|
||||||
|
import type { GetCustomerWishlistOperation } from '../types/wishlist'
|
||||||
|
import type {
|
||||||
|
GetAllProductPathsOperation,
|
||||||
|
GetAllProductsOperation,
|
||||||
|
GetProductOperation,
|
||||||
|
} from '../types/product'
|
||||||
import type { APIProvider, CommerceAPI } from '.'
|
import type { APIProvider, CommerceAPI } from '.'
|
||||||
|
|
||||||
const noop = () => {
|
const noop = () => {
|
||||||
@ -77,6 +83,68 @@ export type Operations<P extends APIProvider> = {
|
|||||||
} & OperationOptions
|
} & OperationOptions
|
||||||
): Promise<T['data']>
|
): Promise<T['data']>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getCustomerWishlist: {
|
||||||
|
<T extends GetCustomerWishlistOperation>(opts: {
|
||||||
|
variables: T['variables']
|
||||||
|
config?: P['config']
|
||||||
|
includeProducts?: boolean
|
||||||
|
}): Promise<T['data']>
|
||||||
|
|
||||||
|
<T extends GetCustomerWishlistOperation>(
|
||||||
|
opts: {
|
||||||
|
variables: T['variables']
|
||||||
|
config?: P['config']
|
||||||
|
includeProducts?: boolean
|
||||||
|
} & OperationOptions
|
||||||
|
): Promise<T['data']>
|
||||||
|
}
|
||||||
|
|
||||||
|
getAllProductPaths: {
|
||||||
|
<T extends GetAllProductPathsOperation>(opts: {
|
||||||
|
variables?: T['variables']
|
||||||
|
config?: P['config']
|
||||||
|
}): Promise<T['data']>
|
||||||
|
|
||||||
|
<T extends GetAllProductPathsOperation>(
|
||||||
|
opts: {
|
||||||
|
variables?: T['variables']
|
||||||
|
config?: P['config']
|
||||||
|
} & OperationOptions
|
||||||
|
): Promise<T['data']>
|
||||||
|
}
|
||||||
|
|
||||||
|
getAllProducts: {
|
||||||
|
<T extends GetAllProductsOperation>(opts: {
|
||||||
|
variables?: T['variables']
|
||||||
|
config?: P['config']
|
||||||
|
preview?: boolean
|
||||||
|
}): Promise<T['data']>
|
||||||
|
|
||||||
|
<T extends GetAllProductsOperation>(
|
||||||
|
opts: {
|
||||||
|
variables?: T['variables']
|
||||||
|
config?: P['config']
|
||||||
|
preview?: boolean
|
||||||
|
} & OperationOptions
|
||||||
|
): Promise<T['data']>
|
||||||
|
}
|
||||||
|
|
||||||
|
getProduct: {
|
||||||
|
<T extends GetProductOperation>(opts: {
|
||||||
|
variables: T['variables']
|
||||||
|
config?: P['config']
|
||||||
|
preview?: boolean
|
||||||
|
}): Promise<T['data']>
|
||||||
|
|
||||||
|
<T extends GetProductOperation>(
|
||||||
|
opts: {
|
||||||
|
variables: T['variables']
|
||||||
|
config?: P['config']
|
||||||
|
preview?: boolean
|
||||||
|
} & OperationOptions
|
||||||
|
): Promise<T['data']>
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type APIOperations<P extends APIProvider> = {
|
export type APIOperations<P extends APIProvider> = {
|
||||||
|
10
framework/commerce/types/checkout.ts
Normal file
10
framework/commerce/types/checkout.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
export type CheckoutSchema = {
|
||||||
|
endpoint: {
|
||||||
|
options: {}
|
||||||
|
handlers: {
|
||||||
|
checkout: {
|
||||||
|
data: null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -65,3 +65,24 @@ export type ProductsSchema<T extends ProductTypes = ProductTypes> = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type GetAllProductPathsOperation<
|
||||||
|
T extends ProductTypes = ProductTypes
|
||||||
|
> = {
|
||||||
|
data: { products: Pick<T['product'], 'path'>[] }
|
||||||
|
variables: { first?: number }
|
||||||
|
}
|
||||||
|
|
||||||
|
export type GetAllProductsOperation<T extends ProductTypes = ProductTypes> = {
|
||||||
|
data: { products: T['product'][] }
|
||||||
|
variables: {
|
||||||
|
relevance?: 'featured' | 'best_selling' | 'newest'
|
||||||
|
ids?: string[]
|
||||||
|
first?: number
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type GetProductOperation<T extends ProductTypes = ProductTypes> = {
|
||||||
|
data: { product?: T['product'] }
|
||||||
|
variables: { path: string; slug?: never } | { path?: never; slug: string }
|
||||||
|
}
|
||||||
|
@ -30,3 +30,10 @@ export type WishlistSchema<T extends WishlistTypes = WishlistTypes> = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type GetCustomerWishlistOperation<
|
||||||
|
T extends WishlistTypes = WishlistTypes
|
||||||
|
> = {
|
||||||
|
data: { wishlist?: T['wishlist'] }
|
||||||
|
variables: { customerId: string }
|
||||||
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import { getConfig, ShopifyConfig } from '../api'
|
import { getConfig, ShopifyConfig } from '../api'
|
||||||
import fetchAllProducts from '../api/utils/fetch-all-products'
|
import { ProductEdge } from '../schema'
|
||||||
import getAllProductsPathsQuery from '../utils/queries/get-all-products-paths-query'
|
import getAllProductsPathsQuery from '../utils/queries/get-all-products-paths-query'
|
||||||
|
|
||||||
type ProductPath = {
|
type ProductPath = {
|
||||||
@ -19,21 +19,22 @@ const getAllProductPaths = async (options?: {
|
|||||||
config?: ShopifyConfig
|
config?: ShopifyConfig
|
||||||
preview?: boolean
|
preview?: boolean
|
||||||
}): Promise<ReturnType> => {
|
}): Promise<ReturnType> => {
|
||||||
let { config, variables = { first: 250 } } = options ?? {}
|
let { config, variables = { first: 100, sortKey: 'BEST_SELLING' } } =
|
||||||
|
options ?? {}
|
||||||
config = getConfig(config)
|
config = getConfig(config)
|
||||||
|
|
||||||
const products = await fetchAllProducts({
|
const { data } = await config.fetch(getAllProductsPathsQuery, {
|
||||||
config,
|
|
||||||
query: getAllProductsPathsQuery,
|
|
||||||
variables,
|
variables,
|
||||||
})
|
})
|
||||||
|
|
||||||
return {
|
return {
|
||||||
products: products?.map(({ node: { handle } }) => ({
|
products: data.products?.edges?.map(
|
||||||
|
({ node: { handle } }: ProductEdge) => ({
|
||||||
node: {
|
node: {
|
||||||
path: `/${handle}`,
|
path: `/${handle}`,
|
||||||
},
|
},
|
||||||
})),
|
})
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,7 +2,7 @@ import { getConfig, ShopifyConfig } from '../api'
|
|||||||
import { GetAllProductsQuery, Product as ShopifyProduct } from '../schema'
|
import { GetAllProductsQuery, Product as ShopifyProduct } from '../schema'
|
||||||
import { getAllProductsQuery } from '../utils/queries'
|
import { getAllProductsQuery } from '../utils/queries'
|
||||||
import { normalizeProduct } from '../utils/normalize'
|
import { normalizeProduct } from '../utils/normalize'
|
||||||
import { Product } from '@commerce/types'
|
import { Product } from '../types/product'
|
||||||
|
|
||||||
type Variables = {
|
type Variables = {
|
||||||
first?: number
|
first?: number
|
||||||
|
@ -8,7 +8,6 @@ import { Text } from '@components/ui'
|
|||||||
import { Layout } from '@components/common'
|
import { Layout } from '@components/common'
|
||||||
import getSlug from '@lib/get-slug'
|
import getSlug from '@lib/get-slug'
|
||||||
import { missingLocaleInPages } from '@lib/usage-warns'
|
import { missingLocaleInPages } from '@lib/usage-warns'
|
||||||
import { getConfig } from '@framework/api'
|
|
||||||
import { defaultPageProps } from '@lib/defaults'
|
import { defaultPageProps } from '@lib/defaults'
|
||||||
|
|
||||||
export async function getStaticProps({
|
export async function getStaticProps({
|
||||||
@ -16,7 +15,7 @@ export async function getStaticProps({
|
|||||||
params,
|
params,
|
||||||
locale,
|
locale,
|
||||||
}: GetStaticPropsContext<{ pages: string[] }>) {
|
}: GetStaticPropsContext<{ pages: string[] }>) {
|
||||||
const config = getConfig({ locale })
|
const config = { locale }
|
||||||
const { pages } = await commerce.getAllPages({ preview, config })
|
const { pages } = await commerce.getAllPages({ preview, config })
|
||||||
const path = params?.pages.join('/')
|
const path = params?.pages.join('/')
|
||||||
const slug = locale ? `${locale}/${path}` : path
|
const slug = locale ? `${locale}/${path}` : path
|
||||||
|
@ -1,3 +0,0 @@
|
|||||||
import checkoutApi from '@framework/api/checkout'
|
|
||||||
|
|
||||||
export default checkoutApi()
|
|
@ -1,11 +1,4 @@
|
|||||||
import products from '@commerce/api/endpoints/catalog/products'
|
import productsApi from '@framework/api/endpoints/catalog/products'
|
||||||
import {
|
|
||||||
ProductsAPI,
|
|
||||||
handlers,
|
|
||||||
} from '@framework/api/endpoints/catalog/products'
|
|
||||||
import commerce from '@lib/api/commerce'
|
import commerce from '@lib/api/commerce'
|
||||||
|
|
||||||
export default commerce.endpoint({
|
export default productsApi(commerce)
|
||||||
handler: products as ProductsAPI['endpoint']['handler'],
|
|
||||||
handlers,
|
|
||||||
})
|
|
||||||
|
4
pages/api/checkout.ts
Normal file
4
pages/api/checkout.ts
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
import checkoutApi from '@framework/api/endpoints/checkout'
|
||||||
|
import commerce from '@lib/api/commerce'
|
||||||
|
|
||||||
|
export default checkoutApi(commerce)
|
@ -1,5 +1,4 @@
|
|||||||
import type { GetStaticPropsContext } from 'next'
|
import type { GetStaticPropsContext } from 'next'
|
||||||
import { getConfig } from '@framework/api'
|
|
||||||
import commerce from '@lib/api/commerce'
|
import commerce from '@lib/api/commerce'
|
||||||
import { Layout } from '@components/common'
|
import { Layout } from '@components/common'
|
||||||
import { Container } from '@components/ui'
|
import { Container } from '@components/ui'
|
||||||
@ -8,7 +7,7 @@ export async function getStaticProps({
|
|||||||
preview,
|
preview,
|
||||||
locale,
|
locale,
|
||||||
}: GetStaticPropsContext) {
|
}: GetStaticPropsContext) {
|
||||||
const config = getConfig({ locale })
|
const config = { locale }
|
||||||
const { pages } = await commerce.getAllPages({ config, preview })
|
const { pages } = await commerce.getAllPages({ config, preview })
|
||||||
return {
|
return {
|
||||||
props: { pages },
|
props: { pages },
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
import type { GetStaticPropsContext } from 'next'
|
import type { GetStaticPropsContext } from 'next'
|
||||||
import { getConfig } from '@framework/api'
|
|
||||||
import useCart from '@framework/cart/use-cart'
|
import useCart from '@framework/cart/use-cart'
|
||||||
import usePrice from '@framework/product/use-price'
|
import usePrice from '@framework/product/use-price'
|
||||||
import commerce from '@lib/api/commerce'
|
import commerce from '@lib/api/commerce'
|
||||||
@ -12,7 +11,7 @@ export async function getStaticProps({
|
|||||||
preview,
|
preview,
|
||||||
locale,
|
locale,
|
||||||
}: GetStaticPropsContext) {
|
}: GetStaticPropsContext) {
|
||||||
const config = getConfig({ locale })
|
const config = { locale }
|
||||||
const { pages } = await commerce.getAllPages({ config, preview })
|
const { pages } = await commerce.getAllPages({ config, preview })
|
||||||
return {
|
return {
|
||||||
props: { pages },
|
props: { pages },
|
||||||
|
@ -5,16 +5,12 @@ import { ProductCard } from '@components/product'
|
|||||||
// import HomeAllProductsGrid from '@components/common/HomeAllProductsGrid'
|
// import HomeAllProductsGrid from '@components/common/HomeAllProductsGrid'
|
||||||
import type { GetStaticPropsContext, InferGetStaticPropsType } from 'next'
|
import type { GetStaticPropsContext, InferGetStaticPropsType } from 'next'
|
||||||
|
|
||||||
import { getConfig } from '@framework/api'
|
|
||||||
import getAllProducts from '@framework/product/get-all-products'
|
|
||||||
|
|
||||||
export async function getStaticProps({
|
export async function getStaticProps({
|
||||||
preview,
|
preview,
|
||||||
locale,
|
locale,
|
||||||
}: GetStaticPropsContext) {
|
}: GetStaticPropsContext) {
|
||||||
const config = getConfig({ locale })
|
const config = { locale }
|
||||||
|
const { products } = await commerce.getAllProducts({
|
||||||
const { products } = await getAllProducts({
|
|
||||||
variables: { first: 12 },
|
variables: { first: 12 },
|
||||||
config,
|
config,
|
||||||
preview,
|
preview,
|
||||||
|
@ -3,13 +3,12 @@ import commerce from '@lib/api/commerce'
|
|||||||
import { Bag } from '@components/icons'
|
import { Bag } from '@components/icons'
|
||||||
import { Layout } from '@components/common'
|
import { Layout } from '@components/common'
|
||||||
import { Container, Text } from '@components/ui'
|
import { Container, Text } from '@components/ui'
|
||||||
import { getConfig } from '@framework/api'
|
|
||||||
|
|
||||||
export async function getStaticProps({
|
export async function getStaticProps({
|
||||||
preview,
|
preview,
|
||||||
locale,
|
locale,
|
||||||
}: GetStaticPropsContext) {
|
}: GetStaticPropsContext) {
|
||||||
const config = getConfig({ locale })
|
const config = { locale }
|
||||||
const { pages } = await commerce.getAllPages({ config, preview })
|
const { pages } = await commerce.getAllPages({ config, preview })
|
||||||
return {
|
return {
|
||||||
props: { pages },
|
props: { pages },
|
||||||
|
@ -8,18 +8,14 @@ import commerce from '@lib/api/commerce'
|
|||||||
import { Layout } from '@components/common'
|
import { Layout } from '@components/common'
|
||||||
import { ProductView } from '@components/product'
|
import { ProductView } from '@components/product'
|
||||||
|
|
||||||
import { getConfig } from '@framework/api'
|
|
||||||
import getProduct from '@framework/product/get-product'
|
|
||||||
import getAllProductPaths from '@framework/product/get-all-product-paths'
|
|
||||||
|
|
||||||
export async function getStaticProps({
|
export async function getStaticProps({
|
||||||
params,
|
params,
|
||||||
locale,
|
locale,
|
||||||
preview,
|
preview,
|
||||||
}: GetStaticPropsContext<{ slug: string }>) {
|
}: GetStaticPropsContext<{ slug: string }>) {
|
||||||
const config = getConfig({ locale })
|
const config = { locale }
|
||||||
const { pages } = await commerce.getAllPages({ config, preview })
|
const { pages } = await commerce.getAllPages({ config, preview })
|
||||||
const { product } = await getProduct({
|
const { product } = await commerce.getProduct({
|
||||||
variables: { slug: params!.slug },
|
variables: { slug: params!.slug },
|
||||||
config,
|
config,
|
||||||
preview,
|
preview,
|
||||||
@ -39,18 +35,18 @@ export async function getStaticProps({
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getStaticPaths({ locales }: GetStaticPathsContext) {
|
export async function getStaticPaths({ locales }: GetStaticPathsContext) {
|
||||||
const { products } = await getAllProductPaths()
|
const { products } = await commerce.getAllProductPaths()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
paths: locales
|
paths: locales
|
||||||
? locales.reduce<string[]>((arr, locale) => {
|
? locales.reduce<string[]>((arr, locale) => {
|
||||||
// Add a product path for every locale
|
// Add a product path for every locale
|
||||||
products.forEach((product) => {
|
products.forEach((product) => {
|
||||||
arr.push(`/${locale}/product${product.node.path}`)
|
arr.push(`/${locale}/product${product.path}`)
|
||||||
})
|
})
|
||||||
return arr
|
return arr
|
||||||
}, [])
|
}, [])
|
||||||
: products.map((product) => `/product${product.node.path}`),
|
: products.map((product) => `/product${product.path}`),
|
||||||
fallback: 'blocking',
|
fallback: 'blocking',
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
import type { GetStaticPropsContext } from 'next'
|
import type { GetStaticPropsContext } from 'next'
|
||||||
import { getConfig } from '@framework/api'
|
|
||||||
import useCustomer from '@framework/customer/use-customer'
|
import useCustomer from '@framework/customer/use-customer'
|
||||||
import commerce from '@lib/api/commerce'
|
import commerce from '@lib/api/commerce'
|
||||||
import { Layout } from '@components/common'
|
import { Layout } from '@components/common'
|
||||||
@ -9,7 +8,7 @@ export async function getStaticProps({
|
|||||||
preview,
|
preview,
|
||||||
locale,
|
locale,
|
||||||
}: GetStaticPropsContext) {
|
}: GetStaticPropsContext) {
|
||||||
const config = getConfig({ locale })
|
const config = { locale }
|
||||||
const { pages } = await commerce.getAllPages({ config, preview })
|
const { pages } = await commerce.getAllPages({ config, preview })
|
||||||
return {
|
return {
|
||||||
props: { pages },
|
props: { pages },
|
||||||
|
@ -8,7 +8,6 @@ import { Layout } from '@components/common'
|
|||||||
import { ProductCard } from '@components/product'
|
import { ProductCard } from '@components/product'
|
||||||
import { Container, Grid, Skeleton } from '@components/ui'
|
import { Container, Grid, Skeleton } from '@components/ui'
|
||||||
|
|
||||||
import { getConfig } from '@framework/api'
|
|
||||||
import useSearch from '@framework/product/use-search'
|
import useSearch from '@framework/product/use-search'
|
||||||
import commerce from '@lib/api/commerce'
|
import commerce from '@lib/api/commerce'
|
||||||
import rangeMap from '@lib/range-map'
|
import rangeMap from '@lib/range-map'
|
||||||
@ -36,7 +35,7 @@ export async function getStaticProps({
|
|||||||
preview,
|
preview,
|
||||||
locale,
|
locale,
|
||||||
}: GetStaticPropsContext) {
|
}: GetStaticPropsContext) {
|
||||||
const config = getConfig({ locale })
|
const config = { locale }
|
||||||
const { pages } = await commerce.getAllPages({ config, preview })
|
const { pages } = await commerce.getAllPages({ config, preview })
|
||||||
const { categories, brands } = await commerce.getSiteInfo({ config, preview })
|
const { categories, brands } = await commerce.getSiteInfo({ config, preview })
|
||||||
return {
|
return {
|
||||||
|
@ -4,7 +4,6 @@ import { Heart } from '@components/icons'
|
|||||||
import { Layout } from '@components/common'
|
import { Layout } from '@components/common'
|
||||||
import { Text, Container } from '@components/ui'
|
import { Text, Container } from '@components/ui'
|
||||||
import { defaultPageProps } from '@lib/defaults'
|
import { defaultPageProps } from '@lib/defaults'
|
||||||
import { getConfig } from '@framework/api'
|
|
||||||
import { useCustomer } from '@framework/customer'
|
import { useCustomer } from '@framework/customer'
|
||||||
import { WishlistCard } from '@components/wishlist'
|
import { WishlistCard } from '@components/wishlist'
|
||||||
import useWishlist from '@framework/wishlist/use-wishlist'
|
import useWishlist from '@framework/wishlist/use-wishlist'
|
||||||
@ -20,7 +19,7 @@ export async function getStaticProps({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const config = getConfig({ locale })
|
const config = { locale }
|
||||||
const { pages } = await commerce.getAllPages({ config, preview })
|
const { pages } = await commerce.getAllPages({ config, preview })
|
||||||
return {
|
return {
|
||||||
props: {
|
props: {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user