mirror of
https://github.com/vercel/commerce.git
synced 2025-07-23 04:36:49 +00:00
Monorepo with Turborepo (#651)
* Moved everything * Figuring out how to make imports work * Updated exports * Added missing exports * Added @vercel/commerce-local to `site` * Updated commerce config * Updated exports and commerce config * Updated commerce hoc * Fixed exports in local * Added publish config * Updated imports in site * It's actually working * Don't use debugger in dev for better speeds * Improved DX when editing packages * Set up eslint with husky * Updated prettier config * Added prettier setup to every package * Moved bigcommerce * Moved Bigcommerce to src and package updates * Updated setup of bigcommerce * Moved definitions script * Moved commercejs * Move to src * Fixed types in commercejs * Moved kibocommerce * Moved kibocommerce to src * Added package/tsconfig to kibocommerce * Fixed imports and other things * Moved ordercloud * Moved ordercloud to src * Fixed imports * Added missing prettier files * Moved Saleor * Moved Saleor to src * Fixed imports * Replaced all imports to @commerce * Added prettierignore/rc to all providers * Moved shopify to src * Build shopify in packages * Moved Spree * Moved spree to src * Updated spree * Moved swell * Moved swell to src * Fixed type imports in swell * Moved Vendure to packages * Moved vendure to src * Fixed imports in vendure * Added codegen to saleor * Updated codegen setup for shopify * Added codegen to vendure * Added codegen to kibocommerce * Added all packages to site's deps * Updated codegen setup in bigcommerce * Minor fixes * Updated providers' names in site * Updated packages based on Bel's changes * Updated turbo to latest * Fixed ts complains * Set npm engine in root * New lockfile install * remove engines * Regen lockfile * Switched from npm to yarn * Updated typesVersions in all packages * Moved dep * Updated SWR to the just released 1.2.0 * Removed "isolatedModules" from packages * Updated list of providers and default * Updated swell declaration * Removed next import from kibocommerce * Added COMMERCE_PROVIDER log * Added another log * Updated turbo config * Updated docs * Removed test logs Co-authored-by: Jared Palmer <jared@jaredpalmer.com>
This commit is contained in:
5
packages/swell/.env.template
Normal file
5
packages/swell/.env.template
Normal file
@@ -0,0 +1,5 @@
|
||||
SWELL_STORE_DOMAIN=
|
||||
SWELL_STOREFRONT_ACCESS_TOKEN=
|
||||
|
||||
NEXT_PUBLIC_SWELL_STORE_ID=
|
||||
NEXT_PUBLIC_SWELL_PUBLIC_KEY=
|
2
packages/swell/.prettierignore
Normal file
2
packages/swell/.prettierignore
Normal file
@@ -0,0 +1,2 @@
|
||||
node_modules
|
||||
dist
|
6
packages/swell/.prettierrc
Normal file
6
packages/swell/.prettierrc
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false
|
||||
}
|
74
packages/swell/package.json
Normal file
74
packages/swell/package.json
Normal file
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"name": "@vercel/commerce-swell",
|
||||
"version": "0.0.1",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"build": "rm -fr dist/* && tsc",
|
||||
"dev": "npm run build -- --watch",
|
||||
"prettier-fix": "prettier --write ."
|
||||
},
|
||||
"sideEffects": false,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./dist/index.js",
|
||||
"./*": [
|
||||
"./dist/*.js",
|
||||
"./dist/*/index.js"
|
||||
],
|
||||
"./next.config": "./dist/next.config.cjs"
|
||||
},
|
||||
"typesVersions": {
|
||||
"*": {
|
||||
"*": [
|
||||
"src/*",
|
||||
"src/*/index"
|
||||
],
|
||||
"next.config": [
|
||||
"dist/next.config.d.cts"
|
||||
]
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"schema.d.ts"
|
||||
],
|
||||
"publishConfig": {
|
||||
"typesVersions": {
|
||||
"*": {
|
||||
"*": [
|
||||
"dist/*.d.ts",
|
||||
"dist/*/index.d.ts"
|
||||
],
|
||||
"next.config": [
|
||||
"dist/next.config.d.cts"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@vercel/commerce": "^0.0.1",
|
||||
"@vercel/fetch": "^6.1.1",
|
||||
"swell-js": "^4.0.0-next.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"next": "^12",
|
||||
"react": "^17",
|
||||
"react-dom": "^17"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^17.0.8",
|
||||
"@types/react": "^17.0.38",
|
||||
"lint-staged": "^12.1.7",
|
||||
"next": "^12.0.8",
|
||||
"prettier": "^2.5.1",
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2",
|
||||
"typescript": "^4.5.4"
|
||||
},
|
||||
"lint-staged": {
|
||||
"**/*.{js,jsx,ts,tsx,json}": [
|
||||
"prettier --write",
|
||||
"git add"
|
||||
]
|
||||
}
|
||||
}
|
5002
packages/swell/schema.d.ts
vendored
Normal file
5002
packages/swell/schema.d.ts
vendored
Normal file
File diff suppressed because it is too large
Load Diff
9631
packages/swell/schema.graphql
Normal file
9631
packages/swell/schema.graphql
Normal file
File diff suppressed because it is too large
Load Diff
1
packages/swell/src/api/cart/index.ts
Normal file
1
packages/swell/src/api/cart/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function () {}
|
1
packages/swell/src/api/catalog/index.ts
Normal file
1
packages/swell/src/api/catalog/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function () {}
|
1
packages/swell/src/api/catalog/products.ts
Normal file
1
packages/swell/src/api/catalog/products.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function () {}
|
1
packages/swell/src/api/customer.ts
Normal file
1
packages/swell/src/api/customer.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function () {}
|
1
packages/swell/src/api/customers/index.ts
Normal file
1
packages/swell/src/api/customers/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function () {}
|
1
packages/swell/src/api/customers/logout.ts
Normal file
1
packages/swell/src/api/customers/logout.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function () {}
|
1
packages/swell/src/api/customers/signup.ts
Normal file
1
packages/swell/src/api/customers/signup.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function () {}
|
1
packages/swell/src/api/endpoints/cart.ts
Normal file
1
packages/swell/src/api/endpoints/cart.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function (_commerce: any) {}
|
1
packages/swell/src/api/endpoints/catalog/products.ts
Normal file
1
packages/swell/src/api/endpoints/catalog/products.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function (_commerce: any) {}
|
30
packages/swell/src/api/endpoints/checkout/index.ts
Normal file
30
packages/swell/src/api/endpoints/checkout/index.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { CommerceAPI, createEndpoint, GetAPISchema } from '@vercel/commerce/api'
|
||||
import { CheckoutSchema } from '@vercel/commerce/types/checkout'
|
||||
import { SWELL_CHECKOUT_URL_COOKIE } from '../../../const'
|
||||
import checkoutEndpoint from '@vercel/commerce/api/endpoints/checkout'
|
||||
|
||||
const getCheckout: CheckoutEndpoint['handlers']['getCheckout'] = async ({
|
||||
req,
|
||||
res,
|
||||
config,
|
||||
}) => {
|
||||
const { cookies } = req
|
||||
const checkoutUrl = cookies[SWELL_CHECKOUT_URL_COOKIE]
|
||||
|
||||
if (checkoutUrl) {
|
||||
res.redirect(checkoutUrl)
|
||||
} else {
|
||||
res.redirect('/cart')
|
||||
}
|
||||
}
|
||||
export const handlers: CheckoutEndpoint['handlers'] = { getCheckout }
|
||||
|
||||
export type CheckoutAPI = GetAPISchema<CommerceAPI, CheckoutSchema>
|
||||
export type CheckoutEndpoint = CheckoutAPI['endpoint']
|
||||
|
||||
const checkoutApi = createEndpoint<CheckoutAPI>({
|
||||
handler: checkoutEndpoint,
|
||||
handlers,
|
||||
})
|
||||
|
||||
export default checkoutApi
|
1
packages/swell/src/api/endpoints/customer/address.ts
Normal file
1
packages/swell/src/api/endpoints/customer/address.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function noopApi(...args: any[]): void {}
|
1
packages/swell/src/api/endpoints/customer/card.ts
Normal file
1
packages/swell/src/api/endpoints/customer/card.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function noopApi(...args: any[]): void {}
|
1
packages/swell/src/api/endpoints/customer/index.ts
Normal file
1
packages/swell/src/api/endpoints/customer/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function noopApi(...args: any[]): void {}
|
1
packages/swell/src/api/endpoints/login.ts
Normal file
1
packages/swell/src/api/endpoints/login.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function (_commerce: any) {}
|
1
packages/swell/src/api/endpoints/logout.ts
Normal file
1
packages/swell/src/api/endpoints/logout.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function (_commerce: any) {}
|
1
packages/swell/src/api/endpoints/signup.ts
Normal file
1
packages/swell/src/api/endpoints/signup.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function (_commerce: any) {}
|
1
packages/swell/src/api/endpoints/wishlist.ts
Normal file
1
packages/swell/src/api/endpoints/wishlist.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default function (_commerce: any) {}
|
53
packages/swell/src/api/index.ts
Normal file
53
packages/swell/src/api/index.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
CommerceAPI,
|
||||
CommerceAPIConfig,
|
||||
getCommerceApi as commerceApi,
|
||||
} from '@vercel/commerce/api'
|
||||
import {
|
||||
SWELL_CHECKOUT_ID_COOKIE,
|
||||
SWELL_CUSTOMER_TOKEN_COOKIE,
|
||||
SWELL_COOKIE_EXPIRE,
|
||||
} from '../const'
|
||||
|
||||
import fetchApi from './utils/fetch-swell-api'
|
||||
import login from './operations/login'
|
||||
import getAllPages from './operations/get-all-pages'
|
||||
import getPage from './operations/get-page'
|
||||
import getSiteInfo from './operations/get-site-info'
|
||||
import getAllProductPaths from './operations/get-all-product-paths'
|
||||
import getAllProducts from './operations/get-all-products'
|
||||
import getProduct from './operations/get-product'
|
||||
|
||||
export interface SwellConfig extends CommerceAPIConfig {
|
||||
fetch: any
|
||||
}
|
||||
|
||||
const config: SwellConfig = {
|
||||
locale: 'en-US',
|
||||
commerceUrl: '',
|
||||
apiToken: ''!,
|
||||
cartCookie: SWELL_CHECKOUT_ID_COOKIE,
|
||||
cartCookieMaxAge: SWELL_COOKIE_EXPIRE,
|
||||
fetch: fetchApi,
|
||||
customerCookie: SWELL_CUSTOMER_TOKEN_COOKIE,
|
||||
}
|
||||
|
||||
const operations = {
|
||||
login,
|
||||
getAllPages,
|
||||
getPage,
|
||||
getSiteInfo,
|
||||
getAllProductPaths,
|
||||
getAllProducts,
|
||||
getProduct,
|
||||
}
|
||||
|
||||
export const provider = { config, operations }
|
||||
|
||||
export type Provider = typeof provider
|
||||
|
||||
export function getCommerceApi<P extends Provider>(
|
||||
customProvider: P = provider as any
|
||||
): CommerceAPI<P> {
|
||||
return commerceApi(customProvider)
|
||||
}
|
44
packages/swell/src/api/operations/get-all-pages.ts
Normal file
44
packages/swell/src/api/operations/get-all-pages.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Provider, SwellConfig } from '..'
|
||||
import type { OperationContext } from '@vercel/commerce/api/operations'
|
||||
import type { Page } from '../../types/page'
|
||||
|
||||
export type GetAllPagesResult<T extends { pages: any[] } = { pages: Page[] }> =
|
||||
T
|
||||
|
||||
export default function getAllPagesOperation({
|
||||
commerce,
|
||||
}: OperationContext<Provider>) {
|
||||
async function getAllPages(opts?: {
|
||||
config?: Partial<SwellConfig>
|
||||
preview?: boolean
|
||||
}): Promise<GetAllPagesResult>
|
||||
|
||||
async function getAllPages<T extends { pages: any[] }>(opts: {
|
||||
url: string
|
||||
config?: Partial<SwellConfig>
|
||||
preview?: boolean
|
||||
}): Promise<GetAllPagesResult<T>>
|
||||
|
||||
async function getAllPages({
|
||||
config: cfg,
|
||||
preview,
|
||||
}: {
|
||||
url?: string
|
||||
config?: Partial<SwellConfig>
|
||||
preview?: boolean
|
||||
} = {}): Promise<GetAllPagesResult> {
|
||||
const config = commerce.getConfig(cfg)
|
||||
const { locale, fetch } = config
|
||||
const data = await fetch('content', 'list', ['pages'])
|
||||
const pages =
|
||||
data?.results?.map(({ slug, ...rest }: { slug: string }) => ({
|
||||
url: `/${locale}/${slug}`,
|
||||
...rest,
|
||||
})) ?? []
|
||||
return {
|
||||
pages,
|
||||
}
|
||||
}
|
||||
|
||||
return getAllPages
|
||||
}
|
51
packages/swell/src/api/operations/get-all-product-paths.ts
Normal file
51
packages/swell/src/api/operations/get-all-product-paths.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { SwellProduct } from '../../types'
|
||||
import { SwellConfig, Provider } from '..'
|
||||
import {
|
||||
OperationContext,
|
||||
OperationOptions,
|
||||
} from '@vercel/commerce/api/operations'
|
||||
import { GetAllProductPathsOperation } from '@vercel/commerce/types/product'
|
||||
|
||||
export default function getAllProductPathsOperation({
|
||||
commerce,
|
||||
}: OperationContext<Provider>) {
|
||||
async function getAllProductPaths<
|
||||
T extends GetAllProductPathsOperation
|
||||
>(opts?: {
|
||||
variables?: T['variables']
|
||||
config?: SwellConfig
|
||||
}): Promise<T['data']>
|
||||
|
||||
async function getAllProductPaths<T extends GetAllProductPathsOperation>(
|
||||
opts: {
|
||||
variables?: T['variables']
|
||||
config?: SwellConfig
|
||||
} & OperationOptions
|
||||
): Promise<T['data']>
|
||||
|
||||
async function getAllProductPaths<T extends GetAllProductPathsOperation>({
|
||||
variables,
|
||||
config: cfg,
|
||||
}: {
|
||||
query?: string
|
||||
variables?: T['variables']
|
||||
config?: SwellConfig
|
||||
} = {}): Promise<T['data']> {
|
||||
const config = commerce.getConfig(cfg)
|
||||
// RecursivePartial forces the method to check for every prop in the data, which is
|
||||
// required in case there's a custom `query`
|
||||
const { results } = await config.fetch('products', 'list', [
|
||||
{
|
||||
limit: variables?.first,
|
||||
},
|
||||
])
|
||||
|
||||
return {
|
||||
products: results?.map(({ slug: handle }: SwellProduct) => ({
|
||||
path: `/${handle}`,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
return getAllProductPaths
|
||||
}
|
43
packages/swell/src/api/operations/get-all-products.ts
Normal file
43
packages/swell/src/api/operations/get-all-products.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { normalizeProduct } from '../../utils/normalize'
|
||||
import { SwellProduct } from '../../types'
|
||||
import { Product } from '@vercel/commerce/types/product'
|
||||
import { Provider, SwellConfig } from '../'
|
||||
import { OperationContext } from '@vercel/commerce/api/operations'
|
||||
|
||||
export type ProductVariables = { first?: number }
|
||||
|
||||
export default function getAllProductsOperation({
|
||||
commerce,
|
||||
}: OperationContext<Provider>) {
|
||||
async function getAllProducts(opts?: {
|
||||
variables?: ProductVariables
|
||||
config?: Partial<SwellConfig>
|
||||
preview?: boolean
|
||||
}): Promise<{ products: Product[] }>
|
||||
|
||||
async function getAllProducts({
|
||||
config: cfg,
|
||||
variables = { first: 250 },
|
||||
}: {
|
||||
query?: string
|
||||
variables?: ProductVariables
|
||||
config?: Partial<SwellConfig>
|
||||
preview?: boolean
|
||||
} = {}): Promise<{ products: Product[] | any[] }> {
|
||||
const config = commerce.getConfig(cfg)
|
||||
const { results } = await config.fetch('products', 'list', [
|
||||
{
|
||||
limit: variables.first,
|
||||
},
|
||||
])
|
||||
const products = results.map((product: SwellProduct) =>
|
||||
normalizeProduct(product)
|
||||
)
|
||||
|
||||
return {
|
||||
products,
|
||||
}
|
||||
}
|
||||
|
||||
return getAllProducts
|
||||
}
|
57
packages/swell/src/api/operations/get-page.ts
Normal file
57
packages/swell/src/api/operations/get-page.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { Page } from '../../../schema'
|
||||
import { SwellConfig, Provider } from '..'
|
||||
import {
|
||||
OperationContext,
|
||||
OperationOptions,
|
||||
} from '@vercel/commerce/api/operations'
|
||||
import { GetPageOperation } from '../../types/page'
|
||||
|
||||
export type GetPageResult<T extends { page?: any } = { page?: Page }> = T
|
||||
|
||||
export type PageVariables = {
|
||||
id: number
|
||||
}
|
||||
|
||||
export default function getPageOperation({
|
||||
commerce,
|
||||
}: OperationContext<Provider>) {
|
||||
async function getPage<T extends GetPageOperation>(opts: {
|
||||
variables: T['variables']
|
||||
config?: Partial<SwellConfig>
|
||||
preview?: boolean
|
||||
}): Promise<T['data']>
|
||||
|
||||
async function getPage<T extends GetPageOperation>(
|
||||
opts: {
|
||||
variables: T['variables']
|
||||
config?: Partial<SwellConfig>
|
||||
preview?: boolean
|
||||
} & OperationOptions
|
||||
): Promise<T['data']>
|
||||
|
||||
async function getPage<T extends GetPageOperation>({
|
||||
variables,
|
||||
config,
|
||||
}: {
|
||||
query?: string
|
||||
variables: T['variables']
|
||||
config?: Partial<SwellConfig>
|
||||
preview?: boolean
|
||||
}): Promise<T['data']> {
|
||||
const { fetch, locale = 'en-US' } = commerce.getConfig(config)
|
||||
const id = variables.id
|
||||
const result = await fetch('content', 'get', ['pages', id])
|
||||
const page = result
|
||||
|
||||
return {
|
||||
page: page
|
||||
? {
|
||||
...page,
|
||||
url: `/${locale}/${page.slug}`,
|
||||
}
|
||||
: null,
|
||||
}
|
||||
}
|
||||
|
||||
return getPage
|
||||
}
|
33
packages/swell/src/api/operations/get-product.ts
Normal file
33
packages/swell/src/api/operations/get-product.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { normalizeProduct } from '../../utils'
|
||||
|
||||
import { Product } from '@vercel/commerce/types/product'
|
||||
import { OperationContext } from '@vercel/commerce/api/operations'
|
||||
import { Provider, SwellConfig } from '../'
|
||||
|
||||
export default function getProductOperation({
|
||||
commerce,
|
||||
}: OperationContext<Provider>) {
|
||||
async function getProduct({
|
||||
variables,
|
||||
config: cfg,
|
||||
}: {
|
||||
query?: string
|
||||
variables: { slug: string }
|
||||
config?: Partial<SwellConfig>
|
||||
preview?: boolean
|
||||
}): Promise<Product | {} | any> {
|
||||
const config = commerce.getConfig(cfg)
|
||||
|
||||
const product = await config.fetch('products', 'get', [variables.slug])
|
||||
|
||||
if (product && product.variants) {
|
||||
product.variants = product.variants?.results
|
||||
}
|
||||
|
||||
return {
|
||||
product: product ? normalizeProduct(product) : null,
|
||||
}
|
||||
}
|
||||
|
||||
return getProduct
|
||||
}
|
37
packages/swell/src/api/operations/get-site-info.ts
Normal file
37
packages/swell/src/api/operations/get-site-info.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import getCategories from '../../utils/get-categories'
|
||||
import getVendors, { Brands } from '../../utils/get-vendors'
|
||||
import { Provider, SwellConfig } from '../'
|
||||
import type { OperationContext } from '@vercel/commerce/api/operations'
|
||||
import type { Category } from '@vercel/commerce/types/site'
|
||||
|
||||
export type GetSiteInfoResult<
|
||||
T extends { categories: any[]; brands: any[] } = {
|
||||
categories: Category[]
|
||||
brands: Brands
|
||||
}
|
||||
> = T
|
||||
|
||||
export default function getSiteInfoOperation({
|
||||
commerce,
|
||||
}: OperationContext<Provider>) {
|
||||
async function getSiteInfo({
|
||||
variables,
|
||||
config: cfg,
|
||||
}: {
|
||||
query?: string
|
||||
variables?: any
|
||||
config?: Partial<SwellConfig>
|
||||
preview?: boolean
|
||||
} = {}): Promise<GetSiteInfoResult> {
|
||||
const config = commerce.getConfig(cfg)
|
||||
const categories = await getCategories(config)
|
||||
const brands = await getVendors(config)
|
||||
|
||||
return {
|
||||
categories,
|
||||
brands,
|
||||
}
|
||||
}
|
||||
|
||||
return getSiteInfo
|
||||
}
|
46
packages/swell/src/api/operations/login.ts
Normal file
46
packages/swell/src/api/operations/login.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import type { ServerResponse } from 'http'
|
||||
import type {
|
||||
OperationContext,
|
||||
OperationOptions,
|
||||
} from '@vercel/commerce/api/operations'
|
||||
import type { LoginOperation } from '../../types/login'
|
||||
import { Provider, SwellConfig } from '..'
|
||||
|
||||
export default function loginOperation({
|
||||
commerce,
|
||||
}: OperationContext<Provider>) {
|
||||
async function login<T extends LoginOperation>(opts: {
|
||||
variables: T['variables']
|
||||
config?: Partial<SwellConfig>
|
||||
res: ServerResponse
|
||||
}): Promise<T['data']>
|
||||
|
||||
async function login<T extends LoginOperation>(
|
||||
opts: {
|
||||
variables: T['variables']
|
||||
config?: Partial<SwellConfig>
|
||||
res: ServerResponse
|
||||
} & OperationOptions
|
||||
): Promise<T['data']>
|
||||
|
||||
async function login<T extends LoginOperation>({
|
||||
variables,
|
||||
res: response,
|
||||
config: cfg,
|
||||
}: {
|
||||
query?: string
|
||||
variables: T['variables']
|
||||
res: ServerResponse
|
||||
config?: Partial<SwellConfig>
|
||||
}): Promise<T['data']> {
|
||||
const config = commerce.getConfig(cfg)
|
||||
|
||||
const { data } = await config.fetch('account', 'login', [variables])
|
||||
|
||||
return {
|
||||
result: data,
|
||||
}
|
||||
}
|
||||
|
||||
return login
|
||||
}
|
7
packages/swell/src/api/utils/fetch-swell-api.ts
Normal file
7
packages/swell/src/api/utils/fetch-swell-api.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import swell from '../../swell'
|
||||
|
||||
const fetchApi = async (query: string, method: string, variables: [] = []) => {
|
||||
return swell[query][method](...variables)
|
||||
}
|
||||
|
||||
export default fetchApi
|
2
packages/swell/src/api/utils/fetch.ts
Normal file
2
packages/swell/src/api/utils/fetch.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
import zeitFetch from '@vercel/fetch'
|
||||
export default zeitFetch()
|
28
packages/swell/src/api/utils/is-allowed-method.ts
Normal file
28
packages/swell/src/api/utils/is-allowed-method.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
|
||||
export default function isAllowedMethod(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse,
|
||||
allowedMethods: string[]
|
||||
) {
|
||||
const methods = allowedMethods.includes('OPTIONS')
|
||||
? allowedMethods
|
||||
: [...allowedMethods, 'OPTIONS']
|
||||
|
||||
if (!req.method || !methods.includes(req.method)) {
|
||||
res.status(405)
|
||||
res.setHeader('Allow', methods.join(', '))
|
||||
res.end()
|
||||
return false
|
||||
}
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
res.status(200)
|
||||
res.setHeader('Allow', methods.join(', '))
|
||||
res.setHeader('Content-Length', '0')
|
||||
res.end()
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
2
packages/swell/src/api/wishlist/index.tsx
Normal file
2
packages/swell/src/api/wishlist/index.tsx
Normal file
@@ -0,0 +1,2 @@
|
||||
export type WishlistItem = { product: any; id: number }
|
||||
export default function () {}
|
76
packages/swell/src/auth/use-login.tsx
Normal file
76
packages/swell/src/auth/use-login.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import { useCallback } from 'react'
|
||||
import type { MutationHook } from '@vercel/commerce/utils/types'
|
||||
import { CommerceError, ValidationError } from '@vercel/commerce/utils/errors'
|
||||
import useCustomer from '../customer/use-customer'
|
||||
import {
|
||||
CustomerUserError,
|
||||
Mutation,
|
||||
MutationCheckoutCreateArgs,
|
||||
} from '../../schema'
|
||||
import useLogin, { UseLogin } from '@vercel/commerce/auth/use-login'
|
||||
import { LoginHook } from '../types/login'
|
||||
import { setCustomerToken } from '../utils'
|
||||
|
||||
export default useLogin as UseLogin<typeof handler>
|
||||
|
||||
const getErrorMessage = ({ code, message }: CustomerUserError) => {
|
||||
switch (code) {
|
||||
case 'UNIDENTIFIED_CUSTOMER':
|
||||
message = 'Cannot find an account that matches the provided credentials'
|
||||
break
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
export const handler: MutationHook<LoginHook> = {
|
||||
fetchOptions: {
|
||||
query: 'account',
|
||||
method: 'login',
|
||||
},
|
||||
async fetcher({ input: { email, password }, options, fetch }) {
|
||||
if (!(email && password)) {
|
||||
throw new CommerceError({
|
||||
message:
|
||||
'A first name, last name, email and password are required to login',
|
||||
})
|
||||
}
|
||||
|
||||
const { customerAccessTokenCreate } = await fetch<
|
||||
Mutation,
|
||||
MutationCheckoutCreateArgs
|
||||
>({
|
||||
...options,
|
||||
variables: [email, password],
|
||||
})
|
||||
|
||||
const errors = customerAccessTokenCreate?.customerUserErrors
|
||||
|
||||
if (errors && errors.length) {
|
||||
throw new ValidationError({
|
||||
message: getErrorMessage(errors[0]),
|
||||
})
|
||||
}
|
||||
const customerAccessToken = customerAccessTokenCreate?.customerAccessToken
|
||||
const accessToken = customerAccessToken?.accessToken
|
||||
|
||||
if (accessToken) {
|
||||
setCustomerToken(accessToken)
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
useHook:
|
||||
({ fetch }) =>
|
||||
() => {
|
||||
const { mutate } = useCustomer()
|
||||
|
||||
return useCallback(
|
||||
async function login(input) {
|
||||
const data = await fetch({ input })
|
||||
await mutate()
|
||||
return data
|
||||
},
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
}
|
39
packages/swell/src/auth/use-logout.tsx
Normal file
39
packages/swell/src/auth/use-logout.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
import { useCallback } from 'react'
|
||||
import type { MutationHook } from '@vercel/commerce/utils/types'
|
||||
import useLogout, { UseLogout } from '@vercel/commerce/auth/use-logout'
|
||||
import useCustomer from '../customer/use-customer'
|
||||
import { getCustomerToken, setCustomerToken } from '../utils/customer-token'
|
||||
import { LogoutHook } from '../types/logout'
|
||||
|
||||
export default useLogout as UseLogout<typeof handler>
|
||||
|
||||
export const handler: MutationHook<LogoutHook> = {
|
||||
fetchOptions: {
|
||||
query: 'account',
|
||||
method: 'logout',
|
||||
},
|
||||
async fetcher({ options, fetch }) {
|
||||
await fetch({
|
||||
...options,
|
||||
variables: {
|
||||
customerAccessToken: getCustomerToken(),
|
||||
},
|
||||
})
|
||||
setCustomerToken(null)
|
||||
return null
|
||||
},
|
||||
useHook:
|
||||
({ fetch }) =>
|
||||
() => {
|
||||
const { mutate } = useCustomer()
|
||||
|
||||
return useCallback(
|
||||
async function logout() {
|
||||
const data = await fetch()
|
||||
await mutate(null, false)
|
||||
return data
|
||||
},
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
}
|
61
packages/swell/src/auth/use-signup.tsx
Normal file
61
packages/swell/src/auth/use-signup.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import { useCallback } from 'react'
|
||||
import type { MutationHook } from '@vercel/commerce/utils/types'
|
||||
import { CommerceError } from '@vercel/commerce/utils/errors'
|
||||
import useSignup, { UseSignup } from '@vercel/commerce/auth/use-signup'
|
||||
import useCustomer from '../customer/use-customer'
|
||||
import { SignupHook } from '../types/signup'
|
||||
import handleLogin from '../utils/handle-login'
|
||||
|
||||
export default useSignup as UseSignup<typeof handler>
|
||||
|
||||
export const handler: MutationHook<SignupHook> = {
|
||||
fetchOptions: {
|
||||
query: 'account',
|
||||
method: 'create',
|
||||
},
|
||||
async fetcher({
|
||||
input: { firstName, lastName, email, password },
|
||||
options,
|
||||
fetch,
|
||||
}) {
|
||||
if (!(firstName && lastName && email && password)) {
|
||||
throw new CommerceError({
|
||||
message:
|
||||
'A first name, last name, email and password are required to signup',
|
||||
})
|
||||
}
|
||||
const data = await fetch({
|
||||
...options,
|
||||
variables: {
|
||||
first_name: firstName,
|
||||
last_name: lastName,
|
||||
email,
|
||||
password,
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
const loginData = await fetch({
|
||||
query: 'account',
|
||||
method: 'login',
|
||||
variables: [email, password],
|
||||
})
|
||||
handleLogin(loginData)
|
||||
} catch (error) {}
|
||||
return data
|
||||
},
|
||||
useHook:
|
||||
({ fetch }) =>
|
||||
() => {
|
||||
const { mutate } = useCustomer()
|
||||
|
||||
return useCallback(
|
||||
async function signup(input) {
|
||||
const data = await fetch({ input })
|
||||
await mutate()
|
||||
return data
|
||||
},
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
}
|
3
packages/swell/src/cart/index.ts
Normal file
3
packages/swell/src/cart/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export { default as useCart } from './use-cart'
|
||||
export { default as useAddItem } from './use-add-item'
|
||||
export { default as useRemoveItem } from './use-remove-item'
|
61
packages/swell/src/cart/use-add-item.tsx
Normal file
61
packages/swell/src/cart/use-add-item.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import type { MutationHook } from '@vercel/commerce/utils/types'
|
||||
import { CommerceError } from '@vercel/commerce/utils/errors'
|
||||
import useAddItem, { UseAddItem } from '@vercel/commerce/cart/use-add-item'
|
||||
import useCart from './use-cart'
|
||||
import { checkoutToCart } from './utils'
|
||||
import { getCheckoutId } from '../utils'
|
||||
import { useCallback } from 'react'
|
||||
import { AddItemHook } from '../types/cart'
|
||||
|
||||
export default useAddItem as UseAddItem<typeof handler>
|
||||
|
||||
export const handler: MutationHook<AddItemHook> = {
|
||||
fetchOptions: {
|
||||
query: 'cart',
|
||||
method: 'addItem',
|
||||
},
|
||||
async fetcher({ input: item, options, fetch }) {
|
||||
if (
|
||||
item.quantity &&
|
||||
(!Number.isInteger(item.quantity) || item.quantity! < 1)
|
||||
) {
|
||||
throw new CommerceError({
|
||||
message: 'The item quantity has to be a valid integer greater than 0',
|
||||
})
|
||||
}
|
||||
const variables: {
|
||||
product_id: string | undefined
|
||||
variant_id?: string
|
||||
checkoutId?: string
|
||||
quantity?: number
|
||||
} = {
|
||||
checkoutId: getCheckoutId(),
|
||||
product_id: item.productId,
|
||||
quantity: item.quantity,
|
||||
}
|
||||
if (item.productId !== item.variantId) {
|
||||
variables.variant_id = item.variantId
|
||||
}
|
||||
|
||||
const response = await fetch({
|
||||
...options,
|
||||
variables,
|
||||
})
|
||||
|
||||
return checkoutToCart(response) as any
|
||||
},
|
||||
useHook:
|
||||
({ fetch }) =>
|
||||
() => {
|
||||
const { mutate } = useCart()
|
||||
|
||||
return useCallback(
|
||||
async function addItem(input) {
|
||||
const data = await fetch({ input })
|
||||
await mutate(data, false)
|
||||
return data
|
||||
},
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
}
|
39
packages/swell/src/cart/use-cart.tsx
Normal file
39
packages/swell/src/cart/use-cart.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
import useCart, { UseCart } from '@vercel/commerce/cart/use-cart'
|
||||
import { SWRHook } from '@vercel/commerce/utils/types'
|
||||
import { useMemo } from 'react'
|
||||
import { normalizeCart } from '../utils/normalize'
|
||||
import { checkoutCreate, checkoutToCart } from './utils'
|
||||
import type { GetCartHook } from '@vercel/commerce/types/cart'
|
||||
|
||||
export default useCart as UseCart<typeof handler>
|
||||
|
||||
export const handler: SWRHook<GetCartHook> = {
|
||||
fetchOptions: {
|
||||
query: 'cart',
|
||||
method: 'get',
|
||||
},
|
||||
async fetcher({ fetch }) {
|
||||
const cart = await checkoutCreate(fetch)
|
||||
|
||||
return cart ? normalizeCart(cart) : null
|
||||
},
|
||||
useHook:
|
||||
({ useData }) =>
|
||||
(input) => {
|
||||
const response = useData({
|
||||
swrOptions: { revalidateOnFocus: false, ...input?.swrOptions },
|
||||
})
|
||||
return useMemo(
|
||||
() =>
|
||||
Object.create(response, {
|
||||
isEmpty: {
|
||||
get() {
|
||||
return (response.data?.lineItems.length ?? 0) <= 0
|
||||
},
|
||||
enumerable: true,
|
||||
},
|
||||
}),
|
||||
[response]
|
||||
)
|
||||
},
|
||||
}
|
57
packages/swell/src/cart/use-remove-item.tsx
Normal file
57
packages/swell/src/cart/use-remove-item.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import { useCallback } from 'react'
|
||||
import type {
|
||||
MutationHookContext,
|
||||
HookFetcherContext,
|
||||
} from '@vercel/commerce/utils/types'
|
||||
|
||||
import useRemoveItem, {
|
||||
UseRemoveItem,
|
||||
} from '@vercel/commerce/cart/use-remove-item'
|
||||
import type {
|
||||
Cart,
|
||||
LineItem,
|
||||
RemoveItemHook,
|
||||
} from '@vercel/commerce/types/cart'
|
||||
import useCart from './use-cart'
|
||||
import { checkoutToCart } from './utils'
|
||||
|
||||
export type RemoveItemFn<T = any> = T extends LineItem
|
||||
? (input?: RemoveItemActionInput<T>) => Promise<Cart | null | undefined>
|
||||
: (input: RemoveItemActionInput<T>) => Promise<Cart | null>
|
||||
|
||||
export type RemoveItemActionInput<T = any> = T extends LineItem
|
||||
? Partial<RemoveItemHook['actionInput']>
|
||||
: RemoveItemHook['actionInput']
|
||||
|
||||
export default useRemoveItem as UseRemoveItem<typeof handler>
|
||||
|
||||
export const handler = {
|
||||
fetchOptions: {
|
||||
query: 'cart',
|
||||
method: 'removeItem',
|
||||
},
|
||||
async fetcher({
|
||||
input: { itemId },
|
||||
options,
|
||||
fetch,
|
||||
}: HookFetcherContext<RemoveItemHook>) {
|
||||
const response = await fetch({ ...options, variables: [itemId] })
|
||||
|
||||
return checkoutToCart(response)
|
||||
},
|
||||
useHook:
|
||||
({ fetch }: MutationHookContext<RemoveItemHook>) =>
|
||||
() => {
|
||||
const { mutate } = useCart()
|
||||
|
||||
return useCallback(
|
||||
async function removeItem(input) {
|
||||
const data = await fetch({ input: { itemId: input.id } })
|
||||
await mutate(data, false)
|
||||
|
||||
return data
|
||||
},
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
}
|
101
packages/swell/src/cart/use-update-item.tsx
Normal file
101
packages/swell/src/cart/use-update-item.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
import { useCallback } from 'react'
|
||||
import debounce from 'lodash.debounce'
|
||||
import type {
|
||||
HookFetcherContext,
|
||||
MutationHook,
|
||||
MutationHookContext,
|
||||
} from '@vercel/commerce/utils/types'
|
||||
import { ValidationError } from '@vercel/commerce/utils/errors'
|
||||
// import useUpdateItem, {
|
||||
// UpdateItemInput as UpdateItemInputBase,
|
||||
// UseUpdateItem,
|
||||
// } from '@vercel/commerce/cart/use-update-item'
|
||||
import useUpdateItem, {
|
||||
UseUpdateItem,
|
||||
} from '@vercel/commerce/cart/use-update-item'
|
||||
import useCart from './use-cart'
|
||||
import { handler as removeItemHandler } from './use-remove-item'
|
||||
import { CartItemBody, LineItem } from '@vercel/commerce/types/cart'
|
||||
import { checkoutToCart } from './utils'
|
||||
import { UpdateItemHook } from '../types/cart'
|
||||
// export type UpdateItemInput<T = any> = T extends LineItem
|
||||
// ? Partial<UpdateItemInputBase<LineItem>>
|
||||
// : UpdateItemInputBase<LineItem>
|
||||
|
||||
export default useUpdateItem as UseUpdateItem<typeof handler>
|
||||
|
||||
export type UpdateItemActionInput<T = any> = T extends LineItem
|
||||
? Partial<UpdateItemHook['actionInput']>
|
||||
: UpdateItemHook['actionInput']
|
||||
|
||||
export const handler = {
|
||||
fetchOptions: {
|
||||
query: 'cart',
|
||||
method: 'updateItem',
|
||||
},
|
||||
async fetcher({
|
||||
input: { itemId, item },
|
||||
options,
|
||||
fetch,
|
||||
}: HookFetcherContext<UpdateItemHook>) {
|
||||
if (Number.isInteger(item.quantity)) {
|
||||
// Also allow the update hook to remove an item if the quantity is lower than 1
|
||||
if (item.quantity! < 1) {
|
||||
return removeItemHandler.fetcher({
|
||||
options: removeItemHandler.fetchOptions,
|
||||
input: { itemId },
|
||||
fetch,
|
||||
})
|
||||
}
|
||||
} else if (item.quantity) {
|
||||
throw new ValidationError({
|
||||
message: 'The item quantity has to be a valid integer',
|
||||
})
|
||||
}
|
||||
const response = await fetch({
|
||||
...options,
|
||||
variables: [itemId, { quantity: item.quantity }],
|
||||
})
|
||||
|
||||
return checkoutToCart(response)
|
||||
},
|
||||
useHook:
|
||||
({ fetch }: MutationHookContext<UpdateItemHook>) =>
|
||||
<T extends LineItem | undefined = undefined>(
|
||||
ctx: {
|
||||
item?: T
|
||||
wait?: number
|
||||
} = {}
|
||||
) => {
|
||||
const { item } = ctx
|
||||
const { mutate, data: cartData } = useCart() as any
|
||||
|
||||
return useCallback(
|
||||
debounce(async (input: UpdateItemActionInput) => {
|
||||
const firstLineItem = cartData.lineItems[0]
|
||||
const itemId = item?.id || firstLineItem.id
|
||||
const productId = item?.productId || firstLineItem.productId
|
||||
const variantId = item?.variant.id || firstLineItem.variant.id
|
||||
if (!itemId || !productId) {
|
||||
throw new ValidationError({
|
||||
message: 'Invalid input used for this operation',
|
||||
})
|
||||
}
|
||||
|
||||
const data = await fetch({
|
||||
input: {
|
||||
item: {
|
||||
productId,
|
||||
variantId,
|
||||
quantity: input.quantity,
|
||||
},
|
||||
itemId,
|
||||
},
|
||||
})
|
||||
await mutate(data, false)
|
||||
return data
|
||||
}, ctx.wait ?? 500),
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
}
|
28
packages/swell/src/cart/utils/checkout-create.ts
Normal file
28
packages/swell/src/cart/utils/checkout-create.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { SWELL_CHECKOUT_URL_COOKIE } from '../../const'
|
||||
|
||||
import Cookies from 'js-cookie'
|
||||
|
||||
export const checkoutCreate = async (fetch: any) => {
|
||||
const cart = await fetch({
|
||||
query: 'cart',
|
||||
method: 'get',
|
||||
})
|
||||
|
||||
if (!cart) {
|
||||
await fetch({
|
||||
query: 'cart',
|
||||
method: 'setItems',
|
||||
variables: [[]],
|
||||
})
|
||||
}
|
||||
|
||||
const checkoutUrl = cart?.checkout_url
|
||||
|
||||
if (checkoutUrl) {
|
||||
Cookies.set(SWELL_CHECKOUT_URL_COOKIE, checkoutUrl)
|
||||
}
|
||||
|
||||
return cart
|
||||
}
|
||||
|
||||
export default checkoutCreate
|
26
packages/swell/src/cart/utils/checkout-to-cart.ts
Normal file
26
packages/swell/src/cart/utils/checkout-to-cart.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { Cart } from '../../types'
|
||||
import { CommerceError } from '@vercel/commerce/utils/errors'
|
||||
|
||||
import {
|
||||
CheckoutLineItemsAddPayload,
|
||||
CheckoutLineItemsRemovePayload,
|
||||
CheckoutLineItemsUpdatePayload,
|
||||
Maybe,
|
||||
} from '../../../schema'
|
||||
import { normalizeCart } from '../../utils'
|
||||
|
||||
export type CheckoutPayload =
|
||||
| CheckoutLineItemsAddPayload
|
||||
| CheckoutLineItemsUpdatePayload
|
||||
| CheckoutLineItemsRemovePayload
|
||||
|
||||
const checkoutToCart = (checkoutPayload?: Maybe<CheckoutPayload>): Cart => {
|
||||
if (!checkoutPayload) {
|
||||
throw new CommerceError({
|
||||
message: 'Invalid response from Swell',
|
||||
})
|
||||
}
|
||||
return normalizeCart(checkoutPayload as any)
|
||||
}
|
||||
|
||||
export default checkoutToCart
|
2
packages/swell/src/cart/utils/index.ts
Normal file
2
packages/swell/src/cart/utils/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { default as checkoutToCart } from './checkout-to-cart'
|
||||
export { default as checkoutCreate } from './checkout-create'
|
16
packages/swell/src/checkout/use-checkout.tsx
Normal file
16
packages/swell/src/checkout/use-checkout.tsx
Normal file
@@ -0,0 +1,16 @@
|
||||
import { SWRHook } from '@vercel/commerce/utils/types'
|
||||
import useCheckout, {
|
||||
UseCheckout,
|
||||
} from '@vercel/commerce/checkout/use-checkout'
|
||||
|
||||
export default useCheckout as UseCheckout<typeof handler>
|
||||
|
||||
export const handler: SWRHook<any> = {
|
||||
fetchOptions: {
|
||||
query: '',
|
||||
},
|
||||
async fetcher({ input, options, fetch }) {},
|
||||
useHook:
|
||||
({ useData }) =>
|
||||
async (input) => ({}),
|
||||
}
|
6
packages/swell/src/commerce.config.json
Normal file
6
packages/swell/src/commerce.config.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"provider": "swell",
|
||||
"features": {
|
||||
"wishlist": false
|
||||
}
|
||||
}
|
11
packages/swell/src/const.ts
Normal file
11
packages/swell/src/const.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export const SWELL_CHECKOUT_ID_COOKIE = 'SWELL_checkoutId'
|
||||
|
||||
export const SWELL_CHECKOUT_URL_COOKIE = 'swell_checkoutUrl'
|
||||
|
||||
export const SWELL_CUSTOMER_TOKEN_COOKIE = 'swell_customerToken'
|
||||
|
||||
export const SWELL_COOKIE_EXPIRE = 30
|
||||
|
||||
export const SWELL_STORE_ID = process.env.NEXT_PUBLIC_SWELL_STORE_ID
|
||||
|
||||
export const SWELL_PUBLIC_KEY = process.env.NEXT_PUBLIC_SWELL_PUBLIC_KEY
|
17
packages/swell/src/customer/address/use-add-item.tsx
Normal file
17
packages/swell/src/customer/address/use-add-item.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import useAddItem, {
|
||||
UseAddItem,
|
||||
} from '@vercel/commerce/customer/address/use-add-item'
|
||||
import { MutationHook } from '@vercel/commerce/utils/types'
|
||||
|
||||
export default useAddItem as UseAddItem<typeof handler>
|
||||
|
||||
export const handler: MutationHook<any> = {
|
||||
fetchOptions: {
|
||||
query: '',
|
||||
},
|
||||
async fetcher({ input, options, fetch }) {},
|
||||
useHook:
|
||||
({ fetch }) =>
|
||||
() =>
|
||||
async () => ({}),
|
||||
}
|
17
packages/swell/src/customer/card/use-add-item.tsx
Normal file
17
packages/swell/src/customer/card/use-add-item.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import useAddItem, {
|
||||
UseAddItem,
|
||||
} from '@vercel/commerce/customer/card/use-add-item'
|
||||
import { MutationHook } from '@vercel/commerce/utils/types'
|
||||
|
||||
export default useAddItem as UseAddItem<typeof handler>
|
||||
|
||||
export const handler: MutationHook<any> = {
|
||||
fetchOptions: {
|
||||
query: '',
|
||||
},
|
||||
async fetcher({ input, options, fetch }) {},
|
||||
useHook:
|
||||
({ fetch }) =>
|
||||
() =>
|
||||
async () => ({}),
|
||||
}
|
1
packages/swell/src/customer/index.ts
Normal file
1
packages/swell/src/customer/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as useCustomer } from './use-customer'
|
31
packages/swell/src/customer/use-customer.tsx
Normal file
31
packages/swell/src/customer/use-customer.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import useCustomer, {
|
||||
UseCustomer,
|
||||
} from '@vercel/commerce/customer/use-customer'
|
||||
import { SWRHook } from '@vercel/commerce/utils/types'
|
||||
import { normalizeCustomer } from '../utils/normalize'
|
||||
import type { CustomerHook } from '../types/customer'
|
||||
|
||||
export default useCustomer as UseCustomer<typeof handler>
|
||||
|
||||
export const handler: SWRHook<CustomerHook> = {
|
||||
fetchOptions: {
|
||||
query: 'account',
|
||||
method: 'get',
|
||||
},
|
||||
async fetcher({ options, fetch }) {
|
||||
const data = await fetch<any | null>({
|
||||
...options,
|
||||
})
|
||||
return data ? normalizeCustomer(data) : null
|
||||
},
|
||||
useHook:
|
||||
({ useData }) =>
|
||||
(input) => {
|
||||
return useData({
|
||||
swrOptions: {
|
||||
revalidateOnFocus: false,
|
||||
...input?.swrOptions,
|
||||
},
|
||||
})
|
||||
},
|
||||
}
|
26
packages/swell/src/fetcher.ts
Normal file
26
packages/swell/src/fetcher.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { Fetcher } from '@vercel/commerce/utils/types'
|
||||
import { CommerceError } from '@vercel/commerce/utils/errors'
|
||||
import { handleFetchResponse } from './utils'
|
||||
import swell from './swell'
|
||||
|
||||
const fetcher: Fetcher = async ({ method = 'get', variables, query }) => {
|
||||
async function callSwell() {
|
||||
if (Array.isArray(variables)) {
|
||||
const arg1 = variables[0]
|
||||
const arg2 = variables[1]
|
||||
const response = await swell[query!][method](arg1, arg2)
|
||||
return handleFetchResponse(response)
|
||||
} else {
|
||||
const response = await swell[query!][method](variables)
|
||||
return handleFetchResponse(response)
|
||||
}
|
||||
}
|
||||
|
||||
if (query && query in swell) {
|
||||
return await callSwell()
|
||||
} else {
|
||||
throw new CommerceError({ message: 'Invalid query argument!' })
|
||||
}
|
||||
}
|
||||
|
||||
export default fetcher
|
12
packages/swell/src/index.tsx
Normal file
12
packages/swell/src/index.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
import {
|
||||
getCommerceProvider,
|
||||
useCommerce as useCoreCommerce,
|
||||
} from '@vercel/commerce'
|
||||
import { swellProvider, SwellProvider } from './provider'
|
||||
|
||||
export { swellProvider }
|
||||
export type { SwellProvider }
|
||||
|
||||
export const CommerceProvider = getCommerceProvider(swellProvider)
|
||||
|
||||
export const useCommerce = () => useCoreCommerce<SwellProvider>()
|
8
packages/swell/src/next.config.cjs
Normal file
8
packages/swell/src/next.config.cjs
Normal file
@@ -0,0 +1,8 @@
|
||||
const commerce = require('./commerce.config.json')
|
||||
|
||||
module.exports = {
|
||||
commerce,
|
||||
images: {
|
||||
domains: ['cdn.schema.io'],
|
||||
},
|
||||
}
|
2
packages/swell/src/product/index.ts
Normal file
2
packages/swell/src/product/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { default as usePrice } from './use-price'
|
||||
export { default as useSearch } from './use-search'
|
2
packages/swell/src/product/use-price.tsx
Normal file
2
packages/swell/src/product/use-price.tsx
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from '@vercel/commerce/product/use-price'
|
||||
export { default } from '@vercel/commerce/product/use-price'
|
61
packages/swell/src/product/use-search.tsx
Normal file
61
packages/swell/src/product/use-search.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import { SWRHook } from '@vercel/commerce/utils/types'
|
||||
import useSearch, { UseSearch } from '@vercel/commerce/product/use-search'
|
||||
import { normalizeProduct } from '../utils'
|
||||
import { SwellProduct } from '../types'
|
||||
import type { SearchProductsHook } from '../types/product'
|
||||
|
||||
export default useSearch as UseSearch<typeof handler>
|
||||
|
||||
export type SearchProductsInput = {
|
||||
search?: string
|
||||
categoryId?: string
|
||||
brandId?: string
|
||||
sort?: string
|
||||
}
|
||||
|
||||
export const handler: SWRHook<SearchProductsHook> = {
|
||||
fetchOptions: {
|
||||
query: 'products',
|
||||
method: 'list',
|
||||
},
|
||||
async fetcher({ input, options, fetch }) {
|
||||
const sortMap = new Map([
|
||||
['latest-desc', ''],
|
||||
['price-asc', 'price_asc'],
|
||||
['price-desc', 'price_desc'],
|
||||
['trending-desc', 'popularity'],
|
||||
])
|
||||
const { categoryId, search, sort = 'latest-desc' } = input
|
||||
const mappedSort = sortMap.get(sort)
|
||||
const { results, count: found } = await fetch({
|
||||
query: 'products',
|
||||
method: 'list',
|
||||
variables: { category: categoryId, search, sort: mappedSort },
|
||||
})
|
||||
|
||||
const products = results.map((product: SwellProduct) =>
|
||||
normalizeProduct(product)
|
||||
)
|
||||
|
||||
return {
|
||||
products,
|
||||
found,
|
||||
}
|
||||
},
|
||||
useHook:
|
||||
({ useData }) =>
|
||||
(input = {}) => {
|
||||
return useData({
|
||||
input: [
|
||||
['search', input.search],
|
||||
['categoryId', input.categoryId],
|
||||
['brandId', input.brandId],
|
||||
['sort', input.sort],
|
||||
],
|
||||
swrOptions: {
|
||||
revalidateOnFocus: false,
|
||||
...input.swrOptions,
|
||||
},
|
||||
})
|
||||
},
|
||||
}
|
30
packages/swell/src/provider.ts
Normal file
30
packages/swell/src/provider.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Provider } from '@vercel/commerce'
|
||||
import { SWELL_CHECKOUT_ID_COOKIE } from './const'
|
||||
|
||||
import { handler as useCart } from './cart/use-cart'
|
||||
import { handler as useAddItem } from './cart/use-add-item'
|
||||
import { handler as useUpdateItem } from './cart/use-update-item'
|
||||
import { handler as useRemoveItem } from './cart/use-remove-item'
|
||||
|
||||
import { handler as useCustomer } from './customer/use-customer'
|
||||
import { handler as useSearch } from './product/use-search'
|
||||
|
||||
import { handler as useLogin } from './auth/use-login'
|
||||
import { handler as useLogout } from './auth/use-logout'
|
||||
import { handler as useSignup } from './auth/use-signup'
|
||||
|
||||
import fetcher from './fetcher'
|
||||
import swell from './swell'
|
||||
|
||||
export const swellProvider: Provider & { swell: any } = {
|
||||
locale: 'en-us',
|
||||
cartCookie: SWELL_CHECKOUT_ID_COOKIE,
|
||||
swell,
|
||||
fetcher,
|
||||
cart: { useCart, useAddItem, useUpdateItem, useRemoveItem },
|
||||
customer: { useCustomer },
|
||||
products: { useSearch },
|
||||
auth: { useLogin, useLogout, useSignup },
|
||||
}
|
||||
|
||||
export type SwellProvider = typeof swellProvider
|
7
packages/swell/src/swell.ts
Normal file
7
packages/swell/src/swell.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
// @ts-ignore
|
||||
import swell from 'swell-js'
|
||||
import { SWELL_STORE_ID, SWELL_PUBLIC_KEY } from './const'
|
||||
|
||||
swell.init(SWELL_STORE_ID, SWELL_PUBLIC_KEY)
|
||||
|
||||
export default swell
|
112
packages/swell/src/types.ts
Normal file
112
packages/swell/src/types.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import * as Core from '@vercel/commerce/types/cart'
|
||||
import { Customer } from '@vercel/commerce/types'
|
||||
import { CheckoutLineItem } from '../schema'
|
||||
|
||||
export type SwellImage = {
|
||||
file: {
|
||||
url: String
|
||||
height: Number
|
||||
width: Number
|
||||
}
|
||||
id: string
|
||||
}
|
||||
|
||||
export type CartLineItem = {
|
||||
id: string
|
||||
product: SwellProduct
|
||||
price: number
|
||||
variant: {
|
||||
name: string | null
|
||||
sku: string | null
|
||||
id: string
|
||||
}
|
||||
quantity: number
|
||||
}
|
||||
|
||||
export type SwellCart = {
|
||||
id: string
|
||||
account_id: number
|
||||
currency: string
|
||||
tax_included_total: number
|
||||
sub_total: number
|
||||
grand_total: number
|
||||
discount_total: number
|
||||
quantity: number
|
||||
items: CartLineItem[]
|
||||
date_created: string
|
||||
discounts?: { id: number; amount: number }[] | null
|
||||
// TODO: add missing fields
|
||||
}
|
||||
|
||||
export type SwellVariant = {
|
||||
id: string
|
||||
option_value_ids: string[]
|
||||
name: string
|
||||
price?: number
|
||||
stock_status?: string
|
||||
__type?: 'MultipleChoiceOption' | undefined
|
||||
}
|
||||
|
||||
export interface SwellProductOptionValue {
|
||||
id: string
|
||||
label: string
|
||||
hexColors?: string[]
|
||||
}
|
||||
|
||||
export interface ProductOptionValue {
|
||||
label: string
|
||||
hexColors?: string[]
|
||||
}
|
||||
|
||||
export type ProductOptions = {
|
||||
id: string
|
||||
name: string
|
||||
variant: boolean
|
||||
values: ProductOptionValue[]
|
||||
required: boolean
|
||||
active: boolean
|
||||
attribute_id: string
|
||||
}
|
||||
|
||||
export interface SwellProduct {
|
||||
id: string
|
||||
description: string
|
||||
name: string
|
||||
slug: string
|
||||
currency: string
|
||||
price: number
|
||||
images: any[]
|
||||
options: any[]
|
||||
variants: any[]
|
||||
}
|
||||
|
||||
export type SwellCustomer = any
|
||||
|
||||
export type SwellCheckout = {
|
||||
id: string
|
||||
webUrl: string
|
||||
lineItems: CheckoutLineItem[]
|
||||
}
|
||||
|
||||
export interface Cart extends Core.Cart {
|
||||
id: string
|
||||
lineItems: LineItem[]
|
||||
}
|
||||
|
||||
export interface LineItem extends Core.LineItem {
|
||||
options?: any[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Cart mutations
|
||||
*/
|
||||
|
||||
export type OptionSelections = {
|
||||
option_id: number
|
||||
option_value: number | string
|
||||
}
|
||||
|
||||
export type CartItemBody = Core.CartItemBody & {
|
||||
productId: string // The product id is always required for BC
|
||||
optionSelections?: OptionSelections
|
||||
}
|
1
packages/swell/src/types/cart.ts
Normal file
1
packages/swell/src/types/cart.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from '@vercel/commerce/types/cart'
|
1
packages/swell/src/types/checkout.ts
Normal file
1
packages/swell/src/types/checkout.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from '@vercel/commerce/types/checkout'
|
1
packages/swell/src/types/common.ts
Normal file
1
packages/swell/src/types/common.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from '@vercel/commerce/types/common'
|
1
packages/swell/src/types/customer.ts
Normal file
1
packages/swell/src/types/customer.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from '@vercel/commerce/types/customer'
|
25
packages/swell/src/types/index.ts
Normal file
25
packages/swell/src/types/index.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import * as Cart from './cart'
|
||||
import * as Checkout from './checkout'
|
||||
import * as Common from './common'
|
||||
import * as Customer from './customer'
|
||||
import * as Login from './login'
|
||||
import * as Logout from './logout'
|
||||
import * as Page from './page'
|
||||
import * as Product from './product'
|
||||
import * as Signup from './signup'
|
||||
import * as Site from './site'
|
||||
import * as Wishlist from './wishlist'
|
||||
|
||||
export type {
|
||||
Cart,
|
||||
Checkout,
|
||||
Common,
|
||||
Customer,
|
||||
Login,
|
||||
Logout,
|
||||
Page,
|
||||
Product,
|
||||
Signup,
|
||||
Site,
|
||||
Wishlist,
|
||||
}
|
11
packages/swell/src/types/login.ts
Normal file
11
packages/swell/src/types/login.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import * as Core from '@vercel/commerce/types/login'
|
||||
import { LoginBody, LoginTypes } from '@vercel/commerce/types/login'
|
||||
|
||||
export * from '@vercel/commerce/types/login'
|
||||
|
||||
export type LoginHook<T extends LoginTypes = LoginTypes> = {
|
||||
data: null
|
||||
actionInput: LoginBody
|
||||
fetcherInput: LoginBody
|
||||
body: T['body']
|
||||
}
|
1
packages/swell/src/types/logout.ts
Normal file
1
packages/swell/src/types/logout.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from '@vercel/commerce/types/logout'
|
1
packages/swell/src/types/page.ts
Normal file
1
packages/swell/src/types/page.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from '@vercel/commerce/types/page'
|
1
packages/swell/src/types/product.ts
Normal file
1
packages/swell/src/types/product.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from '@vercel/commerce/types/product'
|
1
packages/swell/src/types/signup.ts
Normal file
1
packages/swell/src/types/signup.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from '@vercel/commerce/types/signup'
|
1
packages/swell/src/types/site.ts
Normal file
1
packages/swell/src/types/site.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from '@vercel/commerce/types/site'
|
1
packages/swell/src/types/wishlist.ts
Normal file
1
packages/swell/src/types/wishlist.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from '@vercel/commerce/types/wishlist'
|
21
packages/swell/src/utils/customer-token.ts
Normal file
21
packages/swell/src/utils/customer-token.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import Cookies, { CookieAttributes } from 'js-cookie'
|
||||
import { SWELL_COOKIE_EXPIRE, SWELL_CUSTOMER_TOKEN_COOKIE } from '../const'
|
||||
|
||||
export const getCustomerToken = () => Cookies.get(SWELL_CUSTOMER_TOKEN_COOKIE)
|
||||
|
||||
export const setCustomerToken = (
|
||||
token: string | null,
|
||||
options?: CookieAttributes
|
||||
) => {
|
||||
if (!token) {
|
||||
Cookies.remove(SWELL_CUSTOMER_TOKEN_COOKIE)
|
||||
} else {
|
||||
Cookies.set(
|
||||
SWELL_CUSTOMER_TOKEN_COOKIE,
|
||||
token,
|
||||
options ?? {
|
||||
expires: SWELL_COOKIE_EXPIRE,
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
16
packages/swell/src/utils/get-categories.ts
Normal file
16
packages/swell/src/utils/get-categories.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { SwellConfig } from '../api'
|
||||
import { Category } from '../types/site'
|
||||
|
||||
const getCategories = async (config: SwellConfig): Promise<Category[]> => {
|
||||
const data = await config.fetch('categories', 'get')
|
||||
return (
|
||||
data.results.map(({ id, name, slug }: any) => ({
|
||||
id,
|
||||
name,
|
||||
slug,
|
||||
path: `/${slug}`,
|
||||
})) ?? []
|
||||
)
|
||||
}
|
||||
|
||||
export default getCategories
|
8
packages/swell/src/utils/get-checkout-id.ts
Normal file
8
packages/swell/src/utils/get-checkout-id.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import Cookies from 'js-cookie'
|
||||
import { SWELL_CHECKOUT_ID_COOKIE } from '../const'
|
||||
|
||||
const getCheckoutId = (id?: string) => {
|
||||
return id ?? Cookies.get(SWELL_CHECKOUT_ID_COOKIE)
|
||||
}
|
||||
|
||||
export default getCheckoutId
|
27
packages/swell/src/utils/get-search-variables.ts
Normal file
27
packages/swell/src/utils/get-search-variables.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import getSortVariables from './get-sort-variables'
|
||||
import type { SearchProductsInput } from '../product/use-search'
|
||||
|
||||
export const getSearchVariables = ({
|
||||
brandId,
|
||||
search,
|
||||
categoryId,
|
||||
sort,
|
||||
}: SearchProductsInput) => {
|
||||
let query = ''
|
||||
|
||||
if (search) {
|
||||
query += `product_type:${search} OR title:${search} OR tag:${search}`
|
||||
}
|
||||
|
||||
if (brandId) {
|
||||
query += `${search ? ' AND ' : ''}vendor:${brandId}`
|
||||
}
|
||||
|
||||
return {
|
||||
categoryId,
|
||||
query,
|
||||
...getSortVariables(sort, !!categoryId),
|
||||
}
|
||||
}
|
||||
|
||||
export default getSearchVariables
|
32
packages/swell/src/utils/get-sort-variables.ts
Normal file
32
packages/swell/src/utils/get-sort-variables.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
const getSortVariables = (sort?: string, isCategory = false) => {
|
||||
let output = {}
|
||||
switch (sort) {
|
||||
case 'price-asc':
|
||||
output = {
|
||||
sortKey: 'PRICE',
|
||||
reverse: false,
|
||||
}
|
||||
break
|
||||
case 'price-desc':
|
||||
output = {
|
||||
sortKey: 'PRICE',
|
||||
reverse: true,
|
||||
}
|
||||
break
|
||||
case 'trending-desc':
|
||||
output = {
|
||||
sortKey: 'BEST_SELLING',
|
||||
reverse: false,
|
||||
}
|
||||
break
|
||||
case 'latest-desc':
|
||||
output = {
|
||||
sortKey: isCategory ? 'CREATED' : 'CREATED_AT',
|
||||
reverse: true,
|
||||
}
|
||||
break
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
export default getSortVariables
|
27
packages/swell/src/utils/get-vendors.ts
Normal file
27
packages/swell/src/utils/get-vendors.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { SwellConfig } from '../api'
|
||||
|
||||
export type BrandNode = {
|
||||
name: string
|
||||
path: string
|
||||
}
|
||||
|
||||
export type BrandEdge = {
|
||||
node: BrandNode
|
||||
}
|
||||
|
||||
export type Brands = BrandEdge[]
|
||||
|
||||
const getVendors = async (config: SwellConfig) => {
|
||||
const vendors: [string] =
|
||||
(await config.fetch('attributes', 'get', ['brand']))?.values ?? []
|
||||
|
||||
return [...new Set(vendors)].map((v) => ({
|
||||
node: {
|
||||
entityId: v,
|
||||
name: v,
|
||||
path: `brands/${v}`,
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
export default getVendors
|
19
packages/swell/src/utils/handle-fetch-response.ts
Normal file
19
packages/swell/src/utils/handle-fetch-response.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { CommerceError } from '@vercel/commerce/utils/errors'
|
||||
|
||||
type SwellFetchResponse = {
|
||||
error: {
|
||||
message: string
|
||||
code?: string
|
||||
}
|
||||
}
|
||||
|
||||
const handleFetchResponse = async (res: SwellFetchResponse) => {
|
||||
if (res) {
|
||||
if (res.error) {
|
||||
throw new CommerceError(res.error)
|
||||
}
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
export default handleFetchResponse
|
39
packages/swell/src/utils/handle-login.ts
Normal file
39
packages/swell/src/utils/handle-login.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { ValidationError } from '@vercel/commerce/utils/errors'
|
||||
import { setCustomerToken } from './customer-token'
|
||||
|
||||
const getErrorMessage = ({
|
||||
code,
|
||||
message,
|
||||
}: {
|
||||
code: string
|
||||
message: string
|
||||
}) => {
|
||||
switch (code) {
|
||||
case 'UNIDENTIFIED_CUSTOMER':
|
||||
message = 'Cannot find an account that matches the provided credentials'
|
||||
break
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
const handleLogin = (data: any) => {
|
||||
const response = data.customerAccessTokenCreate
|
||||
const errors = response?.customerUserErrors
|
||||
|
||||
if (errors && errors.length) {
|
||||
throw new ValidationError({
|
||||
message: getErrorMessage(errors[0]),
|
||||
})
|
||||
}
|
||||
|
||||
const customerAccessToken = response?.customerAccessToken
|
||||
const accessToken = customerAccessToken?.accessToken
|
||||
|
||||
if (accessToken) {
|
||||
setCustomerToken(accessToken)
|
||||
}
|
||||
|
||||
return customerAccessToken
|
||||
}
|
||||
|
||||
export default handleLogin
|
9
packages/swell/src/utils/index.ts
Normal file
9
packages/swell/src/utils/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export { default as handleFetchResponse } from './handle-fetch-response'
|
||||
export { default as getSearchVariables } from './get-search-variables'
|
||||
export { default as getSortVariables } from './get-sort-variables'
|
||||
export { default as getVendors } from './get-vendors'
|
||||
export { default as getCategories } from './get-categories'
|
||||
export { default as getCheckoutId } from './get-checkout-id'
|
||||
|
||||
export * from './normalize'
|
||||
export * from './customer-token'
|
226
packages/swell/src/utils/normalize.ts
Normal file
226
packages/swell/src/utils/normalize.ts
Normal file
@@ -0,0 +1,226 @@
|
||||
import { Customer } from '../types/customer'
|
||||
import { Product, ProductOption } from '../types/product'
|
||||
import { MoneyV2 } from '../../schema'
|
||||
|
||||
import type {
|
||||
Cart,
|
||||
CartLineItem,
|
||||
SwellCustomer,
|
||||
SwellProduct,
|
||||
SwellImage,
|
||||
SwellVariant,
|
||||
ProductOptionValue,
|
||||
SwellProductOptionValue,
|
||||
SwellCart,
|
||||
LineItem,
|
||||
} from '../types'
|
||||
|
||||
const money = ({ amount, currencyCode }: MoneyV2) => {
|
||||
return {
|
||||
value: +amount,
|
||||
currencyCode,
|
||||
}
|
||||
}
|
||||
|
||||
type swellProductOption = {
|
||||
id: string
|
||||
name: string
|
||||
values: any[]
|
||||
}
|
||||
|
||||
type normalizedProductOption = {
|
||||
id: string
|
||||
displayName: string
|
||||
values: ProductOptionValue[]
|
||||
}
|
||||
|
||||
const normalizeProductOption = ({
|
||||
id,
|
||||
name: displayName = '',
|
||||
values = [],
|
||||
}: swellProductOption): ProductOption => {
|
||||
let returnValues = values.map((value) => {
|
||||
let output: any = {
|
||||
label: value.name,
|
||||
// id: value?.id || id,
|
||||
}
|
||||
if (displayName.match(/colou?r/gi)) {
|
||||
output = {
|
||||
...output,
|
||||
hexColors: [value.name],
|
||||
}
|
||||
}
|
||||
return output
|
||||
})
|
||||
return {
|
||||
__typename: 'MultipleChoiceOption',
|
||||
id,
|
||||
displayName,
|
||||
values: returnValues,
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeProductImages = (images: SwellImage[]) => {
|
||||
if (!images || images.length < 1) {
|
||||
return [{ url: '/' }]
|
||||
}
|
||||
return images?.map(({ file, ...rest }: SwellImage) => ({
|
||||
url: file?.url + '',
|
||||
height: Number(file?.height),
|
||||
width: Number(file?.width),
|
||||
...rest,
|
||||
}))
|
||||
}
|
||||
|
||||
const normalizeProductVariants = (
|
||||
variants: SwellVariant[],
|
||||
productOptions: swellProductOption[]
|
||||
) => {
|
||||
return variants?.map(
|
||||
({ id, name, price, option_value_ids: optionValueIds = [] }) => {
|
||||
const values = name
|
||||
.split(',')
|
||||
.map((i) => ({ name: i.trim(), label: i.trim() }))
|
||||
|
||||
const options = optionValueIds.map((id) => {
|
||||
const matchingOption = productOptions.find((option) => {
|
||||
return option.values.find(
|
||||
(value: SwellProductOptionValue) => value.id == id
|
||||
)
|
||||
})
|
||||
return normalizeProductOption({
|
||||
id,
|
||||
name: matchingOption?.name ?? '',
|
||||
values,
|
||||
})
|
||||
})
|
||||
|
||||
return {
|
||||
id,
|
||||
// name,
|
||||
// sku: sku ?? id,
|
||||
// price: price ?? null,
|
||||
// listPrice: price ?? null,
|
||||
// requiresShipping: true,
|
||||
options,
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export function normalizeProduct(swellProduct: SwellProduct): Product {
|
||||
const {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
images,
|
||||
options,
|
||||
slug,
|
||||
variants,
|
||||
price: value,
|
||||
currency: currencyCode,
|
||||
} = swellProduct
|
||||
// ProductView accesses variants for each product
|
||||
const emptyVariants = [{ options: [], id, name }]
|
||||
|
||||
const productOptions = options
|
||||
? options.map((o) => normalizeProductOption(o))
|
||||
: []
|
||||
const productVariants = variants
|
||||
? normalizeProductVariants(variants, options)
|
||||
: []
|
||||
|
||||
const productImages = normalizeProductImages(images)
|
||||
const product = {
|
||||
...swellProduct,
|
||||
description,
|
||||
id,
|
||||
vendor: '',
|
||||
path: `/${slug}`,
|
||||
images: productImages,
|
||||
variants:
|
||||
productVariants && productVariants.length
|
||||
? productVariants
|
||||
: emptyVariants,
|
||||
options: productOptions,
|
||||
price: {
|
||||
value,
|
||||
currencyCode,
|
||||
},
|
||||
}
|
||||
return product
|
||||
}
|
||||
|
||||
export function normalizeCart({
|
||||
id,
|
||||
account_id,
|
||||
date_created,
|
||||
currency,
|
||||
tax_included_total,
|
||||
items,
|
||||
sub_total,
|
||||
grand_total,
|
||||
discounts,
|
||||
}: SwellCart) {
|
||||
const cart: Cart = {
|
||||
id: id,
|
||||
customerId: account_id + '',
|
||||
email: '',
|
||||
createdAt: date_created,
|
||||
currency: { code: currency },
|
||||
taxesIncluded: tax_included_total > 0,
|
||||
lineItems: items?.map(normalizeLineItem) ?? [],
|
||||
lineItemsSubtotalPrice: +sub_total,
|
||||
subtotalPrice: +sub_total,
|
||||
totalPrice: grand_total,
|
||||
discounts: discounts?.map((discount) => ({ value: discount.amount })),
|
||||
}
|
||||
return cart
|
||||
}
|
||||
|
||||
export function normalizeCustomer(customer: SwellCustomer): Customer {
|
||||
const { first_name: firstName, last_name: lastName } = customer
|
||||
return {
|
||||
...customer,
|
||||
firstName,
|
||||
lastName,
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeLineItem({
|
||||
id,
|
||||
product,
|
||||
price,
|
||||
variant,
|
||||
quantity,
|
||||
}: CartLineItem): LineItem {
|
||||
const item = {
|
||||
id,
|
||||
variantId: variant?.id,
|
||||
productId: product.id ?? '',
|
||||
name: product?.name ?? '',
|
||||
quantity,
|
||||
variant: {
|
||||
id: variant?.id ?? '',
|
||||
sku: variant?.sku ?? '',
|
||||
name: variant?.name!,
|
||||
image: {
|
||||
url:
|
||||
product?.images && product.images.length > 0
|
||||
? product?.images[0].file.url
|
||||
: '/',
|
||||
},
|
||||
requiresShipping: false,
|
||||
price: price,
|
||||
listPrice: price,
|
||||
},
|
||||
path: '',
|
||||
discounts: [],
|
||||
options: [
|
||||
{
|
||||
value: variant?.name,
|
||||
},
|
||||
],
|
||||
}
|
||||
return item
|
||||
}
|
13
packages/swell/src/utils/storage.ts
Normal file
13
packages/swell/src/utils/storage.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
export const getCheckoutIdFromStorage = (token: string) => {
|
||||
if (window && window.sessionStorage) {
|
||||
return window.sessionStorage.getItem(token)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export const setCheckoutIdInStorage = (token: string, id: string | number) => {
|
||||
if (window && window.sessionStorage) {
|
||||
return window.sessionStorage.setItem(token, id + '')
|
||||
}
|
||||
}
|
13
packages/swell/src/wishlist/use-add-item.tsx
Normal file
13
packages/swell/src/wishlist/use-add-item.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { useCallback } from 'react'
|
||||
|
||||
export function emptyHook() {
|
||||
const useEmptyHook = async (options = {}) => {
|
||||
return useCallback(async function () {
|
||||
return Promise.resolve()
|
||||
}, [])
|
||||
}
|
||||
|
||||
return useEmptyHook
|
||||
}
|
||||
|
||||
export default emptyHook
|
17
packages/swell/src/wishlist/use-remove-item.tsx
Normal file
17
packages/swell/src/wishlist/use-remove-item.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { useCallback } from 'react'
|
||||
|
||||
type Options = {
|
||||
includeProducts?: boolean
|
||||
}
|
||||
|
||||
export function emptyHook(options?: Options) {
|
||||
const useEmptyHook = async ({ id }: { id: string | number }) => {
|
||||
return useCallback(async function () {
|
||||
return Promise.resolve()
|
||||
}, [])
|
||||
}
|
||||
|
||||
return useEmptyHook
|
||||
}
|
||||
|
||||
export default emptyHook
|
46
packages/swell/src/wishlist/use-wishlist.tsx
Normal file
46
packages/swell/src/wishlist/use-wishlist.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
// TODO: replace this hook and other wishlist hooks with a handler, or remove them if
|
||||
// Swell doesn't have a wishlist
|
||||
|
||||
import { HookFetcher } from '@vercel/commerce/utils/types'
|
||||
import { Product } from '../../schema'
|
||||
|
||||
const defaultOpts = {}
|
||||
|
||||
export type Wishlist = {
|
||||
items: [
|
||||
{
|
||||
product_id: number
|
||||
variant_id: number
|
||||
id: number
|
||||
product: Product
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export interface UseWishlistOptions {
|
||||
includeProducts?: boolean
|
||||
}
|
||||
|
||||
export interface UseWishlistInput extends UseWishlistOptions {
|
||||
customerId?: number
|
||||
}
|
||||
|
||||
export const fetcher: HookFetcher<Wishlist | null, UseWishlistInput> = () => {
|
||||
return null
|
||||
}
|
||||
|
||||
export function extendHook(
|
||||
customFetcher: typeof fetcher,
|
||||
// swrOptions?: SwrOptions<Wishlist | null, UseWishlistInput>
|
||||
swrOptions?: any
|
||||
) {
|
||||
const useWishlist = ({ includeProducts }: UseWishlistOptions = {}) => {
|
||||
return { data: null }
|
||||
}
|
||||
|
||||
useWishlist.extend = extendHook
|
||||
|
||||
return useWishlist
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
21
packages/swell/tsconfig.json
Normal file
21
packages/swell/tsconfig.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "esnext",
|
||||
"module": "esnext",
|
||||
"outDir": "dist",
|
||||
"baseUrl": "src",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"declaration": true,
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"esModuleInterop": true,
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"incremental": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
Reference in New Issue
Block a user