feat: disable Wishlist

chore: setup commerce & next config
fix: replace all call to bigcommerce from aquilacms provider
feat add validation to input in signup
This commit is contained in:
Gérard Le Cloerec 2021-04-06 15:08:19 +02:00
parent 0545984342
commit 3f41969f5c
68 changed files with 2158 additions and 7642 deletions

View File

@ -1,7 +1,7 @@
{ {
"provider": "bigcommerce", "provider": "aquilacms",
"features": { "features": {
"wishlist": true, "wishlist": false,
"customCheckout": false "customCheckout": false
} }
} }

View File

@ -48,11 +48,13 @@ const SignUpView: FC<Props> = () => {
const handleValidation = useCallback(() => { const handleValidation = useCallback(() => {
// Test for Alphanumeric password // Test for Alphanumeric password
const validPassword = /^(?=.*[a-zA-Z])(?=.*[0-9])/.test(password) const validPassword = /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[^\w\d:])([^\s]){6,}$/.test(
password
)
// Unable to send form unless fields are valid. // Unable to send form unless fields are valid.
if (dirty) { if (dirty) {
setDisabled(!validate(email) || password.length < 7 || !validPassword) setDisabled(!validate(email) || password.length < 6 || !validPassword)
} }
}, [email, password, dirty]) }, [email, password, dirty])
@ -81,8 +83,8 @@ const SignUpView: FC<Props> = () => {
<Info width="15" height="15" /> <Info width="15" height="15" />
</span>{' '} </span>{' '}
<span className="leading-6 text-sm"> <span className="leading-6 text-sm">
<strong>Info</strong>: Passwords must be longer than 7 chars and <strong>Info</strong>: Passwords must be longer than 6 chars and
include numbers.{' '} include numbers, upper and lower case.{' '}
</span> </span>
</span> </span>
<div className="pt-2 w-full flex flex-col"> <div className="pt-2 w-full flex flex-col">

View File

@ -120,7 +120,7 @@ const CartSidebarView: FC = () => {
</li> </li>
<li className="flex justify-between py-1"> <li className="flex justify-between py-1">
<span>Estimated Shipping</span> <span>Estimated Shipping</span>
<span className="font-bold tracking-wide">FREE</span> <span>Calculated at checkout</span>
</li> </li>
</ul> </ul>
<div className="flex justify-between border-t border-accents-3 py-3 font-bold mb-10"> <div className="flex justify-between border-t border-accents-3 py-3 font-bold mb-10">

View File

@ -15,7 +15,7 @@ interface Props {
pages?: Page[] pages?: Page[]
} }
const LEGAL_PAGES = ['terms-of-use', 'shipping-returns', 'privacy-policy'] const LEGAL_PAGES = ['legal-notice', 'terms']
const Footer: FC<Props> = ({ className, pages }) => { const Footer: FC<Props> = ({ className, pages }) => {
const { sitePages, legalPages } = usePages(pages) const { sitePages, legalPages } = usePages(pages)
@ -37,7 +37,7 @@ const Footer: FC<Props> = ({ className, pages }) => {
</div> </div>
<div className="col-span-1 lg:col-span-2"> <div className="col-span-1 lg:col-span-2">
<ul className="flex flex-initial flex-col md:flex-1"> <ul className="flex flex-initial flex-col md:flex-1">
<li className="py-3 md:py-0 md:pb-4"> {/* <li className="py-3 md:py-0 md:pb-4">
<Link href="/"> <Link href="/">
<a className="text-primary hover:text-accents-6 transition ease-in-out duration-150"> <a className="text-primary hover:text-accents-6 transition ease-in-out duration-150">
Home Home
@ -57,7 +57,7 @@ const Footer: FC<Props> = ({ className, pages }) => {
Blog Blog
</a> </a>
</Link> </Link>
</li> </li> */}
{sitePages.map((page) => ( {sitePages.map((page) => (
<li key={page.url} className="py-3 md:py-0 md:pb-4"> <li key={page.url} className="py-3 md:py-0 md:pb-4">
<Link href={page.url!}> <Link href={page.url!}>

View File

@ -2,10 +2,10 @@ import React, { FC, useState } from 'react'
import cn from 'classnames' import cn from 'classnames'
import { useUI } from '@components/ui' import { useUI } from '@components/ui'
import { Heart } from '@components/icons' import { Heart } from '@components/icons'
import useAddItem from '@framework/wishlist/use-add-item' // import useAddItem from '@framework/wishlist/use-add-item'
import useCustomer from '@framework/customer/use-customer' import useCustomer from '@framework/customer/use-customer'
import useWishlist from '@framework/wishlist/use-wishlist' // import useWishlist from '@framework/wishlist/use-wishlist'
import useRemoveItem from '@framework/wishlist/use-remove-item' // import useRemoveItem from '@framework/wishlist/use-remove-item'
import type { Product, ProductVariant } from '@commerce/types' import type { Product, ProductVariant } from '@commerce/types'
type Props = { type Props = {
@ -19,8 +19,11 @@ const WishlistButton: FC<Props> = ({
className, className,
...props ...props
}) => { }) => {
// @ts-ignore
const { data } = useWishlist() const { data } = useWishlist()
// @ts-ignore
const addItem = useAddItem() const addItem = useAddItem()
// @ts-ignore
const removeItem = useRemoveItem() const removeItem = useRemoveItem()
const { data: customer } = useCustomer() const { data: customer } = useCustomer()
const { openModal, setModalView } = useUI() const { openModal, setModalView } = useUI()

View File

@ -10,7 +10,7 @@ import { useUI } from '@components/ui/context'
import type { Product } from '@commerce/types' import type { Product } from '@commerce/types'
import usePrice from '@framework/product/use-price' import usePrice from '@framework/product/use-price'
import useAddItem from '@framework/cart/use-add-item' import useAddItem from '@framework/cart/use-add-item'
import useRemoveItem from '@framework/wishlist/use-remove-item' // import useRemoveItem from '@framework/wishlist/use-remove-item'
interface Props { interface Props {
product: Product product: Product

View File

@ -1,6 +1,2 @@
BIGCOMMERCE_STOREFRONT_API_URL= AQUILACMS_URL=
BIGCOMMERCE_STOREFRONT_API_TOKEN= AQUILACMS_API_URL=
BIGCOMMERCE_STORE_API_URL=
BIGCOMMERCE_STORE_API_TOKEN=
BIGCOMMERCE_STORE_API_CLIENT_ID=
BIGCOMMERCE_CHANNEL_ID=

View File

@ -1,6 +1,7 @@
import { parseCartItem } from '../../utils/parse-item'
import getCartCookie from '../../utils/get-cart-cookie' import getCartCookie from '../../utils/get-cart-cookie'
import type { CartHandlers } from '..' import type { CartHandlers } from '..'
import { AquilacmsCart } from '../../../types'
import { normalizeCart } from '../../../lib/normalize'
const addItem: CartHandlers['addItem'] = async ({ const addItem: CartHandlers['addItem'] = async ({
res, res,
@ -14,32 +15,23 @@ const addItem: CartHandlers['addItem'] = async ({
}) })
} }
if (!item.quantity) item.quantity = 1 if (!item.quantity) item.quantity = 1
const result: AquilacmsCart = await config.storeApiFetch('/v2/cart/item', {
const options = { method: 'PUT',
method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
line_items: [parseCartItem(item)], cartId,
...(!cartId && config.storeChannelId item: {
? { channel_id: config.storeChannelId } id: item.productId,
: {}), quantity: item.quantity,
},
}), }),
} })
const { data } = cartId
? await config.storeApiFetch(
`/v3/carts/${cartId}/items?include=line_items.physical_items.options`,
options
)
: await config.storeApiFetch(
'/v3/carts?include=line_items.physical_items.options',
options
)
// Create or update the cart cookie // Create or update the cart cookie
res.setHeader( res.setHeader(
'Set-Cookie', 'Set-Cookie',
getCartCookie(config.cartCookie, data.id, config.cartCookieMaxAge) getCartCookie(config.cartCookie, result._id, config.cartCookieMaxAge)
) )
res.status(200).json({ data }) res.status(200).json({ data: normalizeCart(result) })
} }
export default addItem export default addItem

View File

@ -2,6 +2,7 @@ import type { AquilacmsCart } from '../../../types'
import { AquilacmsApiError } from '../../utils/errors' import { AquilacmsApiError } from '../../utils/errors'
import getCartCookie from '../../utils/get-cart-cookie' import getCartCookie from '../../utils/get-cart-cookie'
import type { CartHandlers } from '..' import type { CartHandlers } from '..'
import { normalizeCart } from '../../../lib/normalize'
// Return current cart info // Return current cart info
const getCart: CartHandlers['getCart'] = async ({ const getCart: CartHandlers['getCart'] = async ({
@ -9,13 +10,21 @@ const getCart: CartHandlers['getCart'] = async ({
body: { cartId }, body: { cartId },
config, config,
}) => { }) => {
let result: { data?: AquilacmsCart } = {}
if (cartId) { if (cartId) {
try { try {
result = await config.storeApiFetch( let result: AquilacmsCart = await config.storeApiFetch(
`/v3/carts/${cartId}?include=line_items.physical_items.options` `/v2/cart/${cartId}`,
{
method: 'POST',
body: JSON.stringify({
lang: 'en',
PostBody: {
populate: ['items.id'],
},
}),
}
) )
return res.status(200).json({ data: normalizeCart(result) })
} catch (error) { } catch (error) {
if (error instanceof AquilacmsApiError && error.status === 404) { if (error instanceof AquilacmsApiError && error.status === 404) {
// Remove the cookie if it exists but the cart wasn't found // Remove the cookie if it exists but the cart wasn't found
@ -25,8 +34,7 @@ const getCart: CartHandlers['getCart'] = async ({
} }
} }
} }
res.status(200).json({ data: null })
res.status(200).json({ data: result.data ?? null })
} }
export default getCart export default getCart

View File

@ -1,5 +1,7 @@
import getCartCookie from '../../utils/get-cart-cookie' import getCartCookie from '../../utils/get-cart-cookie'
import type { CartHandlers } from '..' import type { CartHandlers } from '..'
import { AquilacmsCart } from '../../../types'
import { normalizeCart } from '../../../lib/normalize'
const removeItem: CartHandlers['removeItem'] = async ({ const removeItem: CartHandlers['removeItem'] = async ({
res, res,
@ -13,11 +15,13 @@ const removeItem: CartHandlers['removeItem'] = async ({
}) })
} }
const result = await config.storeApiFetch<{ data: any } | null>( const result: AquilacmsCart = await config.storeApiFetch(
`/v3/carts/${cartId}/items/${itemId}?include=line_items.physical_items.options`, `/v2/cart/${cartId}/item/${itemId}`,
{ method: 'DELETE' } {
method: 'DELETE',
}
) )
const data = result?.data ?? null let data = normalizeCart(result) ?? null
res.setHeader( res.setHeader(
'Set-Cookie', 'Set-Cookie',

View File

@ -1,6 +1,7 @@
import { parseCartItem } from '../../utils/parse-item'
import getCartCookie from '../../utils/get-cart-cookie' import getCartCookie from '../../utils/get-cart-cookie'
import type { CartHandlers } from '..' import type { CartHandlers } from '..'
import { AquilacmsCart } from '../../../types'
import { normalizeCart } from '../../../lib/normalize'
const updateItem: CartHandlers['updateItem'] = async ({ const updateItem: CartHandlers['updateItem'] = async ({
res, res,
@ -14,14 +15,19 @@ const updateItem: CartHandlers['updateItem'] = async ({
}) })
} }
const { data } = await config.storeApiFetch( const options = {
`/v3/carts/${cartId}/items/${itemId}?include=line_items.physical_items.options`,
{
method: 'PUT', method: 'PUT',
body: JSON.stringify({ body: JSON.stringify({
line_item: parseCartItem(item), item: {
_id: itemId,
quantity: item.quantity,
},
cartId,
}), }),
} }
const result: AquilacmsCart = await config.storeApiFetch(
'/v2/cart/updateqty',
options
) )
// Update the cart cookie // Update the cart cookie
@ -29,7 +35,7 @@ const updateItem: CartHandlers['updateItem'] = async ({
'Set-Cookie', 'Set-Cookie',
getCartCookie(config.cartCookie, cartId, config.cartCookieMaxAge) getCartCookie(config.cartCookie, cartId, config.cartCookieMaxAge)
) )
res.status(200).json({ data }) res.status(200).json({ data: normalizeCart(result) })
} }
export default updateItem export default updateItem

View File

@ -14,19 +14,20 @@ import type {
AddCartItemHandlerBody, AddCartItemHandlerBody,
UpdateCartItemHandlerBody, UpdateCartItemHandlerBody,
RemoveCartItemHandlerBody, RemoveCartItemHandlerBody,
Cart,
} from '../../types' } from '../../types'
export type CartHandlers = { export type CartHandlers = {
getCart: AquilacmsHandler<AquilacmsCart, GetCartHandlerBody> getCart: AquilacmsHandler<Cart, GetCartHandlerBody>
addItem: AquilacmsHandler<AquilacmsCart, AddCartItemHandlerBody> addItem: AquilacmsHandler<Cart, AddCartItemHandlerBody>
updateItem: AquilacmsHandler<AquilacmsCart, UpdateCartItemHandlerBody> updateItem: AquilacmsHandler<Cart, UpdateCartItemHandlerBody>
removeItem: AquilacmsHandler<AquilacmsCart, RemoveCartItemHandlerBody> removeItem: AquilacmsHandler<Cart, RemoveCartItemHandlerBody>
} }
const METHODS = ['GET', 'POST', 'PUT', 'DELETE'] const METHODS = ['GET', 'POST', 'PUT', 'DELETE']
// TODO: a complete implementation should have schema validation for `req.body` // TODO: a complete implementation should have schema validation for `req.body`
const cartApi: AquilacmsApiHandler<AquilacmsCart, CartHandlers> = async ( const cartApi: AquilacmsApiHandler<Cart, CartHandlers> = async (
req, req,
res, res,
config, config,

View File

@ -1,5 +1,6 @@
import { Product } from '@commerce/types' import { Product } from '@commerce/types'
import getAllProducts, { ProductEdge } from '../../../product/get-all-products' import { normalizeProduct } from '../../../lib/normalize'
import getAllProducts from '../../../product/get-all-products'
import type { ProductsHandlers } from '../products' import type { ProductsHandlers } from '../products'
const SORT: { [key: string]: string | undefined } = { const SORT: { [key: string]: string | undefined } = {
@ -13,65 +14,87 @@ const LIMIT = 12
// Return current cart info // Return current cart info
const getProducts: ProductsHandlers['getProducts'] = async ({ const getProducts: ProductsHandlers['getProducts'] = async ({
res, res,
body: { search, category, brand, sort }, body: { search, category, brand, sort: sortParam },
config, config,
}) => { }) => {
// Use a dummy base as we only care about the relative path let filter: any = {}
const url = new URL('/v3/catalog/products', 'http://a') let sort = {}
url.searchParams.set('is_visible', 'true') if (search) filter['$text'] = { $search: search }
url.searchParams.set('limit', String(LIMIT))
if (search) url.searchParams.set('keyword', search) if (category) {
const cat: any = await config.storeApiFetch('/v2/category', {
method: 'POST',
body: JSON.stringify({
lang: 'en',
PostBody: {
filter: {
_id: category,
},
structure: {
productsList: 1,
},
page: 1,
limit: 1,
},
}),
})
if (category && Number.isInteger(Number(category))) const productIds: string[] = cat.productsList
url.searchParams.set('categories:in', category) .filter((p: any) => p.checked)
.map((p: any) => p.id)
// if (search) {
// filter = {
// $and: [{ ...filter }, { _id: { $in: productIds } }],
// }
// } else {
filter = {
_id: { $in: productIds },
}
// }
}
if (brand && Number.isInteger(Number(brand))) if (sortParam) {
url.searchParams.set('brand_id', brand) const [_sort, direction] = sortParam.split('-')
if (sort) {
const [_sort, direction] = sort.split('-')
const sortValue = SORT[_sort] const sortValue = SORT[_sort]
if (sortValue && direction) { if (sortValue && direction) {
url.searchParams.set('sort', sortValue) switch (sortValue) {
url.searchParams.set('direction', direction) case 'latest':
// 'desc'
console.log(`sort by ${sortValue} not implemented`)
case 'trending':
// 'desc'
console.log(`sort by ${sortValue} not implemented`)
case 'price':
if (direction === 'asc') sort = { 'price.priceSort.ati': 1 }
else if (direction === 'desc') sort = { 'price.priceSort.ati': -1 }
}
} }
} }
// We only want the id of each product const { datas } = await config.storeApiFetch('/v2/products', {
url.searchParams.set('include_fields', 'id') method: 'POST',
body: JSON.stringify({
const { data } = await config.storeApiFetch<{ data: { id: number }[] }>( lang: 'en',
url.pathname + url.search PostBody: {
) filter,
structure: {
const entityIds = data.map((p) => p.id) canonical: 1,
const found = entityIds.length > 0 reviews: 1,
stock: 1,
// We want the GraphQL version of each product universe: 1,
const graphqlData = await getAllProducts({ },
variables: { first: LIMIT, entityIds }, // populate: ['bundle_sections.products.id'],
config, sort,
page: 1,
limit: LIMIT,
},
}),
}) })
// Put the products in an object that we can use to get them by id const found = datas ? datas.length > 0 : false
const productsById = graphqlData.products.reduce<{ const products = datas ? datas.map(normalizeProduct) : []
[k: number]: Product
}>((prods, p) => {
prods[Number(p.id)] = p
return prods
}, {})
const products: Product[] = found ? [] : graphqlData.products
// Populate the products array with the graphql products, in the order
// assigned by the list of entity ids
entityIds.forEach((id) => {
const product = productsById[id]
if (product) products.push(product)
})
res.status(200).json({ data: { products, found } }) res.status(200).json({ data: { products, found } })
} }

View File

@ -5,7 +5,7 @@ import createApiHandler, {
import { AquilacmsApiError } from './utils/errors' import { AquilacmsApiError } from './utils/errors'
const METHODS = ['GET'] const METHODS = ['GET']
const fullCheckout = true const fullCheckout = false
// TODO: a complete implementation should have schema validation for `req.body` // TODO: a complete implementation should have schema validation for `req.body`
const checkoutApi: AquilacmsApiHandler<any> = async (req, res, config) => { const checkoutApi: AquilacmsApiHandler<any> = async (req, res, config) => {
@ -13,6 +13,8 @@ const checkoutApi: AquilacmsApiHandler<any> = async (req, res, config) => {
const { cookies } = req const { cookies } = req
const cartId = cookies[config.cartCookie] const cartId = cookies[config.cartCookie]
const token = cookies[config.customerCookie]
console.log(config.customerCookie, cookies)
try { try {
if (!cartId) { if (!cartId) {
@ -20,14 +22,13 @@ const checkoutApi: AquilacmsApiHandler<any> = async (req, res, config) => {
return return
} }
if (fullCheckout) {
const { data } = await config.storeApiFetch( const { data } = await config.storeApiFetch(
`/v3/carts/${cartId}/redirect_urls`, `/v/carts/${cartId}/redirect_urls`,
{ {
method: 'POST', method: 'POST',
} }
) )
if (fullCheckout) {
res.redirect(data.checkout_url) res.redirect(data.checkout_url)
return return
} }
@ -40,20 +41,13 @@ const checkoutApi: AquilacmsApiHandler<any> = async (req, res, config) => {
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Checkout</title> <title>Checkout</title>
<script src="https://checkout-sdk.bigcommerce.com/v1/loader.js"></script>
<script> <script>
window.onload = function() { window.onload = () => {
checkoutKitLoader.load('checkout-sdk').then(function (service) { window.location.href = "${process.env.AQUILACMS_URL}/cart/address?jwt=${token}&cartid=${cartId}"
service.embedCheckout({
containerId: 'checkout',
url: '${data.embedded_checkout_url}'
});
});
} }
</script> </script>
</head> </head>
<body> <body>
<div id="checkout"></div>
</body> </body>
</html> </html>
` `

View File

@ -1,28 +1,8 @@
import type { GetLoggedInCustomerQuery } from '../../../schema'
import type { CustomersHandlers } from '..' import type { CustomersHandlers } from '..'
import { normalizeUser } from '../../../lib/normalize'
import type { AquilacmsUser, User } from '../../../types'
export const getLoggedInCustomerQuery = /* GraphQL */ ` export type Customer = User
query getLoggedInCustomer {
customer {
entityId
firstName
lastName
email
company
customerGroupId
notes
phone
addressCount
attributeCount
storeCredit {
value
currencyCode
}
}
}
`
export type Customer = NonNullable<GetLoggedInCustomerQuery['customer']>
const getLoggedInCustomer: CustomersHandlers['getLoggedInCustomer'] = async ({ const getLoggedInCustomer: CustomersHandlers['getLoggedInCustomer'] = async ({
req, req,
@ -32,25 +12,27 @@ const getLoggedInCustomer: CustomersHandlers['getLoggedInCustomer'] = async ({
const token = req.cookies[config.customerCookie] const token = req.cookies[config.customerCookie]
if (token) { if (token) {
const { data } = await config.fetch<GetLoggedInCustomerQuery>( try {
getLoggedInCustomerQuery, const data = await config.storeApiFetch('/v2/user', {
undefined, method: 'POST',
{ body: JSON.stringify({
PostBody: {},
}),
headers: { headers: {
cookie: `${config.customerCookie}=${token}`, authorization: token,
}, },
} })
) if (!data) {
const { customer } = data
if (!customer) {
return res.status(400).json({ return res.status(400).json({
data: null, data: null,
errors: [{ message: 'Customer not found', code: 'not_found' }], errors: [{ message: 'Customer not found', code: 'not_found' }],
}) })
} }
const customer = normalizeUser(data as AquilacmsUser)
return res.status(200).json({ data: { customer } }) return res.status(200).json({ data: { customer } })
} catch (err) {
console.error(err)
}
} }
res.status(200).json({ data: null }) res.status(200).json({ data: null })

View File

@ -1,4 +1,5 @@
import { serialize } from 'cookie' import { serialize } from 'cookie'
import { getConfig } from '../..'
import { LogoutHandlers } from '../logout' import { LogoutHandlers } from '../logout'
const logoutHandler: LogoutHandlers['logout'] = async ({ const logoutHandler: LogoutHandlers['logout'] = async ({
@ -6,6 +7,12 @@ const logoutHandler: LogoutHandlers['logout'] = async ({
body: { redirectTo }, body: { redirectTo },
config, config,
}) => { }) => {
config = getConfig(config)
await config.storeApiFetch('/v2/auth/logout', {
method: 'GET',
})
// Remove the cookie // Remove the cookie
res.setHeader( res.setHeader(
'Set-Cookie', 'Set-Cookie',

View File

@ -1,36 +1,49 @@
import { AquilacmsApiError } from '../../utils/errors' import { AquilacmsApiError } from '../../utils/errors'
import login from '../../../auth/login' import login from '../../../auth/login'
import { SignupHandlers } from '../signup' import { SignupHandlers } from '../signup'
import Joi, { valid } from 'joi'
const signup: SignupHandlers['signup'] = async ({ const signup: SignupHandlers['signup'] = async ({
res, res,
body: { firstName, lastName, email, password }, body: { firstName, lastName, email, password },
config, config,
}) => { }) => {
// TODO: Add proper validations with something like Ajv const schema = Joi.object({
firstName: Joi.string().min(1),
lastName: Joi.string().min(1),
email: Joi.string().email({ tlds: false }),
password: Joi.string().pattern(
new RegExp('^(?=.*d)(?=.*[A-Z])(?=.*[a-z])(?=.*[^wd:])([^s]){6,}$')
),
})
const validation = schema.validate({ email, password })
if (!(firstName && lastName && email && password)) { if (!(firstName && lastName && email && password)) {
return res.status(400).json({ return res.status(400).json({
data: null, data: null,
errors: [{ message: 'Invalid request' }], errors: [{ message: 'Invalid request' }],
}) })
} }
// TODO: validate the password and email if (validation?.error?.details) {
// Passwords must be at least 7 characters and contain both alphabetic let message = validation.error.details[0].message
// and numeric characters. if (validation.error.details[0].path[0] === 'password')
message =
'password must have a lowercase, a uppercase, a number and be at least 6 characters long'
return res.status(400).json({
data: null,
errors: [{ message }],
})
}
try { try {
await config.storeApiFetch('/v3/customers', { await config.storeApiFetch('/v2/user', {
method: 'POST', method: 'PUT',
body: JSON.stringify([ body: JSON.stringify({
{ firstname: firstName,
first_name: firstName, lastname: lastName,
last_name: lastName,
email, email,
authentication: { password,
new_password: password, }),
},
},
]),
}) })
} catch (error) { } catch (error) {
if (error instanceof AquilacmsApiError && error.status === 422) { if (error instanceof AquilacmsApiError && error.status === 422) {

File diff suppressed because it is too large Load Diff

View File

@ -1,329 +0,0 @@
/**
* This file was auto-generated by swagger-to-ts.
* Do not make direct changes to the file.
*/
export interface definitions {
blogPost_Full: {
/**
* ID of this blog post. (READ-ONLY)
*/
id?: number
} & definitions['blogPost_Base']
addresses: {
/**
* Full URL of where the resource is located.
*/
url?: string
/**
* Resource being accessed.
*/
resource?: string
}
formField: {
/**
* Name of the form field
*/
name?: string
/**
* Value of the form field
*/
value?: string
}
page_Full: {
/**
* ID of the page.
*/
id?: number
} & definitions['page_Base']
redirect: {
/**
* Numeric ID of the redirect.
*/
id?: number
/**
* The path from which to redirect.
*/
path: string
forward: definitions['forward']
/**
* URL of the redirect. READ-ONLY
*/
url?: string
}
forward: {
/**
* The type of redirect. If it is a `manual` redirect then type will always be manual. Dynamic redirects will have the type of the page. Such as product or category.
*/
type?: string
/**
* Reference of the redirect. Dynamic redirects will have the category or product number. Manual redirects will have the url that is being directed to.
*/
ref?: number
}
customer_Full: {
/**
* Unique numeric ID of this customer. This is a READ-ONLY field; do not set or modify its value in a POST or PUT request.
*/
id?: number
/**
* Not returned in any responses, but accepts up to two fields allowing you to set the customers password. If a password is not supplied, it is generated automatically. For further information about using this object, please see the Customers resource documentation.
*/
_authentication?: {
force_reset?: string
password?: string
password_confirmation?: string
}
/**
* The name of the company for which the customer works.
*/
company?: string
/**
* First name of the customer.
*/
first_name: string
/**
* Last name of the customer.
*/
last_name: string
/**
* Email address of the customer.
*/
email: string
/**
* Phone number of the customer.
*/
phone?: string
/**
* Date on which the customer registered from the storefront or was created in the control panel. This is a READ-ONLY field; do not set or modify its value in a POST or PUT request.
*/
date_created?: string
/**
* Date on which the customer updated their details in the storefront or was updated in the control panel. This is a READ-ONLY field; do not set or modify its value in a POST or PUT request.
*/
date_modified?: string
/**
* The amount of credit the customer has. (Float, Float as String, Integer)
*/
store_credit?: string
/**
* The customers IP address when they signed up.
*/
registration_ip_address?: string
/**
* The group to which the customer belongs.
*/
customer_group_id?: number
/**
* Store-owner notes on the customer.
*/
notes?: string
/**
* Used to identify customers who fall into special sales-tax categories in particular, those who are fully or partially exempt from paying sales tax. Can be blank, or can contain a single AvaTax code. (The codes are case-sensitive.) Stores that subscribe to BigCommerces Avalara Premium integration will use this code to determine how/whether to apply sales tax. Does not affect sales-tax calculations for stores that do not subscribe to Avalara Premium.
*/
tax_exempt_category?: string
/**
* Records whether the customer would like to receive marketing content from this store. READ-ONLY.This is a READ-ONLY field; do not set or modify its value in a POST or PUT request.
*/
accepts_marketing?: boolean
addresses?: definitions['addresses']
/**
* Array of custom fields. This is a READ-ONLY field; do not set or modify its value in a POST or PUT request.
*/
form_fields?: definitions['formField'][]
/**
* Force a password change on next login.
*/
reset_pass_on_login?: boolean
}
categoryAccessLevel: {
/**
* + `all` - Customers can access all categories
* + `specific` - Customers can access a specific list of categories
* + `none` - Customers are prevented from viewing any of the categories in this group.
*/
type?: 'all' | 'specific' | 'none'
/**
* Is an array of category IDs and should be supplied only if `type` is specific.
*/
categories?: string[]
}
timeZone: {
/**
* a string identifying the time zone, in the format: <Continent-name>/<City-name>.
*/
name?: string
/**
* a negative or positive number, identifying the offset from UTC/GMT, in seconds, during winter/standard time.
*/
raw_offset?: number
/**
* "-/+" offset from UTC/GMT, in seconds, during summer/daylight saving time.
*/
dst_offset?: number
/**
* a boolean indicating whether this time zone observes daylight saving time.
*/
dst_correction?: boolean
date_format?: definitions['dateFormat']
}
count_Response: { count?: number }
dateFormat: {
/**
* string that defines dates display format, in the pattern: M jS Y
*/
display?: string
/**
* string that defines the CSV export format for orders, customers, and products, in the pattern: M jS Y
*/
export?: string
/**
* string that defines dates extended-display format, in the pattern: M jS Y @ g:i A.
*/
extended_display?: string
}
blogTags: { tag?: string; post_ids?: number[] }[]
blogPost_Base: {
/**
* Title of this blog post.
*/
title: string
/**
* URL for the public blog post.
*/
url?: string
/**
* URL to preview the blog post. (READ-ONLY)
*/
preview_url?: string
/**
* Text body of the blog post.
*/
body: string
/**
* Tags to characterize the blog post.
*/
tags?: string[]
/**
* Summary of the blog post. (READ-ONLY)
*/
summary?: string
/**
* Whether the blog post is published.
*/
is_published?: boolean
published_date?: definitions['publishedDate']
/**
* Published date in `ISO 8601` format.
*/
published_date_iso8601?: string
/**
* Description text for this blog posts `<meta/>` element.
*/
meta_description?: string
/**
* Keywords for this blog posts `<meta/>` element.
*/
meta_keywords?: string
/**
* Name of the blog posts author.
*/
author?: string
/**
* Local path to a thumbnail uploaded to `product_images/` via [WebDav](https://support.bigcommerce.com/s/article/File-Access-WebDAV).
*/
thumbnail_path?: string
}
publishedDate: { timezone_type?: string; date?: string; timezone?: string }
/**
* Not returned in any responses, but accepts up to two fields allowing you to set the customers password. If a password is not supplied, it is generated automatically. For further information about using this object, please see the Customers resource documentation.
*/
authentication: {
force_reset?: string
password?: string
password_confirmation?: string
}
customer_Base: { [key: string]: any }
page_Base: {
/**
* ID of any parent Web page.
*/
parent_id?: number
/**
* `page`: free-text page
* `link`: link to another web address
* `rss_feed`: syndicated content from an RSS feed
* `contact_form`: When the store's contact form is used.
*/
type: 'page' | 'rss_feed' | 'contact_form' | 'raw' | 'link'
/**
* Where the pages type is a contact form: object whose members are the fields enabled (in the control panel) for storefront display. Possible members are:`fullname`: full name of the customer submitting the form; `phone`: customers phone number, as submitted on the form; `companyname`: customers submitted company name; `orderno`: customers submitted order number; `rma`: customers submitted RMA (Return Merchandise Authorization) number.
*/
contact_fields?: string
/**
* Where the pages type is a contact form: email address that receives messages sent via the form.
*/
email?: string
/**
* Page name, as displayed on the storefront.
*/
name: string
/**
* Relative URL on the storefront for this page.
*/
url?: string
/**
* Description contained within this pages `<meta/>` element.
*/
meta_description?: string
/**
* HTML or variable that populates this pages `<body>` element, in default/desktop view. Required in POST if page type is `raw`.
*/
body: string
/**
* HTML to use for this page's body when viewed in the mobile template (deprecated).
*/
mobile_body?: string
/**
* If true, this page has a mobile version.
*/
has_mobile_version?: boolean
/**
* If true, this page appears in the storefronts navigation menu.
*/
is_visible?: boolean
/**
* If true, this page is the storefronts home page.
*/
is_homepage?: boolean
/**
* Text specified for this pages `<title>` element. (If empty, the value of the name property is used.)
*/
meta_title?: string
/**
* Layout template for this page. This field is writable only for stores with a Blueprint theme applied.
*/
layout_file?: string
/**
* Order in which this page should display on the storefront. (Lower integers specify earlier display.)
*/
sort_order?: number
/**
* Comma-separated list of keywords that shoppers can use to locate this page when searching the store.
*/
search_keywords?: string
/**
* Comma-separated list of SEO-relevant keywords to include in the pages `<meta/>` element.
*/
meta_keywords?: string
/**
* If page type is `rss_feed` the n this field is visisble. Required in POST required for `rss page` type.
*/
feed: string
/**
* If page type is `link` this field is returned. Required in POST to create a `link` page.
*/
link: string
content_type?: 'application/json' | 'text/javascript' | 'text/html'
}
}

View File

@ -1,142 +0,0 @@
/**
* This file was auto-generated by swagger-to-ts.
* Do not make direct changes to the file.
*/
export interface definitions {
wishlist_Post: {
/**
* The customer id.
*/
customer_id: number
/**
* Whether the wishlist is available to the public.
*/
is_public?: boolean
/**
* The title of the wishlist.
*/
name?: string
/**
* Array of Wishlist items.
*/
items?: {
/**
* The ID of the product.
*/
product_id?: number
/**
* The variant ID of the product.
*/
variant_id?: number
}[]
}
wishlist_Put: {
/**
* The customer id.
*/
customer_id: number
/**
* Whether the wishlist is available to the public.
*/
is_public?: boolean
/**
* The title of the wishlist.
*/
name?: string
/**
* Array of Wishlist items.
*/
items?: {
/**
* The ID of the item
*/
id?: number
/**
* The ID of the product.
*/
product_id?: number
/**
* The variant ID of the item.
*/
variant_id?: number
}[]
}
wishlist_Full: {
/**
* Wishlist ID, provided after creating a wishlist with a POST.
*/
id?: number
/**
* The ID the customer to which the wishlist belongs.
*/
customer_id?: number
/**
* The Wishlist's name.
*/
name?: string
/**
* Whether the Wishlist is available to the public.
*/
is_public?: boolean
/**
* The token of the Wishlist. This is created internally within BigCommerce. The Wishlist ID is to be used for external apps. Read-Only
*/
token?: string
/**
* Array of Wishlist items
*/
items?: definitions['wishlistItem_Full'][]
}
wishlistItem_Full: {
/**
* The ID of the item
*/
id?: number
/**
* The ID of the product.
*/
product_id?: number
/**
* The variant ID of the item.
*/
variant_id?: number
}
wishlistItem_Post: {
/**
* The ID of the product.
*/
product_id?: number
/**
* The variant ID of the product.
*/
variant_id?: number
}
/**
* Data about the response, including pagination and collection totals.
*/
pagination: {
/**
* Total number of items in the result set.
*/
total?: number
/**
* Total number of items in the collection response.
*/
count?: number
/**
* The amount of items returned in the collection per page, controlled by the limit parameter.
*/
per_page?: number
/**
* The page you are currently on within the collection.
*/
current_page?: number
/**
* The total number of pages in the collection.
*/
total_pages?: number
}
error: { status?: number; title?: string; type?: string }
metaCollection: { pagination?: definitions['pagination'] }
}

View File

@ -1,9 +0,0 @@
export const categoryTreeItemFragment = /* GraphQL */ `
fragment categoryTreeItem on CategoryTreeItem {
entityId
name
path
description
productCount
}
`

View File

@ -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}
`

View File

@ -29,13 +29,8 @@ if (!STORE_API_URL) {
export class Config { export class Config {
private config: AquilacmsConfig private config: AquilacmsConfig
constructor(config: Omit<AquilacmsConfig, 'customerCookie'>) { constructor(config: AquilacmsConfig) {
this.config = { this.config = 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<AquilacmsConfig> = {}) { getConfig(userConfig: Partial<AquilacmsConfig> = {}) {
@ -60,6 +55,7 @@ const config = new Config({
applyLocale: true, applyLocale: true,
storeApiUrl: STORE_API_URL, storeApiUrl: STORE_API_URL,
storeApiFetch: fetchStoreApi, storeApiFetch: fetchStoreApi,
customerCookie: 'jwt',
}) })
export function getConfig(userConfig?: Partial<AquilacmsConfig>) { export function getConfig(userConfig?: Partial<AquilacmsConfig>) {

View File

@ -16,8 +16,6 @@ export default async function fetchStoreApi<T>(
headers: { headers: {
...options?.headers, ...options?.headers,
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Auth-Token': config.storeApiToken,
'X-Auth-Client': config.storeApiClientId,
}, },
}) })
} catch (error) { } catch (error) {
@ -32,7 +30,7 @@ export default async function fetchStoreApi<T>(
if (!res.ok) { if (!res.ok) {
const data = isJSON ? await res.json() : await getTextOrNull(res) const data = isJSON ? await res.json() : await getTextOrNull(res)
const headers = getRawHeaders(res) const headers = getRawHeaders(res)
const msg = `Big Commerce API error (${ const msg = `Aquilacms API error (${
res.status res.status
}) \nHeaders: ${JSON.stringify(headers, null, 2)}\n${ }) \nHeaders: ${JSON.stringify(headers, null, 2)}\n${
typeof data === 'string' ? data : JSON.stringify(data, null, 2) typeof data === 'string' ? data : JSON.stringify(data, null, 2)
@ -40,7 +38,6 @@ export default async function fetchStoreApi<T>(
throw new AquilacmsApiError(msg, res, data) throw new AquilacmsApiError(msg, res, data)
} }
if (res.status !== 204 && !isJSON) { if (res.status !== 204 && !isJSON) {
throw new AquilacmsApiError( throw new AquilacmsApiError(
`Fetch to Aquilacms API failed, expected JSON content but found: ${contentType}`, `Fetch to Aquilacms API failed, expected JSON content but found: ${contentType}`,

View File

@ -1,5 +0,0 @@
export default function filterEdges<T>(
edges: (T | null | undefined)[] | null | undefined
) {
return edges?.filter((edge): edge is T => !!edge) ?? []
}

View File

@ -1,28 +0,0 @@
import type { ItemBody as WishlistItemBody } from '../wishlist'
import type { CartItemBody, OptionSelections } from '../../types'
type BCWishlistItemBody = {
product_id: number
variant_id: number
}
type BCCartItemBody = {
product_id: number
variant_id: number
quantity?: number
option_selections?: OptionSelections
}
export const parseWishlistItem = (
item: WishlistItemBody
): BCWishlistItemBody => ({
product_id: Number(item.productId),
variant_id: Number(item.variantId),
})
export const parseCartItem = (item: CartItemBody): BCCartItemBody => ({
quantity: item.quantity,
product_id: Number(item.productId),
variant_id: Number(item.variantId),
option_selections: item.optionSelections,
})

View File

@ -1,21 +0,0 @@
import type { ProductNode } from '../../product/get-all-products'
import type { RecursivePartial } from './types'
export default function setProductLocaleMeta(
node: RecursivePartial<ProductNode>
) {
if (node.localeMeta?.edges) {
node.localeMeta.edges = node.localeMeta.edges.filter((edge) => {
const { key, value } = edge?.node ?? {}
if (key && key in node) {
;(node as any)[key] = value
return false
}
return true
})
if (!node.localeMeta.edges.length) {
delete node.localeMeta
}
}
}

View File

@ -1,56 +0,0 @@
import type { WishlistHandlers } from '..'
import getCustomerId from '../../../customer/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

View File

@ -1,37 +0,0 @@
import getCustomerId from '../../../customer/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

View File

@ -1,39 +0,0 @@
import getCustomerId from '../../../customer/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

View File

@ -1,104 +0,0 @@
import isAllowedMethod from '../utils/is-allowed-method'
import createApiHandler, {
AquilacmsApiHandler,
AquilacmsHandler,
} from '../utils/create-api-handler'
import { AquilacmsApiError } 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: AquilacmsHandler<
Wishlist,
{ customerToken?: string; includeProducts?: boolean }
>
addItem: AquilacmsHandler<
Wishlist,
{ customerToken?: string } & Partial<AddItemBody>
>
removeItem: AquilacmsHandler<
Wishlist,
{ customerToken?: string } & Partial<RemoveItemBody>
>
}
const METHODS = ['GET', 'POST', 'DELETE']
// TODO: a complete implementation should have schema validation for `req.body`
const wishlistApi: AquilacmsApiHandler<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 AquilacmsApiError
? 'An unexpected error ocurred with the Aquilacms API'
: 'An unexpected error ocurred'
res.status(500).json({ data: null, errors: [{ message }] })
}
}
export const handlers = {
getWishlist,
addItem,
removeItem,
}
export default createApiHandler(wishlistApi, handlers, {})

View File

@ -1,20 +1,11 @@
import type { ServerResponse } from 'http' import type { ServerResponse } from 'http'
import type { LoginMutation, LoginMutationVariables } from '../schema'
import type { RecursivePartial } from '../api/utils/types'
import concatHeader from '../api/utils/concat-cookie' import concatHeader from '../api/utils/concat-cookie'
import { AquilacmsConfig, getConfig } from '../api' import { AquilacmsConfig, getConfig } from '../api'
import { serialize } from 'cookie'
export const loginMutation = /* GraphQL */ `
mutation login($email: String!, $password: String!) {
login(email: $email, password: $password) {
result
}
}
`
export type LoginResult<T extends { result?: any } = { result?: string }> = T export type LoginResult<T extends { result?: any } = { result?: string }> = T
export type LoginVariables = LoginMutationVariables export type LoginVariables = { email: string; password: string }
async function login(opts: { async function login(opts: {
variables: LoginVariables variables: LoginVariables
@ -30,7 +21,6 @@ async function login<T extends { result?: any }, V = any>(opts: {
}): Promise<LoginResult<T>> }): Promise<LoginResult<T>>
async function login({ async function login({
query = loginMutation,
variables, variables,
res: response, res: response,
config, config,
@ -42,31 +32,24 @@ async function login({
}): Promise<LoginResult> { }): Promise<LoginResult> {
config = getConfig(config) config = getConfig(config)
const { data, res } = await config.fetch<RecursivePartial<LoginMutation>>( const { data, code: result } = await config.storeApiFetch('/v2/auth/login', {
query, method: 'POST',
{ variables } body: JSON.stringify({
) username: variables.email,
// Bigcommerce returns a Set-Cookie header with the auth cookie password: variables.password,
let cookie = res.headers.get('Set-Cookie') }),
})
if (cookie && typeof cookie === 'string') {
// In development, don't set a secure cookie or the browser will ignore it
if (process.env.NODE_ENV !== 'production') {
cookie = cookie.replace('; Secure', '')
// SameSite=none can't be set unless the cookie is Secure
// bc seems to sometimes send back SameSite=None rather than none so make
// this case insensitive
cookie = cookie.replace(/; SameSite=none/gi, '; SameSite=lax')
}
response.setHeader( response.setHeader(
'Set-Cookie', 'Set-Cookie',
concatHeader(response.getHeader('Set-Cookie'), cookie)! concatHeader(
response.getHeader('Set-Cookie'),
serialize(config.customerCookie, data, { sameSite: 'lax', path: '/' })
)!
) )
}
return { return {
result: data.login?.result, result,
} }
} }

View File

@ -3,12 +3,7 @@ import type { MutationHook } from '@commerce/utils/types'
import { CommerceError } from '@commerce/utils/errors' import { CommerceError } from '@commerce/utils/errors'
import useAddItem, { UseAddItem } from '@commerce/cart/use-add-item' import useAddItem, { UseAddItem } from '@commerce/cart/use-add-item'
import { normalizeCart } from '../lib/normalize' import { normalizeCart } from '../lib/normalize'
import type { import type { Cart, CartItemBody, AddCartItemBody } from '../types'
Cart,
AquilacmsCart,
CartItemBody,
AddCartItemBody,
} from '../types'
import useCart from './use-cart' import useCart from './use-cart'
export default useAddItem as UseAddItem<typeof handler> export default useAddItem as UseAddItem<typeof handler>
@ -28,12 +23,13 @@ export const handler: MutationHook<Cart, {}, CartItemBody> = {
}) })
} }
const data = await fetch<AquilacmsCart, AddCartItemBody>({ const data = await fetch<Cart, AddCartItemBody>({
...options, ...options,
body: { item }, body: { item },
}) })
return normalizeCart(data) // return normalizeCart(data)
return data
}, },
useHook: ({ fetch }) => () => { useHook: ({ fetch }) => () => {
const { mutate } = useCart() const { mutate } = useCart()

View File

@ -18,7 +18,7 @@ export const handler: SWRHook<
}, },
async fetcher({ input: { cartId }, options, fetch }) { async fetcher({ input: { cartId }, options, fetch }) {
const data = cartId ? await fetch(options) : null const data = cartId ? await fetch(options) : null
return data && normalizeCart(data) return data // && normalizeCart(data)
}, },
useHook: ({ useData }) => (input) => { useHook: ({ useData }) => (input) => {
const response = useData({ const response = useData({

View File

@ -41,7 +41,8 @@ export const handler = {
...options, ...options,
body: { itemId }, body: { itemId },
}) })
return normalizeCart(data) // return normalizeCart(data)
return data
}, },
useHook: ({ useHook: ({
fetch, fetch,

View File

@ -55,7 +55,8 @@ export const handler = {
body: { itemId, item }, body: { itemId, item },
}) })
return normalizeCart(data) // return normalizeCart(data)
return data
}, },
useHook: ({ useHook: ({
fetch, fetch,

View File

@ -1,6 +1,7 @@
{ {
"provider": "aquilacms", "provider": "aquilacms",
"features": { "features": {
"wishlist": false "wishlist": false,
"customCheckout": true
} }
} }

View File

@ -1,8 +1,13 @@
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
import { AquilacmsConfig, getConfig } from '../api' import { AquilacmsConfig, getConfig } from '../api'
import { definitions } from '../api/definitions/store-content' import type { AquilacmsStatic } from '../types'
export type Page = definitions['page_Full'] export type Page = {
id: string
name: string
url: string
sort_order?: number
body: string
}
export type GetAllPagesResult< export type GetAllPagesResult<
T extends { pages: any[] } = { pages: Page[] } T extends { pages: any[] } = { pages: Page[] }
@ -28,15 +33,42 @@ async function getAllPages({
preview?: boolean preview?: boolean
} = {}): Promise<GetAllPagesResult> { } = {}): Promise<GetAllPagesResult> {
config = getConfig(config) config = getConfig(config)
// RecursivePartial forces the method to check for every prop in the data, which is // const { datas } = await config.storeApiFetch('/v2/categories', {
// required in case there's a custom `url` // method: 'POST',
const { data } = await config.storeApiFetch< // body: JSON.stringify({
RecursivePartial<{ data: Page[] }> // lang: 'en',
>('/v3/content/pages') // PostBody: {
const pages = (data as RecursiveRequired<typeof data>) ?? [] // filter: {
// action: 'page',
// },
// limit: 10,
// page: 1,
// },
// }),
// })
const { datas }: { datas: AquilacmsStatic[] } = await config.storeApiFetch(
'/v2/statics',
{
method: 'POST',
body: JSON.stringify({
lang: 'en',
PostBody: {
limit: 10,
page: 1,
},
}),
}
)
const pages: Page[] = datas.map((s: AquilacmsStatic) => ({
id: `en-US/${s._id}`,
name: s.slug['en'],
url: `/en-US/${s.slug['en']}`,
body: s.content,
}))
return { return {
pages: preview ? pages : pages.filter((p) => p.is_visible), pages,
} }
} }

View File

@ -1,13 +1,11 @@
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
import { AquilacmsConfig, getConfig } from '../api' import { AquilacmsConfig, getConfig } from '../api'
import { definitions } from '../api/definitions/store-content' import { Page } from './get-all-pages'
import type { AquilacmsStatic } from '../types'
export type Page = definitions['page_Full']
export type GetPageResult<T extends { page?: any } = { page?: Page }> = T export type GetPageResult<T extends { page?: any } = { page?: Page }> = T
export type PageVariables = { export type PageVariables = {
id: number id: string
} }
async function getPage(opts: { async function getPage(opts: {
@ -26,7 +24,7 @@ async function getPage<T extends { page?: any }, V = any>(opts: {
async function getPage({ async function getPage({
url, url,
variables, variables: { id },
config, config,
preview, preview,
}: { }: {
@ -36,18 +34,42 @@ async function getPage({
preview?: boolean preview?: boolean
}): Promise<GetPageResult> { }): Promise<GetPageResult> {
config = getConfig(config) config = getConfig(config)
// RecursivePartial forces the method to check for every prop in the data, which is const [locale, _id] = id.split('/')
// required in case there's a custom `url` const lang = locale.split('-')[0]
const { data } = await config.storeApiFetch< // const page: any = await config.storeApiFetch('/v2/category', {
RecursivePartial<{ data: Page[] }> // method: 'POST',
>(url || `/v3/content/pages?id=${variables.id}&include=body`) // body: JSON.stringify({
const firstPage = data?.[0] // lang,
const page = firstPage as RecursiveRequired<typeof firstPage> // PostBody: {
// filter: {
// action: 'page',
// _id,
// },
// limit: 10,
// page: 1,
// },
// }),
// })
const staticPage: AquilacmsStatic = await config.storeApiFetch('/v2/static', {
method: 'POST',
body: JSON.stringify({
lang,
PostBody: {
filter: {
_id,
},
},
}),
})
if (preview || page?.is_visible) { return {
return { page } page: {
id: `${locale}/${staticPage._id}`,
name: staticPage.slug[lang],
url: `/${locale}/${staticPage.slug[lang]}`,
body: staticPage?.content ?? '',
},
} }
return {}
} }
export default getPage export default getPage

View File

@ -1,105 +1,56 @@
import type { GetSiteInfoQuery, GetSiteInfoQueryVariables } from '../schema'
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
import filterEdges from '../api/utils/filter-edges'
import { AquilacmsConfig, getConfig } from '../api' import { AquilacmsConfig, getConfig } from '../api'
import { categoryTreeItemFragment } from '../api/fragments/category-tree'
// Get 3 levels of categories export type GetSiteInfoResult = { categories: any[]; brands: any[] }
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?: { async function getSiteInfo(opts?: {
variables?: GetSiteInfoQueryVariables variables?: any
config?: AquilacmsConfig config?: AquilacmsConfig
preview?: boolean preview?: boolean
}): Promise<GetSiteInfoResult> }): Promise<GetSiteInfoResult>
async function getSiteInfo< async function getSiteInfo<T extends GetSiteInfoResult, V = any>(opts: {
T extends { categories: any[]; brands: any[] },
V = any
>(opts: {
query: string
variables?: V variables?: V
config?: AquilacmsConfig config?: AquilacmsConfig
preview?: boolean preview?: boolean
}): Promise<GetSiteInfoResult<T>> }): Promise<GetSiteInfoResult>
async function getSiteInfo({ async function getSiteInfo({
query = getSiteInfoQuery,
variables, variables,
config, config,
}: { }: {
query?: string query?: string
variables?: GetSiteInfoQueryVariables variables?: any
config?: AquilacmsConfig config?: AquilacmsConfig
preview?: boolean preview?: boolean
} = {}): Promise<GetSiteInfoResult> { } = {}): Promise<GetSiteInfoResult> {
// TODO:
config = getConfig(config) config = getConfig(config)
// RecursivePartial forces the method to check for every prop in the data, which is const { datas } = await config.storeApiFetch('/v2/categories', {
// required in case there's a custom `query` method: 'POST',
const { data } = await config.fetch<RecursivePartial<GetSiteInfoQuery>>( body: JSON.stringify({
query, lang: 'en',
{ variables } PostBody: {
) filter: {
const categories = data.site?.categoryTree action: 'catalog',
const brands = data.site?.brands?.edges },
limit: 10,
page: 1,
structure: {
code: 1,
slug: 1,
name: 1,
},
},
}),
})
return { return {
categories: (categories as RecursiveRequired<typeof categories>) ?? [], categories: datas.map((c: any) => ({
brands: filterEdges(brands as RecursiveRequired<typeof brands>), path: c.slug['en'],
entityId: c._id,
name: c.name,
})),
brands: [],
} }
} }

View File

@ -1,13 +1,5 @@
import { GetCustomerIdQuery } from '../schema'
import { AquilacmsConfig, getConfig } from '../api' import { AquilacmsConfig, getConfig } from '../api'
import { AquilacmsUser } from '../types'
export const getCustomerIdQuery = /* GraphQL */ `
query getCustomerId {
customer {
entityId
}
}
`
async function getCustomerId({ async function getCustomerId({
customerToken, customerToken,
@ -15,20 +7,19 @@ async function getCustomerId({
}: { }: {
customerToken: string customerToken: string
config?: AquilacmsConfig config?: AquilacmsConfig
}): Promise<number | undefined> { }): Promise<string | undefined> {
config = getConfig(config) config = getConfig(config)
const data: AquilacmsUser = await config.storeApiFetch('/v2/user', {
const { data } = await config.fetch<GetCustomerIdQuery>( method: 'POST',
getCustomerIdQuery, body: JSON.stringify({
undefined, PostBody: {},
{ }),
headers: { headers: {
cookie: `${config.customerCookie}=${customerToken}`, authorization: customerToken,
}, },
} })
)
return data?.customer?.entityId return data._id
} }
export default getCustomerId export default getCustomerId

View File

@ -1,88 +0,0 @@
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
import { definitions } from '../api/definitions/wishlist'
import { AquilacmsConfig, 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?: AquilacmsConfig
includeProducts?: boolean
}): Promise<GetCustomerWishlistResult>
async function getCustomerWishlist<
T extends { wishlist?: any },
V = any
>(opts: {
url: string
variables: V
config?: AquilacmsConfig
includeProducts?: boolean
}): Promise<GetCustomerWishlistResult<T>>
async function getCustomerWishlist({
config,
variables,
includeProducts,
}: {
url?: string
variables: GetCustomerWishlistVariables
config?: AquilacmsConfig
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

View File

@ -1,13 +0,0 @@
import update, { Context } from 'immutability-helper'
const c = new Context()
c.extend('$auto', function (value, object) {
return object ? c.update(object, value) : c.update({}, value)
})
c.extend('$autoArray', function (value, object) {
return object ? c.update(object, value) : c.update([], value)
})
export default c.update

View File

@ -1,113 +1,141 @@
import type { Product } from '@commerce/types' import type { Product, ProductOption } from '@commerce/types'
import type { Cart, AquilacmsCart, LineItem } from '../types' import { getConfig } from '../api'
import update from './immutability' import type {
Cart,
function normalizeProductOption(productOption: any) { AquilacmsCart,
const { LineItem,
node: { AquilacmsItem,
entityId, AquilacmsProduct,
values: { edges }, AquilacmsProductImage,
...rest AquilacmsUser,
}, User,
} = productOption AquilacmsProductAttribute,
} from '../types'
function normalizeProductOption(
productOption: AquilacmsProductAttribute
): ProductOption {
if (productOption.type === 'color') {
return { return {
id: entityId, id: productOption.id,
values: edges?.map(({ node }: any) => node), displayName: productOption.name,
...rest, values: [
{
label: productOption.value,
hexColors: [productOption.value],
},
],
}
} else if (productOption.type === 'multiselect') {
return {
id: productOption.id,
displayName: productOption.name,
values: productOption.values.map((opt) => ({ label: opt })),
}
} else {
return {
id: productOption.id,
displayName: productOption.name,
values: [],
}
} }
} }
export function normalizeProduct(productNode: any): Product { export function normalizeProductImage(image: AquilacmsProductImage) {
const { return {
entityId: id, url: `${process.env.AQUILACMS_URL}/${image.url}`,
productOptions, alt: image.alt,
prices, }
path, }
id: _,
options: _0,
} = productNode
return update(productNode, { export function normalizeProduct(productNode: AquilacmsProduct): Product {
id: { $set: String(id) }, return {
images: { id: productNode._id,
$apply: ({ edges }: any) => name: productNode.name,
edges?.map(({ node: { urlOriginal, altText, ...rest } }: any) => ({ description: productNode.description1?.text ?? '',
url: urlOriginal, slug: productNode.slug['en'],
alt: altText, images: productNode.images.map(normalizeProductImage),
...rest, variants: [
})), {
}, id: productNode._id,
variants: { options:
$apply: ({ edges }: any) => [] ??
edges?.map(({ node: { entityId, productOptions, ...rest } }: any) => ({ productNode.attributes
id: entityId, .filter(
options: productOptions?.edges (attr) => ['color', 'multiselect'].indexOf(attr.type) !== -1
? productOptions.edges.map(normalizeProductOption) )
: [], .map(normalizeProductOption),
...rest,
})),
},
options: {
$set: productOptions.edges
? productOptions?.edges.map(normalizeProductOption)
: [],
},
brand: {
$apply: (brand: any) => (brand?.entityId ? brand?.entityId : null),
},
slug: {
$set: path?.replace(/^\/+|\/+$/g, ''),
}, },
],
price: { price: {
$set: { currencyCode: 'EUR',
value: prices?.price.value, value: productNode.price.ati.special ?? productNode.price.ati.normal,
currencyCode: prices?.price.currencyCode,
}, },
}, options: [] ?? productNode.attributes.map(normalizeProductOption),
$unset: ['entityId'], }
})
} }
export function normalizeCart(data: AquilacmsCart): Cart { export function normalizeCart(data: AquilacmsCart): Cart {
const lineItems = data.items.map(normalizeLineItem)
// TODO: not good, need to change
const price = lineItems.reduce((total, item) => total + item.variant.price, 0)
return { return {
id: data.id, id: data._id,
customerId: String(data.customer_id), customerId: data.customer?.id,
email: data.email, email: data.customer?.email,
createdAt: data.created_time, createdAt: data.createdAt,
currency: data.currency, currency: { code: 'EUR' },
taxesIncluded: data.tax_included, taxesIncluded: true,
lineItems: data.line_items.physical_items.map(normalizeLineItem), lineItems,
lineItemsSubtotalPrice: data.base_amount, lineItemsSubtotalPrice: price,
subtotalPrice: data.base_amount + data.discount_amount, subtotalPrice: data.priceSubTotal.ati,
totalPrice: data.cart_amount, totalPrice: data.priceTotal.ati,
discounts: data.discounts?.map((discount) => ({ discounts: [],
value: discount.discounted_amount,
})),
} }
} }
function normalizeLineItem(item: any): LineItem { function normalizeLineItem(item: AquilacmsItem): LineItem {
const image = item.id.images.find((i: any) => i.default)
return { return {
id: item.id, id: item._id,
variantId: String(item.variant_id), variantId: item.id._id,
productId: String(item.product_id), productId: item.id._id,
name: item.name, name: item.name,
quantity: item.quantity, quantity: item.quantity,
variant: { variant: {
id: String(item.variant_id), id: item.id._id,
sku: item.sku, sku: item.code,
name: item.name, name: item.name,
image: { image: {
url: item.image_url, url: `${process.env.AQUILACMS_URL}/${image?.url}`,
altText: image?.alt,
}, },
requiresShipping: item.is_require_shipping, requiresShipping: true,
price: item.sale_price, price: item.price?.special?.ati ?? item.price.unit.ati,
listPrice: item.list_price, listPrice: item.price?.special?.ati ?? item.price.unit.ati,
},
path: `${item.id.slug['en']}`,
discounts: [],
}
}
export function normalizeUser(data: AquilacmsUser): User {
return {
entityId: data._id,
firstName: data.firstname,
lastName: data.lastname,
email: data.email,
company: data?.company?.name,
customerGroupId: '',
notes: '',
phone:
data?.addresses?.[data?.delivery_address].phone ||
data?.addresses?.[data?.delivery_address].phone_mobile,
addressCount: data?.addresses?.length,
attributeCount: 0,
storeCredit: {
value: 0,
currencyCode: 'EUR',
}, },
path: item.url.split('/')[3],
discounts: item.discounts.map((discount: any) => ({
value: discount.discounted_amount,
})),
} }
} }

View File

@ -3,6 +3,6 @@ const commerce = require('./commerce.config.json')
module.exports = { module.exports = {
commerce, commerce,
images: { images: {
domains: ['cdn11.bigcommerce.com'], domains: ['recdem.hosting-ns.com', '192.168.1.138'],
}, },
} }

View File

@ -0,0 +1,14 @@
import { AquilacmsConfig } from '..'
import { getConfig } from '../api'
async function getAllOrders({
config,
}: {
config?: AquilacmsConfig
}): Promise<{ orders: any[] }> {
config = getConfig(config)
const data: any = []
return { orders: data }
}
export default getAllOrders

View File

@ -1,71 +1,90 @@
import type {
GetAllProductPathsQuery,
GetAllProductPathsQueryVariables,
} from '../schema'
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
import filterEdges from '../api/utils/filter-edges'
import { AquilacmsConfig, getConfig } from '../api' import { AquilacmsConfig, getConfig } from '../api'
export const getAllProductPathsQuery = /* GraphQL */ ` export type GetAllProductsResultAquila = {
query getAllProductPaths($first: Int = 100) { datas: any[]
site { count: number
products(first: $first) { min: {
edges { et: number
node { ati: number
path }
max: {
et: number
ati: number
}
specialPriceMin: {
et: number
ati: number
}
specialPriceMax: {
et: number
ati: number
} }
} }
}
}
}
`
export type ProductPath = NonNullable< type ProductPath = {
NonNullable<GetAllProductPathsQuery['site']['products']['edges']>[0] node: {
> path: string
}
}
export type ProductPaths = ProductPath[] type ProductPaths = ProductPath[]
export type { GetAllProductPathsQueryVariables } type GetAllProductPathsResult<
export type GetAllProductPathsResult<
T extends { products: any[] } = { products: ProductPaths } T extends { products: any[] } = { products: ProductPaths }
> = T > = T
async function getAllProductPaths(opts?: {
variables?: GetAllProductPathsQueryVariables
config?: AquilacmsConfig
}): Promise<GetAllProductPathsResult>
async function getAllProductPaths<
T extends { products: any[] },
V = any
>(opts: {
query: string
variables?: V
config?: AquilacmsConfig
}): Promise<GetAllProductPathsResult<T>>
async function getAllProductPaths({ async function getAllProductPaths({
query = getAllProductPathsQuery,
variables, variables,
config, config,
}: { }: {
query?: string variables?: {
variables?: GetAllProductPathsQueryVariables locales?: string[] | undefined
}
config?: AquilacmsConfig config?: AquilacmsConfig
} = {}): Promise<GetAllProductPathsResult> { } = {}): Promise<GetAllProductPathsResult> {
config = getConfig(config) config = getConfig(config)
// RecursivePartial forces the method to check for every prop in the data, which is let data: any = {
// required in case there's a custom `query` paths: [],
const { data } = await config.fetch< products: [],
RecursivePartial<GetAllProductPathsQuery>
>(query, { variables })
const products = data.site?.products?.edges
return {
products: filterEdges(products as RecursiveRequired<typeof products>),
} }
try {
const result: GetAllProductsResultAquila = await config.storeApiFetch(
'/v2/products',
{
method: 'POST',
body: JSON.stringify({
PostBody: {
structure: {
translation: 1,
},
limit: 200,
page: 1,
},
}),
}
)
// if (variables?.locales) {
// for (const locale of variables?.locales) {
// for (const p of result.datas) {
// const loc = locale.split('-')[0]
// if (p.slug[loc]) data.paths.push(`/${locale}/product/${p.slug[loc]}/`)
// }
// }
// } else {
return {
products: result.datas.map((p) => {
return {
node: {
path: `/${p.slug['en']}/`,
},
}
}),
}
// }
} catch (err) {
console.error(err)
}
return data
} }
export default getAllProductPaths export default getAllProductPaths

View File

@ -1,57 +1,7 @@
import type {
GetAllProductsQuery,
GetAllProductsQueryVariables,
} from '../schema'
import type { Product } from '@commerce/types' 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 { AquilacmsConfig, getConfig } from '../api' import { AquilacmsConfig, getConfig } from '../api'
import { normalizeProduct } from '../lib/normalize' 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 = [ const FIELDS = [
'products', 'products',
'featuredProducts', 'featuredProducts',
@ -65,29 +15,12 @@ export type ProductTypes =
| 'bestSellingProducts' | 'bestSellingProducts'
| 'newestProducts' | 'newestProducts'
export type ProductVariables = { field?: ProductTypes } & Omit< export type ProductVariables = { field?: ProductTypes; first?: number } & {
GetAllProductsQueryVariables, locale?: string
ProductTypes | 'hasLocale' hasLocale?: boolean
> }
async function getAllProducts(opts?: {
variables?: ProductVariables
config?: AquilacmsConfig
preview?: boolean
}): Promise<{ products: Product[] }>
async function getAllProducts<
T extends Record<keyof GetAllProductsResult, any[]>,
V = any
>(opts: {
query: string
variables?: V
config?: AquilacmsConfig
preview?: boolean
}): Promise<GetAllProductsResult<T>>
async function getAllProducts({ async function getAllProducts({
query = getAllProductsQuery,
variables: { field = 'products', ...vars } = {}, variables: { field = 'products', ...vars } = {},
config, config,
}: { }: {
@ -95,12 +28,11 @@ async function getAllProducts({
variables?: ProductVariables variables?: ProductVariables
config?: AquilacmsConfig config?: AquilacmsConfig
preview?: boolean preview?: boolean
// TODO: fix the product type here
} = {}): Promise<{ products: Product[] | any[] }> { } = {}): Promise<{ products: Product[] | any[] }> {
config = getConfig(config) config = getConfig(config)
const locale = vars.locale || config.locale const locale = (vars.locale || config.locale)?.split('-')[0]
const variables: GetAllProductsQueryVariables = { const variables = {
...vars, ...vars,
locale, locale,
hasLocale: !!locale, hasLocale: !!locale,
@ -112,24 +44,31 @@ async function getAllProducts({
) )
} }
variables[field] = true
// 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<GetAllProductsQuery>>( let { datas } = await config.storeApiFetch('/v2/products', {
query, method: 'POST',
{ variables } body: JSON.stringify({
) lang: locale,
const edges = data.site?.[field]?.edges PostBody: {
const products = filterEdges(edges as RecursiveRequired<typeof edges>) structure: {
code: 1,
if (locale && config.applyLocale) { id: 1,
products.forEach((product: RecursivePartial<ProductEdge>) => { translation: 1,
if (product.node) setProductLocaleMeta(product.node) attributes: 1,
pictos: 1,
canonical: 1,
images: 1,
},
page: 1,
limit: variables.first,
},
}),
}) })
}
return { products: products.map(({ node }) => normalizeProduct(node as any)) } const products = datas.map(normalizeProduct)
return { products }
} }
export default getAllProducts export default getAllProducts

View File

@ -1,92 +1,18 @@
import type { GetProductQuery, GetProductQueryVariables } from '../schema'
import setProductLocaleMeta from '../api/utils/set-product-locale-meta'
import { productInfoFragment } from '../api/fragments/product'
import { AquilacmsConfig, getConfig } from '../api' import { AquilacmsConfig, getConfig } from '../api'
import { normalizeProduct } from '../lib/normalize' import { normalizeProduct } from '../lib/normalize'
import type { Product } from '@commerce/types' import type { Product } from '@commerce/types'
import { AquilacmsProduct } from '../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 } & ( export type ProductVariables = { locale?: string } & (
| { path: string; slug?: never } | { path: string; slug?: never }
| { path?: never; slug: string } | { path?: never; slug: string }
) )
async function getProduct(opts: { export type GetProductResult<
variables: ProductVariables T extends { product?: any } = { product?: Product }
config?: AquilacmsConfig > = T
preview?: boolean
}): Promise<GetProductResult>
async function getProduct<T extends { product?: any }, V = any>(opts: {
query: string
variables: V
config?: AquilacmsConfig
preview?: boolean
}): Promise<GetProductResult<T>>
async function getProduct({ async function getProduct({
query = getProductQuery,
variables: { slug, ...vars }, variables: { slug, ...vars },
config, config,
}: { }: {
@ -94,28 +20,32 @@ async function getProduct({
variables: ProductVariables variables: ProductVariables
config?: AquilacmsConfig config?: AquilacmsConfig
preview?: boolean preview?: boolean
}): Promise<Product | {} | any> { }): Promise<Product | any> {
config = getConfig(config) config = getConfig(config)
const locale = (vars.locale || config.locale)?.split('-')[0]
const locale = vars.locale || config.locale const data: AquilacmsProduct = await config.storeApiFetch('/v2/product', {
const variables: GetProductQueryVariables = { method: 'POST',
...vars, body: JSON.stringify({
locale, lang: locale,
hasLocale: !!locale, countviews: true,
path: slug ? `/${slug}/` : vars.path!, withFilters: false,
} PostBody: {
const { data } = await config.fetch<GetProductQuery>(query, { variables }) filter: {
const product = data.site?.route?.node [`translation.${locale}.slug`]: slug,
},
if (product?.__typename === 'Product') { structure: {
if (locale && config.applyLocale) { code: 1,
setProductLocaleMeta(product) id: 1,
} translation: 1,
attributes: 1,
return { product: normalizeProduct(product as any) } pictos: 1,
} canonical: 1,
images: 1,
return {} },
},
}),
})
return { product: normalizeProduct(data) }
} }
export default getProduct export default getProduct

View File

@ -25,8 +25,7 @@ export const handler: SWRHook<
const url = new URL(options.url!, 'http://a') const url = new URL(options.url!, 'http://a')
if (search) url.searchParams.set('search', search) if (search) url.searchParams.set('search', search)
if (Number.isInteger(categoryId)) if (categoryId) url.searchParams.set('category', String(categoryId))
url.searchParams.set('category', String(categoryId))
if (Number.isInteger(brandId)) if (Number.isInteger(brandId))
url.searchParams.set('brand', String(brandId)) url.searchParams.set('brand', String(brandId))
if (sort) url.searchParams.set('sort', sort) if (sort) url.searchParams.set('sort', sort)

View File

@ -3,10 +3,6 @@ import { handler as useAddItem } from './cart/use-add-item'
import { handler as useUpdateItem } from './cart/use-update-item' import { handler as useUpdateItem } from './cart/use-update-item'
import { handler as useRemoveItem } from './cart/use-remove-item' import { handler as useRemoveItem } from './cart/use-remove-item'
import { handler as useWishlist } from './wishlist/use-wishlist'
import { handler as useWishlistAddItem } from './wishlist/use-add-item'
import { handler as useWishlistRemoveItem } from './wishlist/use-remove-item'
import { handler as useCustomer } from './customer/use-customer' import { handler as useCustomer } from './customer/use-customer'
import { handler as useSearch } from './product/use-search' import { handler as useSearch } from './product/use-search'
@ -15,20 +11,16 @@ import { handler as useLogout } from './auth/use-logout'
import { handler as useSignup } from './auth/use-signup' import { handler as useSignup } from './auth/use-signup'
import fetcher from './fetcher' import fetcher from './fetcher'
import { Provider } from '../commerce'
export const aquilacmsProvider = { export const aquilacmsProvider = {
locale: 'en-us', locale: 'en-us',
cartCookie: 'aquilacms_cartId', cartCookie: 'aquilacms_cartId',
fetcher, fetcher,
cart: { useCart, useAddItem, useUpdateItem, useRemoveItem }, cart: { useCart, useAddItem, useUpdateItem, useRemoveItem },
wishlist: {
useWishlist,
useAddItem: useWishlistAddItem,
useRemoveItem: useWishlistRemoveItem,
},
customer: { useCustomer }, customer: { useCustomer },
products: { useSearch }, products: { useSearch },
auth: { useLogin, useLogout, useSignup }, auth: { useLogin, useLogout, useSignup },
} } as Provider
export type AquilacmsProvider = typeof aquilacmsProvider export type AquilacmsProvider = typeof aquilacmsProvider

File diff suppressed because it is too large Load Diff

View File

@ -1,49 +0,0 @@
/**
* Generates definitions for REST API endpoints that are being
* used by ../api using https://github.com/drwpow/swagger-to-ts
*/
const { readFileSync, promises } = require('fs')
const path = require('path')
const fetch = require('node-fetch')
const swaggerToTS = require('@manifoldco/swagger-to-ts').default
async function getSchema(filename) {
const url = `https://next-api.stoplight.io/projects/8433/files/${filename}`
const res = await fetch(url)
if (!res.ok) {
throw new Error(`Request failed with ${res.status}: ${res.statusText}`)
}
return res.json()
}
const schemas = Object.entries({
'../api/definitions/catalog.ts':
'BigCommerce_Catalog_API.oas2.yml?ref=version%2F20.930',
'../api/definitions/store-content.ts':
'BigCommerce_Store_Content_API.oas2.yml?ref=version%2F20.930',
'../api/definitions/wishlist.ts':
'BigCommerce_Wishlist_API.oas2.yml?ref=version%2F20.930',
// swagger-to-ts is not working for the schema of the cart API
// '../api/definitions/cart.ts':
// 'BigCommerce_Server_to_Server_Cart_API.oas2.yml',
})
async function writeDefinitions() {
const ops = schemas.map(async ([dest, filename]) => {
const destination = path.join(__dirname, dest)
const schema = await getSchema(filename)
const definition = swaggerToTS(schema.content, {
prettierConfig: 'package.json',
})
await promises.writeFile(destination, definition)
console.log(`✔️ Added definitions for: ${dest}`)
})
await Promise.all(ops)
}
writeDefinitions()

View File

@ -1,24 +1,361 @@
import * as Core from '@commerce/types' import * as Core from '@commerce/types'
export type AquilacmsCart = { export type AquilacmsTranslation = {
id: string [index: string]: any
parent_id?: string
customer_id: number
email: string
currency: { code: string }
tax_included: boolean
base_amount: number
discount_amount: number
cart_amount: number
line_items: {
custom_items: any[]
digital_items: any[]
gift_certificates: any[]
physical_items: any[]
} }
created_time: string
discounts?: { id: number; discounted_amount: number }[] export enum AquilacmsCartStatus {
// TODO: add missing fields IN_PROGRESS = 'IN_PROGRESS',
EXPIRING = 'EXPIRING',
EXPIRED = 'EXPIRED',
}
export enum AquilacmsCartOrderReceiptMethod {
DELIVERY = 'delivery',
WITHDRAWAL = 'withdrawal',
}
export enum AquilacmsCartDiscountType {
PERCENT = 'PERCENT',
PRICE = 'PRICE',
FREE_DELIVERY = 'FREE_DELIVERY',
}
export enum supplierCode {
simple = 'simple',
bundle = 'bundle',
virtual = 'virtual',
}
export enum AquilacmsUserCivility {
MAN = 0,
WOMAN = 1,
}
export enum AquilacmsItemStatus {
PROCESSING = 'PROCESSING',
DELIVERY_PROGRESS = 'DELIVERY_PROGRESS',
DELIVERY_PARTIAL_PROGRESS = 'DELIVERY_PARTIAL_PROGRESS',
RETURNED = 'RETURNED',
RETURNED_PARTIAL = 'RETURNED_PARTIAL',
}
export type AquilacmsItem = {
_id: string
id: AquilacmsProduct
status: AquilacmsItemStatus
name: string
code: string
image: string
parent: string
children: string[]
quantity: number
weight: number
noRecalculatePrice: boolean
price: {
vat: {
rate: number
}
total?: {
ati: number
}
unit: {
et: number
ati: number
vat?: number
}
special: {
et: number
ati: number
vat?: number
}
}
atts: any[]
typeDisplay?: string
}
export type AquilacmsAddress = {
firstname: string
lastname: string
companyName: string
phone: string
phone_mobile: string
line1: string
line2: string
zipcode: string
city: string
isoCountryCode: string
country: string
complementaryInfo: string
civility: AquilacmsUserCivility
}
export type AquilacmsCartPromo = {
promoId: string
promoCodeId: string
discountATI: number
discountET: number
name: string
description: string
code: string
gifts: AquilacmsItem[]
productsId: {
productId: string
discountATI: number
discountET: number
basePriceET: number
basePriceATI: number
}[]
}
export type AquilacmsCartCustomer = {
id: string
email: string
phone: string
}
export type AquilacmsCartDiscount = {
code?: string
type?: AquilacmsCartDiscountType
value?: number
description?: string
minimumATI?: number
onAllSite?: boolean
openDate?: string
closeDate?: string
priceATI: number
}
export type AquilacmsCart = {
_id: string
updated: string
paidTax: boolean
status: AquilacmsCartStatus
promos?: AquilacmsCartPromo[]
customer?: AquilacmsCartCustomer
addresses?: {
delivery: AquilacmsAddress
billing: AquilacmsAddress
}
comment?: string
items: AquilacmsItem[]
discount?: AquilacmsCartDiscount[]
delivery?: {
method?: string
value: {
ati: number
et: number
vat: number
}
freePriceLimit?: number
code?: string
name?: string
url?: string
date?: string
dateDelivery?: {
delayDelivery?: number
unitDelivery?: string
delayPreparation?: number
unitPreparation?: string
}
}
priceSubTotal: {
et: number
ati: number
}
priceTotal: {
et: number
ati: number
}
orderReceipt?: {
method: AquilacmsCartOrderReceiptMethod
date?: string
}
createdAt: string
updatedAt: string
}
export type AquilacmsProductAttribute = {
id: string
code: string
values: string[]
value: string
param: string
type: string
position: number
visible: boolean
name: string
}
export type AquilacmsProductImage = {
url: string
name: string
title: string
alt: string
position: number
modificationDate: string
default: boolean
extension: string
}
export type AquilacmsProductPicto = {
code: string
image: string
title: string
location: string
pictoId: string
}
export type AquilacmsProductReviewsQuestion = {
translation: AquilacmsTranslation
idQuestion: string
average: number
}
export type AquilacmsProductReviewsDataQuestion = {
question: string
idQuestion: string
rate: number
}
export type AquilacmsProductReviewsData = {
id_review: string
name: string
id_client: string
ip_client: string
review_date: string
review: string
lang: string
rate: number
order_ref: string
title: string
visible: boolean
verify: boolean
questions: AquilacmsProductReviewsDataQuestion[]
stats: {
views: number
}
}
export type AquilacmsProduct = {
_id: string
code: string
trademark: number
supplier_ref: string
supplier_code: supplierCode
active: boolean
_visible: boolean
universe: string
family: string
subfamily: string
component_template: string
weight: number
price: {
purchase: number
tax: number
et: { normal: number; special: number }
ati: { normal: number; special: number }
priceSort: {
et: number
ati: number
}
}
presentInLastImport: boolean
specific: {
custom_text1: string
custom_text2: string
custom_text3: string
custom_supplier_code: string
custom_traitement: string
custom_code_fabrication: string
}
associated_prds: string[]
set_attributes: string
attributes: AquilacmsProductAttribute[]
images: AquilacmsProductImage[]
code_ean: string
is_new: boolean
translation: AquilacmsTranslation
pictos: AquilacmsProductPicto[]
reviews: {
average: number
reviews_nb: number
questions: AquilacmsProductReviewsQuestion[]
datas: AquilacmsProductReviewsData[]
}
createdAt: string
updatedAt: string
slug: {
[index: string]: string
}
name: string
description1?: {
title: string
text: string
}
description2?: {
title: string
text: string
}
canonical: string
}
export type AquilacmsUserAttribute = {
id: string
code: string
values: string
visible: boolean
param: string
type: string
translation: AquilacmsTranslation
position: number
}
export type AquilacmsUser = {
_id: string
email: string
password: string
code: string
civility: AquilacmsUserCivility
firstname: string
lastname: string
fullname: string
phone: string
phone_mobile: string
company: {
name: string
siret: string
intracom: string
address: string
postal_code: string
town: string
country: string
contact: {
first_name: string
last_name: string
email: string
phone: string
}
}
status: string
delivery_address: number
billing_address: number
addresses: AquilacmsAddress[]
isAdmin: boolean
price: string
taxDisplay: boolean
isActive: boolean
isActiveAccount: boolean
activateAccountToken: string
resetPassToken: string
birthDate: string
accessList: string[]
type: string
preferredLanguage: string
set_attributes: string
attributes: AquilacmsUserAttribute[]
createdAt: string
updatedAt: string
} }
export type Cart = Core.Cart & { export type Cart = Core.Cart & {
@ -54,3 +391,46 @@ export type UpdateCartItemHandlerBody = Core.UpdateCartItemHandlerBody<CartItemB
export type RemoveCartItemBody = Core.RemoveCartItemBody export type RemoveCartItemBody = Core.RemoveCartItemBody
export type RemoveCartItemHandlerBody = Core.RemoveCartItemHandlerBody export type RemoveCartItemHandlerBody = Core.RemoveCartItemHandlerBody
export type User = {
entityId: string
firstName: string
lastName: string
email: string
company?: string
customerGroupId: string
notes: string
phone?: string
addressCount?: number
attributeCount: number
storeCredit: {
value: number
currencyCode: string
}
}
type AquilacmsPage = {
action: string
_id: string
code: string
slug: {
[index: string]: string
}
name: string
metaDescription: string
pageSlug: string
}
export type AquilacmsStatic = {
_id: string
active: boolean
group: string
type: string
code: string
content: string
metaDesc: string
slug: {
[index: string]: string
}
name: string
}

View File

@ -1,3 +0,0 @@
export { default as useAddItem } from './use-add-item'
export { default as useWishlist } from './use-wishlist'
export { default as useRemoveItem } from './use-remove-item'

View File

@ -1,37 +0,0 @@
import { useCallback } from 'react'
import type { MutationHook } from '@commerce/utils/types'
import { CommerceError } from '@commerce/utils/errors'
import useAddItem, { UseAddItem } from '@commerce/wishlist/use-add-item'
import type { ItemBody, AddItemBody } from '../api/wishlist'
import useCustomer from '../customer/use-customer'
import useWishlist from './use-wishlist'
export default useAddItem as UseAddItem<typeof handler>
export const handler: MutationHook<any, {}, ItemBody, AddItemBody> = {
fetchOptions: {
url: '/api/bigcommerce/wishlist',
method: 'POST',
},
useHook: ({ fetch }) => () => {
const { data: customer } = useCustomer()
const { revalidate } = useWishlist()
return useCallback(
async function addItem(item) {
if (!customer) {
// A signed customer is required in order to have a wishlist
throw new CommerceError({
message: 'Signed customer not found',
})
}
// TODO: add validations before doing the fetch
const data = await fetch({ input: { item } })
await revalidate()
return data
},
[fetch, revalidate, customer]
)
},
}

View File

@ -1,44 +0,0 @@
import { useCallback } from 'react'
import type { MutationHook } from '@commerce/utils/types'
import { CommerceError } from '@commerce/utils/errors'
import useRemoveItem, {
RemoveItemInput,
UseRemoveItem,
} from '@commerce/wishlist/use-remove-item'
import type { RemoveItemBody, Wishlist } from '../api/wishlist'
import useCustomer from '../customer/use-customer'
import useWishlist, { UseWishlistInput } from './use-wishlist'
export default useRemoveItem as UseRemoveItem<typeof handler>
export const handler: MutationHook<
Wishlist | null,
{ wishlist?: UseWishlistInput },
RemoveItemInput,
RemoveItemBody
> = {
fetchOptions: {
url: '/api/bigcommerce/wishlist',
method: 'DELETE',
},
useHook: ({ fetch }) => ({ wishlist } = {}) => {
const { data: customer } = useCustomer()
const { revalidate } = useWishlist(wishlist)
return useCallback(
async function removeItem(input) {
if (!customer) {
// A signed customer is required in order to have a wishlist
throw new CommerceError({
message: 'Signed customer not found',
})
}
const data = await fetch({ input: { itemId: String(input.id) } })
await revalidate()
return data
},
[fetch, revalidate, customer]
)
},
}

View File

@ -1,60 +0,0 @@
import { useMemo } from 'react'
import { SWRHook } from '@commerce/utils/types'
import useWishlist, { UseWishlist } from '@commerce/wishlist/use-wishlist'
import type { Wishlist } from '../api/wishlist'
import useCustomer from '../customer/use-customer'
export type UseWishlistInput = { includeProducts?: boolean }
export default useWishlist as UseWishlist<typeof handler>
export const handler: SWRHook<
Wishlist | null,
UseWishlistInput,
{ customerId?: number } & UseWishlistInput,
{ isEmpty?: boolean }
> = {
fetchOptions: {
url: '/api/bigcommerce/wishlist',
method: 'GET',
},
async fetcher({ input: { customerId, includeProducts }, options, fetch }) {
if (!customerId) return null
// Use a dummy base as we only care about the relative path
const url = new URL(options.url!, 'http://a')
if (includeProducts) url.searchParams.set('products', '1')
return fetch({
url: url.pathname + url.search,
method: options.method,
})
},
useHook: ({ useData }) => (input) => {
const { data: customer } = useCustomer()
const response = useData({
input: [
['customerId', customer?.entityId],
['includeProducts', input?.includeProducts],
],
swrOptions: {
revalidateOnFocus: false,
...input?.swrOptions,
},
})
return useMemo(
() =>
Object.create(response, {
isEmpty: {
get() {
return (response.data?.items?.length || 0) <= 0
},
enumerable: true,
},
}),
[response]
)
},
}

View File

@ -172,7 +172,7 @@ export interface Product extends Entity {
sku?: string sku?: string
} }
interface ProductOption extends Entity { export interface ProductOption extends Entity {
displayName: string displayName: string
values: ProductOptionValues[] values: ProductOptionValues[]
} }

View File

@ -34,7 +34,7 @@ module.exports = (nextConfig = {}) => {
config.env = config.env || {} config.env = config.env || {}
Object.entries(config.commerce.features).forEach(([k, v]) => { Object.entries(config.commerce.features).forEach(([k, v]) => {
if (v) config.env[`COMMERCE_${k.toUpperCase()}_ENABLED`] = true if (v) config.env[`COMMERCE_${k.toUpperCase()}_ENABLED`] = v
}) })
return config return config

View File

@ -1,4 +1,4 @@
const commerce = require('./commerce.config.json') const commerce = require('./framework/aquilacms/commerce.config.json')
const withCommerceConfig = require('./framework/commerce/with-config') const withCommerceConfig = require('./framework/commerce/with-config')
const isBC = commerce.provider === 'bigcommerce' const isBC = commerce.provider === 'bigcommerce'
@ -8,18 +8,18 @@ const isAquilacms = commerce.provider === 'aquilacms'
module.exports = withCommerceConfig({ module.exports = withCommerceConfig({
commerce, commerce,
i18n: { i18n: {
locales: ['en-US', 'es'], locales: ['en-US'],
defaultLocale: 'en-US', defaultLocale: 'en-US',
}, },
rewrites() { rewrites() {
return [ return [
(isBC || isShopify) && { (isBC || isShopify || isAquilacms) && {
source: '/checkout', source: '/checkout',
destination: '/api/bigcommerce/checkout', destination: '/api/bigcommerce/checkout',
}, },
// The logout is also an action so this route is not required, but it's also another way // The logout is also an action so this route is not required, but it's also another way
// you can allow a logout! // you can allow a logout!
isBC && { (isBC || isAquilacms) && {
source: '/logout', source: '/logout',
destination: '/api/bigcommerce/customers/logout?redirect_to=/', destination: '/api/bigcommerce/customers/logout?redirect_to=/',
}, },

View File

@ -2,7 +2,10 @@
"name": "nextjs-commerce", "name": "nextjs-commerce",
"version": "1.0.0", "version": "1.0.0",
"scripts": { "scripts": {
"dev": "next dev", "clean": "rm -rf .next",
"predev": "npm run clean",
"dev": "cross-env NODE_OPTIONS='--inspect' next dev",
"prebuild": "npm run clean",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"analyze": "BUNDLE_ANALYZE=both yarn build", "analyze": "BUNDLE_ANALYZE=both yarn build",
@ -27,6 +30,7 @@
"dot-object": "^2.1.4", "dot-object": "^2.1.4",
"email-validator": "^2.0.4", "email-validator": "^2.0.4",
"immutability-helper": "^3.1.1", "immutability-helper": "^3.1.1",
"joi": "^17.4.0",
"js-cookie": "^2.2.1", "js-cookie": "^2.2.1",
"keen-slider": "^5.2.4", "keen-slider": "^5.2.4",
"lodash.debounce": "^4.0.8", "lodash.debounce": "^4.0.8",
@ -63,6 +67,7 @@
"@types/node": "^14.14.16", "@types/node": "^14.14.16",
"@types/react": "^17.0.0", "@types/react": "^17.0.0",
"@types/shopify-buy": "^2.10.5", "@types/shopify-buy": "^2.10.5",
"cross-env": "^7.0.3",
"deepmerge": "^4.2.2", "deepmerge": "^4.2.2",
"graphql": "^15.4.0", "graphql": "^15.4.0",
"husky": "^4.3.8", "husky": "^4.3.8",

View File

@ -1,5 +1,6 @@
import type { import type {
GetStaticPathsContext, GetStaticPathsContext,
GetStaticPathsResult,
GetStaticPropsContext, GetStaticPropsContext,
InferGetStaticPropsType, InferGetStaticPropsType,
} from 'next' } from 'next'
@ -40,7 +41,9 @@ export async function getStaticProps({
} }
} }
export async function getStaticPaths({ locales }: GetStaticPathsContext) { export async function getStaticPaths({
locales,
}: GetStaticPathsContext): Promise<GetStaticPathsResult> {
const { pages } = await getAllPages() const { pages } = await getAllPages()
const [invalidPaths, log] = missingLocaleInPages() const [invalidPaths, log] = missingLocaleInPages()
const paths = pages const paths = pages
@ -53,7 +56,6 @@ export async function getStaticPaths({ locales }: GetStaticPathsContext) {
invalidPaths.push(url) invalidPaths.push(url)
}) })
log() log()
return { return {
paths, paths,
// Fallback shouldn't be enabled here or otherwise this route // Fallback shouldn't be enabled here or otherwise this route

View File

@ -1,3 +1,4 @@
import wishlistApi from '@framework/api/wishlist' export {}
// import wishlistApi from '@framework/api/wishlist'
export default wishlistApi() // export default wishlistApi()

View File

@ -144,7 +144,7 @@ export default function Cart() {
</li> </li>
<li className="flex justify-between py-1"> <li className="flex justify-between py-1">
<span>Estimated Shipping</span> <span>Estimated Shipping</span>
<span className="font-bold tracking-wide">FREE</span> <span>Calculated at checkout</span>
</li> </li>
</ul> </ul>
<div className="flex justify-between border-t border-accents-2 py-3 font-bold mb-10"> <div className="flex justify-between border-t border-accents-2 py-3 font-bold mb-10">

View File

@ -6,7 +6,7 @@ import { defaultPageProps } from '@lib/defaults'
import { getConfig } from '@framework/api' 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'
import getAllPages from '@framework/common/get-all-pages' import getAllPages from '@framework/common/get-all-pages'
export async function getStaticProps({ export async function getStaticProps({
@ -56,6 +56,7 @@ export default function Wishlist() {
data && data &&
// @ts-ignore Shopify - Fix this types // @ts-ignore Shopify - Fix this types
data.items?.map((item) => ( data.items?.map((item) => (
// @ts-ignore
<WishlistCard key={item.id} product={item.product! as any} /> <WishlistCard key={item.id} product={item.product! as any} />
)) ))
)} )}

View File

@ -22,10 +22,17 @@
"@components/*": ["components/*"], "@components/*": ["components/*"],
"@commerce": ["framework/commerce"], "@commerce": ["framework/commerce"],
"@commerce/*": ["framework/commerce/*"], "@commerce/*": ["framework/commerce/*"],
"@framework": ["framework/bigcommerce"], "@framework": ["framework/aquilacms"],
"@framework/*": ["framework/bigcommerce/*"] "@framework/*": ["framework/aquilacms/*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"], "include": ["next-env.d.ts", "**/*.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"],
"exclude": ["node_modules"] "exclude": [
"node_modules/*",
"components/wishlist",
"components/wishlist/WishlistButton",
"components/wishlist/WishlistCard",
"pages/api/bigcommerce/wishlist",
"pages/wishlist"
]
} }

1743
yarn.lock

File diff suppressed because it is too large Load Diff