mirror of
https://github.com/vercel/commerce.git
synced 2025-05-18 07:26:59 +00:00
🤖 test cases for home and navbar component
This commit is contained in:
parent
a46057c5ef
commit
436e2ed8df
@ -17,7 +17,7 @@ Demo live at: [demo.vercel.store](https://demo.vercel.store/)
|
||||
- Kibo Commerce Demo: https://kibocommerce.vercel.store/
|
||||
- Commerce.js Demo: https://commercejs.vercel.store/
|
||||
|
||||
## Run minimal version locally
|
||||
## Run minimal version locally
|
||||
|
||||
> To run a minimal version of Next.js Commerce you can start with the default local provider `@vercel/commerce-local` that has disabled all features (cart, auth) and use static files for the backend
|
||||
|
||||
@ -25,7 +25,8 @@ Demo live at: [demo.vercel.store](https://demo.vercel.store/)
|
||||
yarn # run this comman in root folder of the mono repo
|
||||
yarn dev
|
||||
```
|
||||
> If you encounter any problems while installing and running for the first time, please see the Troubleshoot section
|
||||
|
||||
> If you encounter any problems while installing and running for the first time, please see the Troubleshoot section
|
||||
|
||||
## Features
|
||||
|
||||
|
5
cypress.json
Normal file
5
cypress.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"baseUrl": "http://localhost:3000",
|
||||
"viewportHeight": 1000,
|
||||
"viewportWidth": 1280
|
||||
}
|
5
cypress/fixtures/example.json
Normal file
5
cypress/fixtures/example.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "Using fixtures to represent data",
|
||||
"email": "hello@cypress.io",
|
||||
"body": "Fixtures are a great way to mock data for responses to routes"
|
||||
}
|
18
cypress/integration/header.spec.js
Normal file
18
cypress/integration/header.spec.js
Normal file
@ -0,0 +1,18 @@
|
||||
describe('Header', () => {
|
||||
beforeEach(() => {
|
||||
cy.visit('/')
|
||||
})
|
||||
|
||||
it('links to the correct pages', () => {
|
||||
cy.getBySel('logo').click()
|
||||
cy.location('pathname').should('eq', '/')
|
||||
|
||||
cy.getBySel('nav-link-search').click()
|
||||
cy.location('pathname').should('eq', '/search')
|
||||
|
||||
cy.getBySel('nav-link-home-page').click({ multiple: true })
|
||||
cy.location('pathname').should('eq', '/search/featured')
|
||||
})
|
||||
|
||||
it('the search bar returns the correct search results', () => {})
|
||||
})
|
29
cypress/integration/home.spec.js
Normal file
29
cypress/integration/home.spec.js
Normal file
@ -0,0 +1,29 @@
|
||||
describe('Home Page', () => {
|
||||
it('displays all 3 products on the home page', () => {
|
||||
cy.visit('/')
|
||||
|
||||
cy.getBySel('product-tag')
|
||||
.eq(0)
|
||||
.within(() => {
|
||||
cy.getBySel('product-name').should(
|
||||
'contain',
|
||||
'New Short Sleeve T-Shirt'
|
||||
)
|
||||
cy.getBySel('product-price').should('contain', '$25.00 USD')
|
||||
})
|
||||
|
||||
cy.getBySel('product-tag')
|
||||
.eq(1)
|
||||
.within(() => {
|
||||
cy.getBySel('product-name').should('contain', 'Lightweight Jacket')
|
||||
cy.getBySel('product-price').should('contain', '$249.99 USD')
|
||||
})
|
||||
|
||||
cy.getBySel('product-tag')
|
||||
.eq(2)
|
||||
.within(() => {
|
||||
cy.getBySel('product-name').should('contain', 'Shirt')
|
||||
cy.getBySel('product-price').should('contain', '$25.00 USD')
|
||||
})
|
||||
})
|
||||
})
|
22
cypress/plugins/index.js
Normal file
22
cypress/plugins/index.js
Normal file
@ -0,0 +1,22 @@
|
||||
/// <reference types="cypress" />
|
||||
// ***********************************************************
|
||||
// This example plugins/index.js can be used to load plugins
|
||||
//
|
||||
// You can change the location of this file or turn off loading
|
||||
// the plugins file with the 'pluginsFile' configuration option.
|
||||
//
|
||||
// You can read more here:
|
||||
// https://on.cypress.io/plugins-guide
|
||||
// ***********************************************************
|
||||
|
||||
// This function is called when a project is opened or re-opened (e.g. due to
|
||||
// the project's config changing)
|
||||
|
||||
/**
|
||||
* @type {Cypress.PluginConfig}
|
||||
*/
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
module.exports = (on, config) => {
|
||||
// `on` is used to hook into various events Cypress emits
|
||||
// `config` is the resolved Cypress config
|
||||
}
|
29
cypress/support/commands.js
Normal file
29
cypress/support/commands.js
Normal file
@ -0,0 +1,29 @@
|
||||
// ***********************************************
|
||||
// This example commands.js shows you how to
|
||||
// create various custom commands and overwrite
|
||||
// existing commands.
|
||||
//
|
||||
// For more comprehensive examples of custom
|
||||
// commands please read more here:
|
||||
// https://on.cypress.io/custom-commands
|
||||
// ***********************************************
|
||||
//
|
||||
//
|
||||
// -- This is a parent command --
|
||||
// Cypress.Commands.add('login', (email, password) => { ... })
|
||||
//
|
||||
//
|
||||
// -- This is a child command --
|
||||
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
|
||||
//
|
||||
//
|
||||
// -- This is a dual command --
|
||||
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
|
||||
//
|
||||
//
|
||||
// -- This will overwrite an existing command --
|
||||
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
|
||||
|
||||
Cypress.Commands.add('getBySel', (selector, ...args) => {
|
||||
return cy.get(`[data-test=${selector}]`, ...args)
|
||||
})
|
20
cypress/support/index.js
Normal file
20
cypress/support/index.js
Normal file
@ -0,0 +1,20 @@
|
||||
// ***********************************************************
|
||||
// This example support/index.js is processed and
|
||||
// loaded automatically before your test files.
|
||||
//
|
||||
// This is a great place to put global configuration and
|
||||
// behavior that modifies Cypress.
|
||||
//
|
||||
// You can change the location of this file or turn off
|
||||
// automatically serving support files with the
|
||||
// 'supportFile' configuration option.
|
||||
//
|
||||
// You can read more here:
|
||||
// https://on.cypress.io/configuration
|
||||
// ***********************************************************
|
||||
|
||||
// Import commands.js using ES2015 syntax:
|
||||
import './commands'
|
||||
|
||||
// Alternatively you can use CommonJS syntax:
|
||||
// require('./commands')
|
25442
package-lock.json
generated
Normal file
25442
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -11,9 +11,12 @@
|
||||
"dev": "turbo run dev",
|
||||
"start": "turbo run start",
|
||||
"types": "turbo run types",
|
||||
"prettier-fix": "prettier --write ."
|
||||
"prettier-fix": "prettier --write .",
|
||||
"cypress:open": "cypress open",
|
||||
"cypress:run": "cypress run"
|
||||
},
|
||||
"devDependencies": {
|
||||
"cypress": "^9.5.4",
|
||||
"husky": "^7.0.4",
|
||||
"prettier": "^2.5.1",
|
||||
"turbo": "^1.1.2"
|
||||
|
@ -42,7 +42,7 @@ const getCheckout: CheckoutEndpoint['handlers']['getCheckout'] = async ({
|
||||
store_hash: config.storeHash,
|
||||
customer_id: customerId,
|
||||
channel_id: config.storeChannelId,
|
||||
redirect_to: data.checkout_url.replace(config.storeUrl, ""),
|
||||
redirect_to: data.checkout_url.replace(config.storeUrl, ''),
|
||||
}
|
||||
let token = jwt.sign(payload, config.storeApiClientSecret!, {
|
||||
algorithm: 'HS256',
|
||||
|
@ -4,8 +4,14 @@ import type {
|
||||
HookFetcherContext,
|
||||
} from '@vercel/commerce/utils/types'
|
||||
import { ValidationError } from '@vercel/commerce/utils/errors'
|
||||
import useRemoveItem, { UseRemoveItem } from '@vercel/commerce/cart/use-remove-item'
|
||||
import type { Cart, LineItem, RemoveItemHook } from '@vercel/commerce/types/cart'
|
||||
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'
|
||||
|
||||
export type RemoveItemFn<T = any> = T extends LineItem
|
||||
|
@ -5,7 +5,9 @@ import type {
|
||||
HookFetcherContext,
|
||||
} from '@vercel/commerce/utils/types'
|
||||
import { ValidationError } from '@vercel/commerce/utils/errors'
|
||||
import useUpdateItem, { UseUpdateItem } from '@vercel/commerce/cart/use-update-item'
|
||||
import useUpdateItem, {
|
||||
UseUpdateItem,
|
||||
} from '@vercel/commerce/cart/use-update-item'
|
||||
import type { LineItem, UpdateItemHook } from '@vercel/commerce/types/cart'
|
||||
import { handler as removeItemHandler } from './use-remove-item'
|
||||
import useCart from './use-cart'
|
||||
|
@ -1,5 +1,7 @@
|
||||
import { SWRHook } from '@vercel/commerce/utils/types'
|
||||
import useCheckout, { UseCheckout } from '@vercel/commerce/checkout/use-checkout'
|
||||
import useCheckout, {
|
||||
UseCheckout,
|
||||
} from '@vercel/commerce/checkout/use-checkout'
|
||||
|
||||
export default useCheckout as UseCheckout<typeof handler>
|
||||
|
||||
|
@ -1,4 +1,6 @@
|
||||
import useAddItem, { UseAddItem } from '@vercel/commerce/customer/address/use-add-item'
|
||||
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>
|
||||
|
@ -1,4 +1,6 @@
|
||||
import useAddItem, { UseAddItem } from '@vercel/commerce/customer/card/use-add-item'
|
||||
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>
|
||||
|
@ -1,5 +1,7 @@
|
||||
import { SWRHook } from '@vercel/commerce/utils/types'
|
||||
import useCustomer, { UseCustomer } from '@vercel/commerce/customer/use-customer'
|
||||
import useCustomer, {
|
||||
UseCustomer,
|
||||
} from '@vercel/commerce/customer/use-customer'
|
||||
import type { CustomerHook } from '../types/customer'
|
||||
|
||||
export default useCustomer as UseCustomer<typeof handler>
|
||||
|
@ -1,4 +1,7 @@
|
||||
import { getCommerceProvider, useCommerce as useCoreCommerce } from '@vercel/commerce'
|
||||
import {
|
||||
getCommerceProvider,
|
||||
useCommerce as useCoreCommerce,
|
||||
} from '@vercel/commerce'
|
||||
import { bigcommerceProvider, BigcommerceProvider } from './provider'
|
||||
|
||||
export { bigcommerceProvider }
|
||||
|
@ -68,7 +68,10 @@ Then, open [/site/.env.template](/site/.env.template) and add the provider name
|
||||
Using BigCommerce as an example. The first thing to do is export a `CommerceProvider` component that includes a `provider` object with all the handlers that can be used for hooks:
|
||||
|
||||
```tsx
|
||||
import { getCommerceProvider, useCommerce as useCoreCommerce } from '@vercel/commerce'
|
||||
import {
|
||||
getCommerceProvider,
|
||||
useCommerce as useCoreCommerce,
|
||||
} from '@vercel/commerce'
|
||||
import { bigcommerceProvider, BigcommerceProvider } from './provider'
|
||||
|
||||
export { bigcommerceProvider }
|
||||
@ -212,25 +215,26 @@ export const handler: MutationHook<AddItemHook> = {
|
||||
```
|
||||
|
||||
## Showing progress and features
|
||||
|
||||
When creating a PR for a new provider, include this list in the PR description and mark the progress as you push so we can organize the code review. Not all points are required (but advised) so make sure to keep the list up to date.
|
||||
|
||||
**Status**
|
||||
|
||||
* [ ] CommerceProvider
|
||||
* [ ] Schema & TS types
|
||||
* [ ] API Operations - Get all collections
|
||||
* [ ] API Operations - Get all pages
|
||||
* [ ] API Operations - Get all products
|
||||
* [ ] API Operations - Get page
|
||||
* [ ] API Operations - Get product
|
||||
* [ ] API Operations - Get Shop Info (categories and vendors working — `vendors` query still a WIP PR on Reaction)
|
||||
* [ ] Hook - Add Item
|
||||
* [ ] Hook - Remove Item
|
||||
* [ ] Hook - Update Item
|
||||
* [ ] Hook - Get Cart (account-tied carts working, anonymous carts working, cart reconciliation working)
|
||||
* [ ] Auth (based on a WIP PR on Reaction - still need to implement refresh tokens)
|
||||
* [ ] Customer information
|
||||
* [ ] Product attributes - Size, Colors
|
||||
* [ ] Custom checkout
|
||||
* [ ] Typing (in progress)
|
||||
* [ ] Tests
|
||||
- [ ] CommerceProvider
|
||||
- [ ] Schema & TS types
|
||||
- [ ] API Operations - Get all collections
|
||||
- [ ] API Operations - Get all pages
|
||||
- [ ] API Operations - Get all products
|
||||
- [ ] API Operations - Get page
|
||||
- [ ] API Operations - Get product
|
||||
- [ ] API Operations - Get Shop Info (categories and vendors working — `vendors` query still a WIP PR on Reaction)
|
||||
- [ ] Hook - Add Item
|
||||
- [ ] Hook - Remove Item
|
||||
- [ ] Hook - Update Item
|
||||
- [ ] Hook - Get Cart (account-tied carts working, anonymous carts working, cart reconciliation working)
|
||||
- [ ] Auth (based on a WIP PR on Reaction - still need to implement refresh tokens)
|
||||
- [ ] Customer information
|
||||
- [ ] Product attributes - Size, Colors
|
||||
- [ ] Custom checkout
|
||||
- [ ] Typing (in progress)
|
||||
- [ ] Tests
|
||||
|
@ -3,58 +3,60 @@ import { CommerceAPIError } from '../utils/errors'
|
||||
import isAllowedOperation from '../utils/is-allowed-operation'
|
||||
import type { GetAPISchema } from '..'
|
||||
|
||||
const cartEndpoint: GetAPISchema<any, CartSchema<any>>['endpoint']['handler'] =
|
||||
async (ctx) => {
|
||||
const { req, res, handlers, config } = ctx
|
||||
const cartEndpoint: GetAPISchema<
|
||||
any,
|
||||
CartSchema<any>
|
||||
>['endpoint']['handler'] = async (ctx) => {
|
||||
const { req, res, handlers, config } = ctx
|
||||
|
||||
if (
|
||||
!isAllowedOperation(req, res, {
|
||||
GET: handlers['getCart'],
|
||||
POST: handlers['addItem'],
|
||||
PUT: handlers['updateItem'],
|
||||
DELETE: handlers['removeItem'],
|
||||
})
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
const { cookies } = req
|
||||
const cartId = cookies[config.cartCookie]
|
||||
|
||||
try {
|
||||
// Return current cart info
|
||||
if (req.method === 'GET') {
|
||||
const body = { cartId }
|
||||
return await handlers['getCart']({ ...ctx, body })
|
||||
}
|
||||
|
||||
// Create or add an item to the cart
|
||||
if (req.method === 'POST') {
|
||||
const body = { ...req.body, cartId }
|
||||
return await handlers['addItem']({ ...ctx, body })
|
||||
}
|
||||
|
||||
// Update item in cart
|
||||
if (req.method === 'PUT') {
|
||||
const body = { ...req.body, cartId }
|
||||
return await handlers['updateItem']({ ...ctx, body })
|
||||
}
|
||||
|
||||
// Remove an item from the cart
|
||||
if (req.method === 'DELETE') {
|
||||
const body = { ...req.body, cartId }
|
||||
return await handlers['removeItem']({ ...ctx, body })
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
|
||||
const message =
|
||||
error instanceof CommerceAPIError
|
||||
? 'An unexpected error ocurred with the Commerce API'
|
||||
: 'An unexpected error ocurred'
|
||||
|
||||
res.status(500).json({ data: null, errors: [{ message }] })
|
||||
}
|
||||
if (
|
||||
!isAllowedOperation(req, res, {
|
||||
GET: handlers['getCart'],
|
||||
POST: handlers['addItem'],
|
||||
PUT: handlers['updateItem'],
|
||||
DELETE: handlers['removeItem'],
|
||||
})
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
const { cookies } = req
|
||||
const cartId = cookies[config.cartCookie]
|
||||
|
||||
try {
|
||||
// Return current cart info
|
||||
if (req.method === 'GET') {
|
||||
const body = { cartId }
|
||||
return await handlers['getCart']({ ...ctx, body })
|
||||
}
|
||||
|
||||
// Create or add an item to the cart
|
||||
if (req.method === 'POST') {
|
||||
const body = { ...req.body, cartId }
|
||||
return await handlers['addItem']({ ...ctx, body })
|
||||
}
|
||||
|
||||
// Update item in cart
|
||||
if (req.method === 'PUT') {
|
||||
const body = { ...req.body, cartId }
|
||||
return await handlers['updateItem']({ ...ctx, body })
|
||||
}
|
||||
|
||||
// Remove an item from the cart
|
||||
if (req.method === 'DELETE') {
|
||||
const body = { ...req.body, cartId }
|
||||
return await handlers['removeItem']({ ...ctx, body })
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
|
||||
const message =
|
||||
error instanceof CommerceAPIError
|
||||
? 'An unexpected error ocurred with the Commerce API'
|
||||
: 'An unexpected error ocurred'
|
||||
|
||||
res.status(500).json({ data: null, errors: [{ message }] })
|
||||
}
|
||||
}
|
||||
|
||||
export default cartEndpoint
|
||||
|
@ -3,33 +3,35 @@ import { CommerceAPIError } from '../utils/errors'
|
||||
import isAllowedOperation from '../utils/is-allowed-operation'
|
||||
import type { GetAPISchema } from '..'
|
||||
|
||||
const logoutEndpoint: GetAPISchema<any, LogoutSchema>['endpoint']['handler'] =
|
||||
async (ctx) => {
|
||||
const { req, res, handlers } = ctx
|
||||
const logoutEndpoint: GetAPISchema<
|
||||
any,
|
||||
LogoutSchema
|
||||
>['endpoint']['handler'] = async (ctx) => {
|
||||
const { req, res, handlers } = ctx
|
||||
|
||||
if (
|
||||
!isAllowedOperation(req, res, {
|
||||
GET: handlers['logout'],
|
||||
})
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const redirectTo = req.query.redirect_to
|
||||
const body = typeof redirectTo === 'string' ? { redirectTo } : {}
|
||||
|
||||
return await handlers['logout']({ ...ctx, body })
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
|
||||
const message =
|
||||
error instanceof CommerceAPIError
|
||||
? 'An unexpected error ocurred with the Commerce API'
|
||||
: 'An unexpected error ocurred'
|
||||
|
||||
res.status(500).json({ data: null, errors: [{ message }] })
|
||||
}
|
||||
if (
|
||||
!isAllowedOperation(req, res, {
|
||||
GET: handlers['logout'],
|
||||
})
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const redirectTo = req.query.redirect_to
|
||||
const body = typeof redirectTo === 'string' ? { redirectTo } : {}
|
||||
|
||||
return await handlers['logout']({ ...ctx, body })
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
|
||||
const message =
|
||||
error instanceof CommerceAPIError
|
||||
? 'An unexpected error ocurred with the Commerce API'
|
||||
: 'An unexpected error ocurred'
|
||||
|
||||
res.status(500).json({ data: null, errors: [{ message }] })
|
||||
}
|
||||
}
|
||||
|
||||
export default logoutEndpoint
|
||||
|
@ -3,34 +3,36 @@ import { CommerceAPIError } from '../utils/errors'
|
||||
import isAllowedOperation from '../utils/is-allowed-operation'
|
||||
import type { GetAPISchema } from '..'
|
||||
|
||||
const signupEndpoint: GetAPISchema<any, SignupSchema>['endpoint']['handler'] =
|
||||
async (ctx) => {
|
||||
const { req, res, handlers, config } = ctx
|
||||
const signupEndpoint: GetAPISchema<
|
||||
any,
|
||||
SignupSchema
|
||||
>['endpoint']['handler'] = async (ctx) => {
|
||||
const { req, res, handlers, config } = ctx
|
||||
|
||||
if (
|
||||
!isAllowedOperation(req, res, {
|
||||
POST: handlers['signup'],
|
||||
})
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
const { cookies } = req
|
||||
const cartId = cookies[config.cartCookie]
|
||||
|
||||
try {
|
||||
const body = { ...req.body, cartId }
|
||||
return await handlers['signup']({ ...ctx, body })
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
|
||||
const message =
|
||||
error instanceof CommerceAPIError
|
||||
? 'An unexpected error ocurred with the Commerce API'
|
||||
: 'An unexpected error ocurred'
|
||||
|
||||
res.status(500).json({ data: null, errors: [{ message }] })
|
||||
}
|
||||
if (
|
||||
!isAllowedOperation(req, res, {
|
||||
POST: handlers['signup'],
|
||||
})
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
const { cookies } = req
|
||||
const cartId = cookies[config.cartCookie]
|
||||
|
||||
try {
|
||||
const body = { ...req.body, cartId }
|
||||
return await handlers['signup']({ ...ctx, body })
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
|
||||
const message =
|
||||
error instanceof CommerceAPIError
|
||||
? 'An unexpected error ocurred with the Commerce API'
|
||||
: 'An unexpected error ocurred'
|
||||
|
||||
res.status(500).json({ data: null, errors: [{ message }] })
|
||||
}
|
||||
}
|
||||
|
||||
export default signupEndpoint
|
||||
|
@ -1,7 +1,9 @@
|
||||
import { useCallback } from 'react'
|
||||
import type { MutationHook } from '@vercel/commerce/utils/types'
|
||||
import type { RemoveItemHook } from '@vercel/commerce/types/cart'
|
||||
import useRemoveItem, { UseRemoveItem } from '@vercel/commerce/cart/use-remove-item'
|
||||
import useRemoveItem, {
|
||||
UseRemoveItem,
|
||||
} from '@vercel/commerce/cart/use-remove-item'
|
||||
import type { CommercejsCart } from '../types/cart'
|
||||
import { normalizeCart } from '../utils/normalize-cart'
|
||||
import useCart from './use-cart'
|
||||
|
@ -6,7 +6,9 @@ import type {
|
||||
import { ValidationError } from '@vercel/commerce/utils/errors'
|
||||
import debounce from 'lodash.debounce'
|
||||
import { useCallback } from 'react'
|
||||
import useUpdateItem, { UseUpdateItem } from '@vercel/commerce/cart/use-update-item'
|
||||
import useUpdateItem, {
|
||||
UseUpdateItem,
|
||||
} from '@vercel/commerce/cart/use-update-item'
|
||||
import type { CommercejsCart } from '../types/cart'
|
||||
import { normalizeCart } from '../utils/normalize-cart'
|
||||
import useCart from './use-cart'
|
||||
|
@ -2,7 +2,9 @@ import type { GetCheckoutHook } from '@vercel/commerce/types/checkout'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import { SWRHook } from '@vercel/commerce/utils/types'
|
||||
import useCheckout, { UseCheckout } from '@vercel/commerce/checkout/use-checkout'
|
||||
import useCheckout, {
|
||||
UseCheckout,
|
||||
} from '@vercel/commerce/checkout/use-checkout'
|
||||
import useSubmitCheckout from './use-submit-checkout'
|
||||
import { useCheckoutContext } from '@components/checkout/context'
|
||||
|
||||
|
@ -1,7 +1,9 @@
|
||||
import type { AddItemHook } from '@vercel/commerce/types/customer/address'
|
||||
import type { MutationHook } from '@vercel/commerce/utils/types'
|
||||
import { useCallback } from 'react'
|
||||
import useAddItem, { UseAddItem } from '@vercel/commerce/customer/address/use-add-item'
|
||||
import useAddItem, {
|
||||
UseAddItem,
|
||||
} from '@vercel/commerce/customer/address/use-add-item'
|
||||
import { useCheckoutContext } from '@components/checkout/context'
|
||||
|
||||
export default useAddItem as UseAddItem<typeof handler>
|
||||
|
@ -1,7 +1,9 @@
|
||||
import type { AddItemHook } from '@vercel/commerce/types/customer/card'
|
||||
import type { MutationHook } from '@vercel/commerce/utils/types'
|
||||
import { useCallback } from 'react'
|
||||
import useAddItem, { UseAddItem } from '@vercel/commerce/customer/card/use-add-item'
|
||||
import useAddItem, {
|
||||
UseAddItem,
|
||||
} from '@vercel/commerce/customer/card/use-add-item'
|
||||
import { useCheckoutContext } from '@components/checkout/context'
|
||||
|
||||
export default useAddItem as UseAddItem<typeof handler>
|
||||
|
@ -1,7 +1,9 @@
|
||||
import Cookies from 'js-cookie'
|
||||
import { decode } from 'jsonwebtoken'
|
||||
import { SWRHook } from '@vercel/commerce/utils/types'
|
||||
import useCustomer, { UseCustomer } from '@vercel/commerce/customer/use-customer'
|
||||
import useCustomer, {
|
||||
UseCustomer,
|
||||
} from '@vercel/commerce/customer/use-customer'
|
||||
import { CUSTOMER_COOKIE, API_URL } from '../constants'
|
||||
import type { CustomerHook } from '../types/customer'
|
||||
|
||||
|
@ -1,5 +1,8 @@
|
||||
import { commercejsProvider, CommercejsProvider } from './provider'
|
||||
import { getCommerceProvider, useCommerce as useCoreCommerce } from '@vercel/commerce'
|
||||
import {
|
||||
getCommerceProvider,
|
||||
useCommerce as useCoreCommerce,
|
||||
} from '@vercel/commerce'
|
||||
|
||||
export { commercejsProvider }
|
||||
export type { CommercejsProvider }
|
||||
|
@ -24,12 +24,12 @@ KIBO_AUTH_URL='https://home.mozu.com'
|
||||
- `KIBO_CLIENT_ID` - Unique Application (Client) ID of your Application
|
||||
- `KIBO_SHARED_SECRET` - Secret API key used to authenticate application/client id.
|
||||
|
||||
|
||||
Your Kibo Client ID and Shared Secret can be found from your [Kibo eCommerce Dev Center](https://mozu.com/login)
|
||||
|
||||
Visit [Kibo documentation](https://apidocs.kibong-perf.com/?spec=graphql#auth) for more details on API authentication
|
||||
|
||||
Based on the config, this integration will handle Authenticating your application against the Kibo API using the Kibo Client ID and Kibo Shared Secret.
|
||||
|
||||
## Contribute
|
||||
|
||||
Our commitment to Open Source can be found [here](https://vercel.com/oss).
|
||||
|
@ -1,21 +1,21 @@
|
||||
{
|
||||
"schema": {
|
||||
"https://t17194-s21127.dev10.kubedev.kibo-dev.com/graphql": {}
|
||||
},
|
||||
"generates": {
|
||||
"./schema.d.ts": {
|
||||
"plugins": ["typescript", "typescript-operations"],
|
||||
"config": {
|
||||
"scalars": {
|
||||
"ID": "string"
|
||||
}
|
||||
"schema": {
|
||||
"https://t17194-s21127.dev10.kubedev.kibo-dev.com/graphql": {}
|
||||
},
|
||||
"generates": {
|
||||
"./schema.d.ts": {
|
||||
"plugins": ["typescript", "typescript-operations"],
|
||||
"config": {
|
||||
"scalars": {
|
||||
"ID": "string"
|
||||
}
|
||||
},
|
||||
"./schema.graphql": {
|
||||
"plugins": ["schema-ast"]
|
||||
}
|
||||
},
|
||||
"hooks": {
|
||||
"afterAllFileWrite": ["prettier --write"]
|
||||
"./schema.graphql": {
|
||||
"plugins": ["schema-ast"]
|
||||
}
|
||||
},
|
||||
"hooks": {
|
||||
"afterAllFileWrite": ["prettier --write"]
|
||||
}
|
||||
}
|
||||
|
10
packages/kibocommerce/schema.d.ts
vendored
10
packages/kibocommerce/schema.d.ts
vendored
@ -2,10 +2,12 @@ export type Maybe<T> = T | null
|
||||
export type Exact<T extends { [key: string]: unknown }> = {
|
||||
[K in keyof T]: T[K]
|
||||
}
|
||||
export type MakeOptional<T, K extends keyof T> = Omit<T, K> &
|
||||
{ [SubKey in K]?: Maybe<T[SubKey]> }
|
||||
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> &
|
||||
{ [SubKey in K]: Maybe<T[SubKey]> }
|
||||
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & {
|
||||
[SubKey in K]?: Maybe<T[SubKey]>
|
||||
}
|
||||
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & {
|
||||
[SubKey in K]: Maybe<T[SubKey]>
|
||||
}
|
||||
/** All built-in and custom scalars, mapped to their actual values */
|
||||
export type Scalars = {
|
||||
ID: string
|
||||
|
@ -74,7 +74,7 @@ const addItem: CartEndpoint['handlers']['addItem'] = async ({
|
||||
|
||||
if (!cookieHandler.getAccessToken()) {
|
||||
let anonymousShopperTokenResponse = await cookieHandler.getAnonymousToken()
|
||||
accessToken = anonymousShopperTokenResponse.accessToken;
|
||||
accessToken = anonymousShopperTokenResponse.accessToken
|
||||
} else {
|
||||
accessToken = cookieHandler.getAccessToken()
|
||||
}
|
||||
|
@ -16,7 +16,8 @@ const getCart: CartEndpoint['handlers']['getCart'] = async ({
|
||||
let accessToken = null
|
||||
|
||||
if (!cookieHandler.getAccessToken()) {
|
||||
let anonymousShopperTokenResponse = await cookieHandler.getAnonymousToken()
|
||||
let anonymousShopperTokenResponse =
|
||||
await cookieHandler.getAnonymousToken()
|
||||
const response = anonymousShopperTokenResponse.response
|
||||
accessToken = anonymousShopperTokenResponse.accessToken
|
||||
cookieHandler.setAnonymousShopperCookie(response)
|
||||
|
@ -1,8 +1,8 @@
|
||||
import { GetAPISchema, createEndpoint } from '@vercel/commerce/api'
|
||||
import cartEndpoint from '@vercel/commerce/api/endpoints/cart'
|
||||
import type { KiboCommerceAPI } from '../..'
|
||||
import getCart from './get-cart';
|
||||
import addItem from './add-item';
|
||||
import getCart from './get-cart'
|
||||
import addItem from './add-item'
|
||||
import updateItem from './update-item'
|
||||
import removeItem from './remove-item'
|
||||
|
||||
|
@ -2,16 +2,16 @@ import { Product } from '@vercel/commerce/types/product'
|
||||
import { ProductsEndpoint } from '.'
|
||||
import productSearchQuery from '../../../queries/product-search-query'
|
||||
import { buildProductSearchVars } from '../../../../lib/product-search-vars'
|
||||
import {normalizeProduct} from '../../../../lib/normalize'
|
||||
import { normalizeProduct } from '../../../../lib/normalize'
|
||||
|
||||
const getProducts: ProductsEndpoint['handlers']['getProducts'] = async ({
|
||||
res,
|
||||
body: { search, categoryId, brandId, sort },
|
||||
config,
|
||||
}) => {
|
||||
const pageSize = 100;
|
||||
const filters = {};
|
||||
const startIndex = 0;
|
||||
const pageSize = 100
|
||||
const filters = {}
|
||||
const startIndex = 0
|
||||
const variables = buildProductSearchVars({
|
||||
categoryCode: categoryId,
|
||||
pageSize,
|
||||
@ -20,12 +20,14 @@ const getProducts: ProductsEndpoint['handlers']['getProducts'] = async ({
|
||||
filters,
|
||||
startIndex,
|
||||
})
|
||||
const {data} = await config.fetch(productSearchQuery, { variables });
|
||||
const found = data?.products?.items?.length > 0 ? true : false;
|
||||
let productsResponse= data?.products?.items.map((item: any) =>normalizeProduct(item,config));
|
||||
const products: Product[] = found ? productsResponse : [];
|
||||
const { data } = await config.fetch(productSearchQuery, { variables })
|
||||
const found = data?.products?.items?.length > 0 ? true : false
|
||||
let productsResponse = data?.products?.items.map((item: any) =>
|
||||
normalizeProduct(item, config)
|
||||
)
|
||||
const products: Product[] = found ? productsResponse : []
|
||||
|
||||
res.status(200).json({ data: { products, found } });
|
||||
res.status(200).json({ data: { products, found } })
|
||||
}
|
||||
|
||||
export default getProducts
|
||||
|
@ -3,34 +3,31 @@ import type { CustomerEndpoint } from '.'
|
||||
import { getCustomerAccountQuery } from '../../queries/get-customer-account-query'
|
||||
import { normalizeCustomer } from '../../../lib/normalize'
|
||||
|
||||
const getLoggedInCustomer: CustomerEndpoint['handlers']['getLoggedInCustomer'] = async ({
|
||||
req,
|
||||
res,
|
||||
config,
|
||||
}) => {
|
||||
const cookieHandler = new CookieHandler(config, req, res)
|
||||
let accessToken = cookieHandler.getAccessToken();
|
||||
const getLoggedInCustomer: CustomerEndpoint['handlers']['getLoggedInCustomer'] =
|
||||
async ({ req, res, config }) => {
|
||||
const cookieHandler = new CookieHandler(config, req, res)
|
||||
let accessToken = cookieHandler.getAccessToken()
|
||||
|
||||
if (!cookieHandler.isShopperCookieAnonymous()) {
|
||||
const { data } = await config.fetch(getCustomerAccountQuery, undefined, {
|
||||
headers: {
|
||||
'x-vol-user-claims': accessToken,
|
||||
},
|
||||
})
|
||||
|
||||
const customer = normalizeCustomer(data?.customerAccount)
|
||||
|
||||
if (!customer.id) {
|
||||
return res.status(400).json({
|
||||
data: null,
|
||||
errors: [{ message: 'Customer not found', code: 'not_found' }],
|
||||
if (!cookieHandler.isShopperCookieAnonymous()) {
|
||||
const { data } = await config.fetch(getCustomerAccountQuery, undefined, {
|
||||
headers: {
|
||||
'x-vol-user-claims': accessToken,
|
||||
},
|
||||
})
|
||||
|
||||
const customer = normalizeCustomer(data?.customerAccount)
|
||||
|
||||
if (!customer.id) {
|
||||
return res.status(400).json({
|
||||
data: null,
|
||||
errors: [{ message: 'Customer not found', code: 'not_found' }],
|
||||
})
|
||||
}
|
||||
|
||||
return res.status(200).json({ data: { customer } })
|
||||
}
|
||||
|
||||
return res.status(200).json({ data: { customer } })
|
||||
res.status(200).json({ data: null })
|
||||
}
|
||||
|
||||
res.status(200).json({ data: null })
|
||||
}
|
||||
|
||||
export default getLoggedInCustomer
|
||||
|
@ -15,6 +15,4 @@ const loginApi = createEndpoint<LoginAPI>({
|
||||
handlers,
|
||||
})
|
||||
|
||||
export default loginApi;
|
||||
|
||||
|
||||
export default loginApi
|
||||
|
@ -1,7 +1,7 @@
|
||||
import { FetcherError } from '@vercel/commerce/utils/errors'
|
||||
import type { LoginEndpoint } from '.'
|
||||
import { loginMutation } from '../../mutations/login-mutation'
|
||||
import { prepareSetCookie } from '../../../lib/prepare-set-cookie';
|
||||
import { prepareSetCookie } from '../../../lib/prepare-set-cookie'
|
||||
import { setCookies } from '../../../lib/set-cookie'
|
||||
import { getCookieExpirationDate } from '../../../lib/get-cookie-expiration-date'
|
||||
|
||||
@ -14,7 +14,6 @@ const login: LoginEndpoint['handlers']['login'] = async ({
|
||||
config,
|
||||
commerce,
|
||||
}) => {
|
||||
|
||||
if (!(email && password)) {
|
||||
return res.status(400).json({
|
||||
data: null,
|
||||
@ -22,23 +21,23 @@ const login: LoginEndpoint['handlers']['login'] = async ({
|
||||
})
|
||||
}
|
||||
|
||||
let response;
|
||||
let response
|
||||
try {
|
||||
|
||||
const variables = { loginInput : { username: email, password }};
|
||||
response = await config.fetch(loginMutation, { variables })
|
||||
const { account: token } = response.data;
|
||||
const variables = { loginInput: { username: email, password } }
|
||||
response = await config.fetch(loginMutation, { variables })
|
||||
const { account: token } = response.data
|
||||
|
||||
// Set Cookie
|
||||
const cookieExpirationDate = getCookieExpirationDate(config.customerCookieMaxAgeInDays)
|
||||
const cookieExpirationDate = getCookieExpirationDate(
|
||||
config.customerCookieMaxAgeInDays
|
||||
)
|
||||
|
||||
const authCookie = prepareSetCookie(
|
||||
config.customerCookie,
|
||||
JSON.stringify(token),
|
||||
token.accessTokenExpiration ? { expires: cookieExpirationDate }: {},
|
||||
token.accessTokenExpiration ? { expires: cookieExpirationDate } : {}
|
||||
)
|
||||
setCookies(res, [authCookie])
|
||||
|
||||
} catch (error) {
|
||||
// Check if the email and password didn't match an existing account
|
||||
if (
|
||||
|
@ -1,6 +1,6 @@
|
||||
import type { LogoutEndpoint } from '.'
|
||||
import {prepareSetCookie} from '../../../lib/prepare-set-cookie';
|
||||
import {setCookies} from '../../../lib/set-cookie'
|
||||
import { prepareSetCookie } from '../../../lib/prepare-set-cookie'
|
||||
import { setCookies } from '../../../lib/set-cookie'
|
||||
|
||||
const logout: LogoutEndpoint['handlers']['logout'] = async ({
|
||||
res,
|
||||
@ -8,8 +8,11 @@ const logout: LogoutEndpoint['handlers']['logout'] = async ({
|
||||
config,
|
||||
}) => {
|
||||
// Remove the cookie
|
||||
const authCookie = prepareSetCookie(config.customerCookie,'',{ maxAge: -1, path: '/' })
|
||||
setCookies(res, [authCookie])
|
||||
const authCookie = prepareSetCookie(config.customerCookie, '', {
|
||||
maxAge: -1,
|
||||
path: '/',
|
||||
})
|
||||
setCookies(res, [authCookie])
|
||||
|
||||
// Only allow redirects to a relative URL
|
||||
if (redirectTo?.startsWith('/')) {
|
||||
|
@ -1,7 +1,10 @@
|
||||
import { FetcherError } from '@vercel/commerce/utils/errors'
|
||||
import type { SignupEndpoint } from '.'
|
||||
import { registerUserMutation, registerUserLoginMutation } from '../../mutations/signup-mutation'
|
||||
import { prepareSetCookie } from '../../../lib/prepare-set-cookie';
|
||||
import {
|
||||
registerUserMutation,
|
||||
registerUserLoginMutation,
|
||||
} from '../../mutations/signup-mutation'
|
||||
import { prepareSetCookie } from '../../../lib/prepare-set-cookie'
|
||||
import { setCookies } from '../../../lib/set-cookie'
|
||||
import { getCookieExpirationDate } from '../../../lib/get-cookie-expiration-date'
|
||||
|
||||
@ -14,7 +17,6 @@ const signup: SignupEndpoint['handlers']['signup'] = async ({
|
||||
config,
|
||||
commerce,
|
||||
}) => {
|
||||
|
||||
if (!(email && password)) {
|
||||
return res.status(400).json({
|
||||
data: null,
|
||||
@ -22,48 +24,52 @@ const signup: SignupEndpoint['handlers']['signup'] = async ({
|
||||
})
|
||||
}
|
||||
|
||||
let response;
|
||||
let response
|
||||
try {
|
||||
|
||||
// Register user
|
||||
const registerUserVariables = {
|
||||
customerAccountInput: {
|
||||
emailAddress: email,
|
||||
firstName: firstName,
|
||||
lastName: lastName,
|
||||
acceptsMarketing: true,
|
||||
id: 0
|
||||
}
|
||||
emailAddress: email,
|
||||
firstName: firstName,
|
||||
lastName: lastName,
|
||||
acceptsMarketing: true,
|
||||
id: 0,
|
||||
},
|
||||
}
|
||||
|
||||
const registerUserResponse = await config.fetch(registerUserMutation, { variables: registerUserVariables})
|
||||
const accountId = registerUserResponse.data?.account?.id;
|
||||
const registerUserResponse = await config.fetch(registerUserMutation, {
|
||||
variables: registerUserVariables,
|
||||
})
|
||||
const accountId = registerUserResponse.data?.account?.id
|
||||
|
||||
// Login user
|
||||
const registerUserLoginVairables = {
|
||||
accountId: accountId,
|
||||
customerLoginInfoInput: {
|
||||
emailAddress: email,
|
||||
username: email,
|
||||
password: password,
|
||||
isImport: false
|
||||
}
|
||||
emailAddress: email,
|
||||
username: email,
|
||||
password: password,
|
||||
isImport: false,
|
||||
},
|
||||
}
|
||||
|
||||
response = await config.fetch(registerUserLoginMutation, { variables: registerUserLoginVairables})
|
||||
const { account: token } = response.data;
|
||||
response = await config.fetch(registerUserLoginMutation, {
|
||||
variables: registerUserLoginVairables,
|
||||
})
|
||||
const { account: token } = response.data
|
||||
|
||||
// Set Cookie
|
||||
const cookieExpirationDate = getCookieExpirationDate(config.customerCookieMaxAgeInDays)
|
||||
const cookieExpirationDate = getCookieExpirationDate(
|
||||
config.customerCookieMaxAgeInDays
|
||||
)
|
||||
|
||||
const authCookie = prepareSetCookie(
|
||||
config.customerCookie,
|
||||
JSON.stringify(token),
|
||||
token.accessTokenExpiration ? { expires: cookieExpirationDate }: {},
|
||||
token.accessTokenExpiration ? { expires: cookieExpirationDate } : {}
|
||||
)
|
||||
|
||||
setCookies(res, [authCookie])
|
||||
|
||||
} catch (error) {
|
||||
// Check if the email and password didn't match an existing account
|
||||
if (
|
||||
|
@ -11,7 +11,7 @@ const buildAddToWishlistVariables = ({
|
||||
productId,
|
||||
variantId,
|
||||
productResponse,
|
||||
wishlist
|
||||
wishlist,
|
||||
}: {
|
||||
productId: string
|
||||
variantId: string
|
||||
@ -23,7 +23,7 @@ const buildAddToWishlistVariables = ({
|
||||
const selectedOptions = product.variations?.find(
|
||||
(v: any) => v.productCode === variantId
|
||||
).options
|
||||
const quantity=1
|
||||
const quantity = 1
|
||||
let options: any[] = []
|
||||
selectedOptions?.forEach((each: any) => {
|
||||
product?.options
|
||||
@ -47,8 +47,8 @@ const buildAddToWishlistVariables = ({
|
||||
productCode: productId,
|
||||
variationProductCode: variantId ? variantId : null,
|
||||
options,
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@ -58,8 +58,10 @@ const addItem: WishlistEndpoint['handlers']['addItem'] = async ({
|
||||
config,
|
||||
commerce,
|
||||
}) => {
|
||||
const token = customerToken ? Buffer.from(customerToken, 'base64').toString('ascii'): null;
|
||||
const accessToken = token ? JSON.parse(token).accessToken : null;
|
||||
const token = customerToken
|
||||
? Buffer.from(customerToken, 'base64').toString('ascii')
|
||||
: null
|
||||
const accessToken = token ? JSON.parse(token).accessToken : null
|
||||
let result: { data?: any } = {}
|
||||
let wishlist: any
|
||||
|
||||
@ -70,8 +72,9 @@ const addItem: WishlistEndpoint['handlers']['addItem'] = async ({
|
||||
})
|
||||
}
|
||||
|
||||
const customerId = customerToken && (await getCustomerId({ customerToken, config }))
|
||||
const wishlistName= config.defaultWishlistName
|
||||
const customerId =
|
||||
customerToken && (await getCustomerId({ customerToken, config }))
|
||||
const wishlistName = config.defaultWishlistName
|
||||
|
||||
if (!customerId) {
|
||||
return res.status(400).json({
|
||||
@ -84,16 +87,21 @@ const addItem: WishlistEndpoint['handlers']['addItem'] = async ({
|
||||
variables: { customerId, wishlistName },
|
||||
config,
|
||||
})
|
||||
wishlist= wishlistResponse?.wishlist
|
||||
if(Object.keys(wishlist).length === 0) {
|
||||
const createWishlistResponse= await config.fetch(createWishlist, {variables: {
|
||||
wishlistInput: {
|
||||
customerAccountId: customerId,
|
||||
name: wishlistName
|
||||
}
|
||||
}
|
||||
}, {headers: { 'x-vol-user-claims': accessToken } })
|
||||
wishlist= createWishlistResponse?.data?.createWishlist
|
||||
wishlist = wishlistResponse?.wishlist
|
||||
if (Object.keys(wishlist).length === 0) {
|
||||
const createWishlistResponse = await config.fetch(
|
||||
createWishlist,
|
||||
{
|
||||
variables: {
|
||||
wishlistInput: {
|
||||
customerAccountId: customerId,
|
||||
name: wishlistName,
|
||||
},
|
||||
},
|
||||
},
|
||||
{ headers: { 'x-vol-user-claims': accessToken } }
|
||||
)
|
||||
wishlist = createWishlistResponse?.data?.createWishlist
|
||||
}
|
||||
|
||||
const productResponse = await config.fetch(getProductQuery, {
|
||||
@ -103,20 +111,31 @@ const addItem: WishlistEndpoint['handlers']['addItem'] = async ({
|
||||
const addItemToWishlistResponse = await config.fetch(
|
||||
addItemToWishlistMutation,
|
||||
{
|
||||
variables: buildAddToWishlistVariables({ ...item, productResponse, wishlist }),
|
||||
variables: buildAddToWishlistVariables({
|
||||
...item,
|
||||
productResponse,
|
||||
wishlist,
|
||||
}),
|
||||
},
|
||||
{ headers: { 'x-vol-user-claims': accessToken } }
|
||||
)
|
||||
|
||||
if(addItemToWishlistResponse?.data?.createWishlistItem){
|
||||
const wishlistResponse= await commerce.getCustomerWishlist({
|
||||
if (addItemToWishlistResponse?.data?.createWishlistItem) {
|
||||
const wishlistResponse = await commerce.getCustomerWishlist({
|
||||
variables: { customerId, wishlistName },
|
||||
config,
|
||||
})
|
||||
wishlist= wishlistResponse?.wishlist
|
||||
wishlist = wishlistResponse?.wishlist
|
||||
}
|
||||
|
||||
result = {
|
||||
data: {
|
||||
...wishlist,
|
||||
items: wishlist?.items?.map((item: any) =>
|
||||
normalizeWishlistItem(item, config)
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
result = { data: {...wishlist, items: wishlist?.items?.map((item:any) => normalizeWishlistItem(item, config))} }
|
||||
|
||||
res.status(200).json({ data: result?.data })
|
||||
}
|
||||
|
@ -11,8 +11,9 @@ const getWishlist: WishlistEndpoint['handlers']['getWishlist'] = async ({
|
||||
}) => {
|
||||
let result: { data?: any } = {}
|
||||
if (customerToken) {
|
||||
const customerId = customerToken && (await getCustomerId({ customerToken, config }))
|
||||
const wishlistName= config.defaultWishlistName
|
||||
const customerId =
|
||||
customerToken && (await getCustomerId({ customerToken, config }))
|
||||
const wishlistName = config.defaultWishlistName
|
||||
if (!customerId) {
|
||||
// If the customerToken is invalid, then this request is too
|
||||
return res.status(404).json({
|
||||
@ -26,7 +27,14 @@ const getWishlist: WishlistEndpoint['handlers']['getWishlist'] = async ({
|
||||
config,
|
||||
})
|
||||
|
||||
result = { data: {...wishlist, items: wishlist?.items?.map((item:any) => normalizeWishlistItem(item, config, includeProducts))} }
|
||||
result = {
|
||||
data: {
|
||||
...wishlist,
|
||||
items: wishlist?.items?.map((item: any) =>
|
||||
normalizeWishlistItem(item, config, includeProducts)
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
res.status(200).json({ data: result?.data ?? null })
|
||||
|
@ -10,50 +10,58 @@ const removeItem: WishlistEndpoint['handlers']['removeItem'] = async ({
|
||||
config,
|
||||
commerce,
|
||||
}) => {
|
||||
const token = customerToken ? Buffer.from(customerToken, 'base64').toString('ascii'): null;
|
||||
const accessToken = token ? JSON.parse(token).accessToken : null;
|
||||
const token = customerToken
|
||||
? Buffer.from(customerToken, 'base64').toString('ascii')
|
||||
: null
|
||||
const accessToken = token ? JSON.parse(token).accessToken : null
|
||||
let result: { data?: any } = {}
|
||||
let wishlist: any
|
||||
|
||||
const customerId = customerToken && (await getCustomerId({ customerToken, config }))
|
||||
const wishlistName= config.defaultWishlistName
|
||||
const customerId =
|
||||
customerToken && (await getCustomerId({ customerToken, config }))
|
||||
const wishlistName = config.defaultWishlistName
|
||||
const wishlistResponse = await commerce.getCustomerWishlist({
|
||||
variables: { customerId, wishlistName },
|
||||
config,
|
||||
})
|
||||
wishlist= wishlistResponse?.wishlist
|
||||
|
||||
wishlist = wishlistResponse?.wishlist
|
||||
|
||||
if (!wishlist || !itemId) {
|
||||
return res.status(400).json({
|
||||
data: null,
|
||||
errors: [{ message: 'Invalid request' }],
|
||||
})
|
||||
}
|
||||
const removedItem = wishlist?.items?.find(
|
||||
(item:any) => {
|
||||
return item.product.productCode === itemId;
|
||||
}
|
||||
);
|
||||
const removedItem = wishlist?.items?.find((item: any) => {
|
||||
return item.product.productCode === itemId
|
||||
})
|
||||
|
||||
const removeItemFromWishlistResponse = await config.fetch(
|
||||
removeItemFromWishlistMutation,
|
||||
{
|
||||
variables: {
|
||||
wishlistId: wishlist?.id,
|
||||
wishlistItemId: removedItem?.id
|
||||
wishlistItemId: removedItem?.id,
|
||||
},
|
||||
},
|
||||
{ headers: { 'x-vol-user-claims': accessToken } }
|
||||
)
|
||||
|
||||
if(removeItemFromWishlistResponse?.data?.deleteWishlistItem){
|
||||
const wishlistResponse= await commerce.getCustomerWishlist({
|
||||
if (removeItemFromWishlistResponse?.data?.deleteWishlistItem) {
|
||||
const wishlistResponse = await commerce.getCustomerWishlist({
|
||||
variables: { customerId, wishlistName },
|
||||
config,
|
||||
})
|
||||
wishlist= wishlistResponse?.wishlist
|
||||
wishlist = wishlistResponse?.wishlist
|
||||
}
|
||||
result = {
|
||||
data: {
|
||||
...wishlist,
|
||||
items: wishlist?.items?.map((item: any) =>
|
||||
normalizeWishlistItem(item, config)
|
||||
),
|
||||
},
|
||||
}
|
||||
result = { data: {...wishlist, items: wishlist?.items?.map((item:any) => normalizeWishlistItem(item, config))} }
|
||||
res.status(200).json({ data: result?.data })
|
||||
}
|
||||
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { productDetails } from '../fragments/productDetails'
|
||||
export const cartItemDetails = /*GraphQL*/`
|
||||
export const cartItemDetails = /*GraphQL*/ `
|
||||
fragment cartItemDetails on CartItem {
|
||||
id
|
||||
product {
|
||||
@ -8,4 +8,4 @@ fragment cartItemDetails on CartItem {
|
||||
quantity
|
||||
}
|
||||
${productDetails}
|
||||
`;
|
||||
`
|
||||
|
@ -1,11 +1,12 @@
|
||||
export const CategoryInfo = /* GraphQL */`
|
||||
fragment categoryInfo on PrCategory {
|
||||
export const CategoryInfo = /* GraphQL */ `
|
||||
fragment categoryInfo on PrCategory {
|
||||
categoryId
|
||||
categoryCode
|
||||
isDisplayed
|
||||
content {
|
||||
name
|
||||
slug
|
||||
description
|
||||
name
|
||||
slug
|
||||
description
|
||||
}
|
||||
}`;
|
||||
}
|
||||
`
|
||||
|
@ -1,98 +1,104 @@
|
||||
export const productPrices = /* GraphQL */`
|
||||
fragment productPrices on Product {
|
||||
price {
|
||||
export const productPrices = /* GraphQL */ `
|
||||
fragment productPrices on Product {
|
||||
price {
|
||||
price
|
||||
salePrice
|
||||
}
|
||||
priceRange {
|
||||
lower {
|
||||
price
|
||||
salePrice
|
||||
}
|
||||
priceRange {
|
||||
lower { price, salePrice}
|
||||
upper { price, salePrice }
|
||||
upper {
|
||||
price
|
||||
salePrice
|
||||
}
|
||||
}
|
||||
`;
|
||||
export const productAttributes = /* GraphQL */`
|
||||
fragment productAttributes on Product {
|
||||
properties {
|
||||
attributeFQN
|
||||
attributeDetail {
|
||||
name
|
||||
}
|
||||
isHidden
|
||||
values {
|
||||
value
|
||||
stringValue
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
export const productContent = /* GraphQL */`
|
||||
fragment productContent on Product {
|
||||
content {
|
||||
productFullDescription
|
||||
productShortDescription
|
||||
seoFriendlyUrl
|
||||
productName
|
||||
productImages {
|
||||
imageUrl
|
||||
imageLabel
|
||||
mediaType
|
||||
}
|
||||
`
|
||||
export const productAttributes = /* GraphQL */ `
|
||||
fragment productAttributes on Product {
|
||||
properties {
|
||||
attributeFQN
|
||||
attributeDetail {
|
||||
name
|
||||
}
|
||||
isHidden
|
||||
values {
|
||||
value
|
||||
stringValue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
export const productOptions = /* GraphQL */`
|
||||
fragment productOptions on Product {
|
||||
options {
|
||||
attributeFQN
|
||||
attributeDetail {
|
||||
name
|
||||
}
|
||||
isProductImageGroupSelector
|
||||
isRequired
|
||||
isMultiValue
|
||||
values {
|
||||
value
|
||||
isSelected
|
||||
deltaPrice
|
||||
stringValue
|
||||
`
|
||||
export const productContent = /* GraphQL */ `
|
||||
fragment productContent on Product {
|
||||
content {
|
||||
productFullDescription
|
||||
productShortDescription
|
||||
seoFriendlyUrl
|
||||
productName
|
||||
productImages {
|
||||
imageUrl
|
||||
imageLabel
|
||||
mediaType
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
export const productInfo = /* GraphQL */`
|
||||
fragment productInfo on Product {
|
||||
productCode
|
||||
productUsage
|
||||
`
|
||||
export const productOptions = /* GraphQL */ `
|
||||
fragment productOptions on Product {
|
||||
options {
|
||||
attributeFQN
|
||||
attributeDetail {
|
||||
name
|
||||
}
|
||||
isProductImageGroupSelector
|
||||
isRequired
|
||||
isMultiValue
|
||||
values {
|
||||
value
|
||||
isSelected
|
||||
deltaPrice
|
||||
stringValue
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export const productInfo = /* GraphQL */ `
|
||||
fragment productInfo on Product {
|
||||
productCode
|
||||
productUsage
|
||||
|
||||
purchasableState {
|
||||
isPurchasable
|
||||
}
|
||||
purchasableState {
|
||||
isPurchasable
|
||||
}
|
||||
|
||||
variations {
|
||||
productCode,
|
||||
options {
|
||||
__typename
|
||||
attributeFQN
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
categories {
|
||||
categoryCode
|
||||
categoryId
|
||||
content {
|
||||
name
|
||||
slug
|
||||
}
|
||||
}
|
||||
|
||||
...productPrices
|
||||
...productAttributes
|
||||
...productContent
|
||||
...productOptions
|
||||
}
|
||||
${productPrices}
|
||||
${productAttributes}
|
||||
${productContent}
|
||||
${productOptions}
|
||||
`;
|
||||
variations {
|
||||
productCode
|
||||
options {
|
||||
__typename
|
||||
attributeFQN
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
categories {
|
||||
categoryCode
|
||||
categoryId
|
||||
content {
|
||||
name
|
||||
slug
|
||||
}
|
||||
}
|
||||
|
||||
...productPrices
|
||||
...productAttributes
|
||||
...productContent
|
||||
...productOptions
|
||||
}
|
||||
${productPrices}
|
||||
${productAttributes}
|
||||
${productContent}
|
||||
${productOptions}
|
||||
`
|
||||
|
@ -25,6 +25,6 @@ export const productDetails = /* GraphQL */ `
|
||||
}
|
||||
categories {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
@ -1,32 +1,33 @@
|
||||
import { productInfo } from './product';
|
||||
import { productInfo } from './product'
|
||||
|
||||
export const searchFacets = /* GraphQL */`
|
||||
fragment searchFacets on Facet {
|
||||
export const searchFacets = /* GraphQL */ `
|
||||
fragment searchFacets on Facet {
|
||||
label
|
||||
field
|
||||
values {
|
||||
label
|
||||
value
|
||||
isApplied
|
||||
filterValue
|
||||
isDisplayed
|
||||
count
|
||||
label
|
||||
value
|
||||
isApplied
|
||||
filterValue
|
||||
isDisplayed
|
||||
count
|
||||
}
|
||||
}`;
|
||||
}
|
||||
`
|
||||
|
||||
export const searchResults = /* GraphQL */`
|
||||
fragment searchResults on ProductSearchResult {
|
||||
export const searchResults = /* GraphQL */ `
|
||||
fragment searchResults on ProductSearchResult {
|
||||
totalCount
|
||||
pageSize
|
||||
pageCount
|
||||
startIndex
|
||||
items {
|
||||
...productInfo
|
||||
...productInfo
|
||||
}
|
||||
facets {
|
||||
...searchFacets
|
||||
...searchFacets
|
||||
}
|
||||
}
|
||||
${searchFacets}
|
||||
${productInfo}
|
||||
`;
|
||||
}
|
||||
${searchFacets}
|
||||
${productInfo}
|
||||
`
|
||||
|
@ -15,10 +15,10 @@ export interface KiboCommerceConfig extends CommerceAPIConfig {
|
||||
apiHost?: string
|
||||
clientId?: string
|
||||
sharedSecret?: string
|
||||
customerCookieMaxAgeInDays: number,
|
||||
currencyCode: string,
|
||||
documentListName: string,
|
||||
defaultWishlistName: string,
|
||||
customerCookieMaxAgeInDays: number
|
||||
currencyCode: string
|
||||
documentListName: string
|
||||
defaultWishlistName: string
|
||||
authUrl?: string
|
||||
}
|
||||
|
||||
@ -37,7 +37,7 @@ const config: KiboCommerceConfig = {
|
||||
sharedSecret: process.env.KIBO_SHARED_SECRET || '',
|
||||
customerCookieMaxAgeInDays: 30,
|
||||
currencyCode: 'USD',
|
||||
defaultWishlistName: 'My Wishlist'
|
||||
defaultWishlistName: 'My Wishlist',
|
||||
}
|
||||
|
||||
const operations = {
|
||||
@ -55,7 +55,7 @@ export const provider = { config, operations }
|
||||
export type KiboCommerceProvider = typeof provider
|
||||
export type KiboCommerceAPI<
|
||||
P extends KiboCommerceProvider = KiboCommerceProvider
|
||||
> = CommerceAPI<P | any>
|
||||
> = CommerceAPI<P | any>
|
||||
|
||||
export function getCommerceApi<P extends KiboCommerceProvider>(
|
||||
customProvider: P = provider as any
|
||||
|
@ -1,5 +1,5 @@
|
||||
import {productDetails} from '../fragments/productDetails'
|
||||
const addItemToWishlistMutation = /* GraphQL */`
|
||||
import { productDetails } from '../fragments/productDetails'
|
||||
const addItemToWishlistMutation = /* GraphQL */ `
|
||||
mutation createWishlistItem(
|
||||
$wishlistId: String!
|
||||
$wishlistItemInput: WishlistItemInput
|
||||
@ -15,7 +15,7 @@ const addItemToWishlistMutation = /* GraphQL */`
|
||||
}
|
||||
}
|
||||
}
|
||||
${productDetails}
|
||||
`;
|
||||
${productDetails}
|
||||
`
|
||||
|
||||
export default addItemToWishlistMutation;
|
||||
export default addItemToWishlistMutation
|
||||
|
@ -1,4 +1,4 @@
|
||||
const createWishlist = /*GraphQL*/`
|
||||
const createWishlist = /*GraphQL*/ `
|
||||
mutation createWishlist($wishlistInput:WishlistInput!) {
|
||||
createWishlist(wishlistInput:$wishlistInput){
|
||||
id
|
||||
@ -6,6 +6,6 @@ mutation createWishlist($wishlistInput:WishlistInput!) {
|
||||
customerAccountId
|
||||
}
|
||||
}
|
||||
`;
|
||||
`
|
||||
|
||||
export default createWishlist;
|
||||
export default createWishlist
|
||||
|
@ -1,7 +1,6 @@
|
||||
|
||||
export const loginMutation = /* GraphQL */`
|
||||
mutation login($loginInput:CustomerUserAuthInfoInput!) {
|
||||
account:createCustomerAuthTicket(customerUserAuthInfoInput:$loginInput) {
|
||||
export const loginMutation = /* GraphQL */ `
|
||||
mutation login($loginInput: CustomerUserAuthInfoInput!) {
|
||||
account: createCustomerAuthTicket(customerUserAuthInfoInput: $loginInput) {
|
||||
accessToken
|
||||
userId
|
||||
refreshToken
|
||||
@ -17,4 +16,3 @@ mutation login($loginInput:CustomerUserAuthInfoInput!) {
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
|
@ -1,9 +1,9 @@
|
||||
/*
|
||||
* Delete cart based on current user session
|
||||
*/
|
||||
const removeItemFromCartMutation = /*GraphQL*/`
|
||||
* Delete cart based on current user session
|
||||
*/
|
||||
const removeItemFromCartMutation = /*GraphQL*/ `
|
||||
mutation deleteCartItem($id: String!) {
|
||||
deleteCurrentCartItem(cartItemId:$id)
|
||||
}`;
|
||||
}`
|
||||
|
||||
export default removeItemFromCartMutation;
|
||||
export default removeItemFromCartMutation
|
||||
|
@ -1,8 +1,7 @@
|
||||
const removeItemFromWishlistMutation = /* GraphQL */`
|
||||
mutation deletewishlistitem($wishlistId: String!, $wishlistItemId: String!) {
|
||||
deleteWishlistItem(wishlistId: $wishlistId, wishlistItemId:$wishlistItemId)
|
||||
const removeItemFromWishlistMutation = /* GraphQL */ `
|
||||
mutation deletewishlistitem($wishlistId: String!, $wishlistItemId: String!) {
|
||||
deleteWishlistItem(wishlistId: $wishlistId, wishlistItemId: $wishlistItemId)
|
||||
}
|
||||
`;
|
||||
|
||||
export default removeItemFromWishlistMutation;
|
||||
`
|
||||
|
||||
export default removeItemFromWishlistMutation
|
||||
|
@ -1,41 +1,46 @@
|
||||
|
||||
const registerUserMutation = /* GraphQL */`
|
||||
mutation registerUser($customerAccountInput: CustomerAccountInput!) {
|
||||
account:createCustomerAccount(customerAccountInput:$customerAccountInput) {
|
||||
emailAddress
|
||||
userName
|
||||
firstName
|
||||
lastName
|
||||
localeCode
|
||||
userId
|
||||
id
|
||||
isAnonymous
|
||||
attributes {
|
||||
values
|
||||
fullyQualifiedName
|
||||
}
|
||||
const registerUserMutation = /* GraphQL */ `
|
||||
mutation registerUser($customerAccountInput: CustomerAccountInput!) {
|
||||
account: createCustomerAccount(
|
||||
customerAccountInput: $customerAccountInput
|
||||
) {
|
||||
emailAddress
|
||||
userName
|
||||
firstName
|
||||
lastName
|
||||
localeCode
|
||||
userId
|
||||
id
|
||||
isAnonymous
|
||||
attributes {
|
||||
values
|
||||
fullyQualifiedName
|
||||
}
|
||||
}
|
||||
}`;
|
||||
}
|
||||
`
|
||||
|
||||
const registerUserLoginMutation = /* GraphQL */`
|
||||
mutation registerUserLogin($accountId: Int!, $customerLoginInfoInput: CustomerLoginInfoInput!) {
|
||||
account:createCustomerAccountLogin(accountId:$accountId, customerLoginInfoInput:$customerLoginInfoInput) {
|
||||
const registerUserLoginMutation = /* GraphQL */ `
|
||||
mutation registerUserLogin(
|
||||
$accountId: Int!
|
||||
$customerLoginInfoInput: CustomerLoginInfoInput!
|
||||
) {
|
||||
account: createCustomerAccountLogin(
|
||||
accountId: $accountId
|
||||
customerLoginInfoInput: $customerLoginInfoInput
|
||||
) {
|
||||
accessToken
|
||||
accessTokenExpiration
|
||||
refreshToken
|
||||
refreshTokenExpiration
|
||||
userId
|
||||
customerAccount {
|
||||
id
|
||||
emailAddress
|
||||
firstName
|
||||
userName
|
||||
id
|
||||
emailAddress
|
||||
firstName
|
||||
userName
|
||||
}
|
||||
}
|
||||
}
|
||||
}`;
|
||||
|
||||
export {
|
||||
registerUserMutation,
|
||||
registerUserLoginMutation
|
||||
};
|
||||
`
|
||||
|
||||
export { registerUserMutation, registerUserLoginMutation }
|
||||
|
@ -1,9 +1,9 @@
|
||||
const updateCartItemQuantityMutation = /*GraphQL*/`
|
||||
const updateCartItemQuantityMutation = /*GraphQL*/ `
|
||||
mutation updateCartItemQuantity($itemId:String!, $quantity: Int!){
|
||||
updateCurrentCartItemQuantity(cartItemId:$itemId, quantity:$quantity){
|
||||
id
|
||||
quantity
|
||||
}
|
||||
}`;
|
||||
}`
|
||||
|
||||
export default updateCartItemQuantityMutation;
|
||||
export default updateCartItemQuantityMutation
|
||||
|
@ -1,17 +1,14 @@
|
||||
import type { OperationContext } from '@vercel/commerce/api/operations'
|
||||
import type { KiboCommerceConfig } from '../index'
|
||||
import { getAllPagesQuery } from '../queries/get-all-pages-query'
|
||||
import { GetPagesQueryParams } from "../../types/page";
|
||||
import { GetPagesQueryParams } from '../../types/page'
|
||||
import { normalizePage } from '../../lib/normalize'
|
||||
|
||||
export type GetAllPagesResult<
|
||||
T extends { pages: any[] } = { pages: any[] }
|
||||
> = T
|
||||
export type GetAllPagesResult<T extends { pages: any[] } = { pages: any[] }> = T
|
||||
|
||||
export default function getAllPagesOperation({
|
||||
commerce,
|
||||
}: OperationContext<any>) {
|
||||
|
||||
async function getAllPages({
|
||||
query = getAllPagesQuery,
|
||||
config,
|
||||
@ -25,11 +22,11 @@ export default function getAllPagesOperation({
|
||||
} = {}): Promise<GetAllPagesResult> {
|
||||
const cfg = commerce.getConfig(config)
|
||||
variables = {
|
||||
documentListName: cfg.documentListName
|
||||
documentListName: cfg.documentListName,
|
||||
}
|
||||
const { data } = await cfg.fetch(query, { variables });
|
||||
const { data } = await cfg.fetch(query, { variables })
|
||||
|
||||
const pages = data.documentListDocuments.items.map(normalizePage);
|
||||
const pages = data.documentListDocuments.items.map(normalizePage)
|
||||
|
||||
return { pages }
|
||||
}
|
||||
|
@ -1,24 +1,31 @@
|
||||
import { KiboCommerceConfig } from '../index'
|
||||
import { getAllProductsQuery } from '../queries/get-all-products-query';
|
||||
import { getAllProductsQuery } from '../queries/get-all-products-query'
|
||||
import { normalizeProduct } from '../../lib/normalize'
|
||||
|
||||
export type GetAllProductPathsResult = {
|
||||
products: Array<{ path: string }>
|
||||
}
|
||||
|
||||
export default function getAllProductPathsOperation({commerce,}: any) {
|
||||
async function getAllProductPaths({ config }: {config?: KiboCommerceConfig } = {}): Promise<GetAllProductPathsResult> {
|
||||
|
||||
export default function getAllProductPathsOperation({ commerce }: any) {
|
||||
async function getAllProductPaths({
|
||||
config,
|
||||
}: { config?: KiboCommerceConfig } = {}): Promise<GetAllProductPathsResult> {
|
||||
const cfg = commerce.getConfig(config)
|
||||
|
||||
const productVariables = {startIndex: 0, pageSize: 100};
|
||||
const { data } = await cfg.fetch(getAllProductsQuery, { variables: productVariables });
|
||||
const productVariables = { startIndex: 0, pageSize: 100 }
|
||||
const { data } = await cfg.fetch(getAllProductsQuery, {
|
||||
variables: productVariables,
|
||||
})
|
||||
|
||||
const normalizedProducts = data.products.items ? data.products.items.map( (item:any) => normalizeProduct(item, cfg)) : [];
|
||||
const products = normalizedProducts.map((product: any) => ({ path: product.path }))
|
||||
const normalizedProducts = data.products.items
|
||||
? data.products.items.map((item: any) => normalizeProduct(item, cfg))
|
||||
: []
|
||||
const products = normalizedProducts.map((product: any) => ({
|
||||
path: product.path,
|
||||
}))
|
||||
|
||||
return Promise.resolve({
|
||||
products: products
|
||||
products: products,
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -2,7 +2,7 @@ import { Product } from '@vercel/commerce/types/product'
|
||||
import { GetAllProductsOperation } from '@vercel/commerce/types/product'
|
||||
import type { OperationContext } from '@vercel/commerce/api/operations'
|
||||
import type { KiboCommerceConfig } from '../index'
|
||||
import { getAllProductsQuery } from '../queries/get-all-products-query';
|
||||
import { getAllProductsQuery } from '../queries/get-all-products-query'
|
||||
import { normalizeProduct } from '../../lib/normalize'
|
||||
|
||||
export default function getAllProductsOperation({
|
||||
@ -18,11 +18,12 @@ export default function getAllProductsOperation({
|
||||
config?: Partial<KiboCommerceConfig>
|
||||
preview?: boolean
|
||||
} = {}): Promise<{ products: Product[] | any[] }> {
|
||||
|
||||
const cfg = commerce.getConfig(config)
|
||||
const { data } = await cfg.fetch(query);
|
||||
const { data } = await cfg.fetch(query)
|
||||
|
||||
let normalizedProducts = data.products.items ? data.products.items.map( (item:any) => normalizeProduct(item, cfg)) : [];
|
||||
let normalizedProducts = data.products.items
|
||||
? data.products.items.map((item: any) => normalizeProduct(item, cfg))
|
||||
: []
|
||||
|
||||
return {
|
||||
products: normalizedProducts,
|
||||
|
@ -9,7 +9,7 @@ import type {
|
||||
// import type { RecursivePartial, RecursiveRequired } from '../utils/types'
|
||||
import { KiboCommerceConfig } from '..'
|
||||
// import getAllProducts, { ProductEdge } from './get-all-products'
|
||||
import {getCustomerWishlistQuery} from '../queries/get-customer-wishlist-query'
|
||||
import { getCustomerWishlistQuery } from '../queries/get-customer-wishlist-query'
|
||||
|
||||
export default function getCustomerWishlistOperation({
|
||||
commerce,
|
||||
@ -40,14 +40,15 @@ export default function getCustomerWishlistOperation({
|
||||
config?: KiboCommerceConfig
|
||||
includeProducts?: boolean
|
||||
}): Promise<T['data']> {
|
||||
let customerWishlist ={}
|
||||
let customerWishlist = {}
|
||||
try {
|
||||
|
||||
config = commerce.getConfig(config)
|
||||
const result= await config?.fetch(getCustomerWishlistQuery,{variables})
|
||||
customerWishlist= result?.data?.customerWishlist;
|
||||
} catch(e) {
|
||||
customerWishlist= {}
|
||||
const result = await config?.fetch(getCustomerWishlistQuery, {
|
||||
variables,
|
||||
})
|
||||
customerWishlist = result?.data?.customerWishlist
|
||||
} catch (e) {
|
||||
customerWishlist = {}
|
||||
}
|
||||
|
||||
return { wishlist: customerWishlist as any }
|
||||
|
@ -1,15 +1,11 @@
|
||||
import type {
|
||||
OperationContext,
|
||||
} from '@vercel/commerce/api/operations'
|
||||
import type { OperationContext } from '@vercel/commerce/api/operations'
|
||||
import type { KiboCommerceConfig, KiboCommerceProvider } from '..'
|
||||
import { normalizePage } from '../../lib/normalize'
|
||||
import { getPageQuery } from '../queries/get-page-query'
|
||||
import type { Page, GetPageQueryParams } from "../../types/page";
|
||||
import type { Page, GetPageQueryParams } from '../../types/page'
|
||||
import type { Document } from '../../../schema'
|
||||
|
||||
export default function getPageOperation({
|
||||
commerce,
|
||||
}: OperationContext<any>) {
|
||||
export default function getPageOperation({ commerce }: OperationContext<any>) {
|
||||
async function getPage<T extends Page>({
|
||||
url,
|
||||
variables,
|
||||
@ -24,11 +20,14 @@ export default function getPageOperation({
|
||||
// RecursivePartial forces the method to check for every prop in the data, which is
|
||||
// required in case there's a custom `url`
|
||||
const cfg = commerce.getConfig(config)
|
||||
const pageVariables = { documentListName: cfg.documentListName, filter: `id eq ${variables.id}` }
|
||||
const pageVariables = {
|
||||
documentListName: cfg.documentListName,
|
||||
filter: `id eq ${variables.id}`,
|
||||
}
|
||||
|
||||
const { data } = await cfg.fetch(getPageQuery, { variables: pageVariables })
|
||||
|
||||
const firstPage = data.documentListDocuments.items?.[0];
|
||||
const firstPage = data.documentListDocuments.items?.[0]
|
||||
const page = firstPage as Document
|
||||
if (preview || page?.properties?.is_visible) {
|
||||
return { page: normalizePage(page as any) }
|
||||
|
@ -8,7 +8,6 @@ import { normalizeProduct } from '../../lib/normalize'
|
||||
export default function getProductOperation({
|
||||
commerce,
|
||||
}: OperationContext<any>) {
|
||||
|
||||
async function getProduct<T extends GetProductOperation>({
|
||||
query = getProductQuery,
|
||||
variables,
|
||||
@ -19,15 +18,15 @@ export default function getProductOperation({
|
||||
config?: Partial<KiboCommerceConfig>
|
||||
preview?: boolean
|
||||
} = {}): Promise<Product | {} | any> {
|
||||
const productVariables = { productCode: variables?.slug}
|
||||
const productVariables = { productCode: variables?.slug }
|
||||
|
||||
const cfg = commerce.getConfig(config)
|
||||
const { data } = await cfg.fetch(query, { variables: productVariables });
|
||||
const { data } = await cfg.fetch(query, { variables: productVariables })
|
||||
|
||||
const normalizedProduct = normalizeProduct(data.product, cfg)
|
||||
|
||||
return {
|
||||
product: normalizedProduct
|
||||
product: normalizedProduct,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
import { OperationContext } from '@vercel/commerce/api/operations'
|
||||
import { Category } from '@vercel/commerce/types/site'
|
||||
import { KiboCommerceConfig } from '../index'
|
||||
import {categoryTreeQuery} from '../queries/get-categories-tree-query'
|
||||
import { categoryTreeQuery } from '../queries/get-categories-tree-query'
|
||||
import { normalizeCategory } from '../../lib/normalize'
|
||||
|
||||
export type GetSiteInfoResult<
|
||||
@ -11,9 +11,11 @@ export type GetSiteInfoResult<
|
||||
}
|
||||
> = T
|
||||
|
||||
export default function getSiteInfoOperation({commerce}: OperationContext<any>) {
|
||||
export default function getSiteInfoOperation({
|
||||
commerce,
|
||||
}: OperationContext<any>) {
|
||||
async function getSiteInfo({
|
||||
query= categoryTreeQuery,
|
||||
query = categoryTreeQuery,
|
||||
variables,
|
||||
config,
|
||||
}: {
|
||||
@ -23,8 +25,8 @@ export default function getSiteInfoOperation({commerce}: OperationContext<any>)
|
||||
preview?: boolean
|
||||
} = {}): Promise<GetSiteInfoResult> {
|
||||
const cfg = commerce.getConfig(config)
|
||||
const { data } = await cfg.fetch(query);
|
||||
const categories= data.categories.items.map(normalizeCategory);
|
||||
const { data } = await cfg.fetch(query)
|
||||
const categories = data.categories.items.map(normalizeCategory)
|
||||
return Promise.resolve({
|
||||
categories: categories ?? [],
|
||||
brands: [],
|
||||
|
@ -1,6 +1,6 @@
|
||||
export const getAllPagesQuery = /* GraphQL */`
|
||||
query($documentListName: String!) {
|
||||
documentListDocuments(documentListName:$documentListName){
|
||||
export const getAllPagesQuery = /* GraphQL */ `
|
||||
query ($documentListName: String!) {
|
||||
documentListDocuments(documentListName: $documentListName) {
|
||||
items {
|
||||
id
|
||||
name
|
||||
@ -8,4 +8,5 @@ query($documentListName: String!) {
|
||||
properties
|
||||
}
|
||||
}
|
||||
}`;
|
||||
}
|
||||
`
|
||||
|
@ -1,21 +1,13 @@
|
||||
import { productInfo } from '../fragments/product';
|
||||
import { productInfo } from '../fragments/product'
|
||||
|
||||
export const getAllProductsQuery = /* GraphQL */`
|
||||
${productInfo}
|
||||
export const getAllProductsQuery = /* GraphQL */ `
|
||||
${productInfo}
|
||||
|
||||
query products(
|
||||
$filter: String
|
||||
$startIndex: Int
|
||||
$pageSize: Int
|
||||
) {
|
||||
products(
|
||||
filter: $filter
|
||||
startIndex: $startIndex
|
||||
pageSize: $pageSize
|
||||
) {
|
||||
items {
|
||||
...productInfo
|
||||
query products($filter: String, $startIndex: Int, $pageSize: Int) {
|
||||
products(filter: $filter, startIndex: $startIndex, pageSize: $pageSize) {
|
||||
items {
|
||||
...productInfo
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
`
|
||||
|
@ -1,6 +1,6 @@
|
||||
import { productDetails } from '../fragments/productDetails'
|
||||
export const getCartQuery = /* GraphQL */`
|
||||
query cart {
|
||||
export const getCartQuery = /* GraphQL */ `
|
||||
query cart {
|
||||
currentCart {
|
||||
id
|
||||
userId
|
||||
@ -8,7 +8,7 @@ query cart {
|
||||
impact
|
||||
discount {
|
||||
id
|
||||
name
|
||||
name
|
||||
}
|
||||
couponCode
|
||||
}
|
||||
@ -18,15 +18,15 @@ query cart {
|
||||
items {
|
||||
id
|
||||
subtotal
|
||||
unitPrice{
|
||||
unitPrice {
|
||||
extendedAmount
|
||||
}
|
||||
product {
|
||||
...productDetails
|
||||
}
|
||||
quantity
|
||||
product {
|
||||
...productDetails
|
||||
}
|
||||
quantity
|
||||
}
|
||||
}
|
||||
${productDetails}
|
||||
}
|
||||
${productDetails}
|
||||
`
|
||||
|
@ -1,29 +1,30 @@
|
||||
import { CategoryInfo } from '../fragments/category'
|
||||
|
||||
export const categoryTreeQuery = /* GraphQL */`
|
||||
query GetCategoryTree {
|
||||
export const categoryTreeQuery = /* GraphQL */ `
|
||||
query GetCategoryTree {
|
||||
categories: categoriesTree {
|
||||
items {
|
||||
...categoryInfo
|
||||
childrenCategories {
|
||||
...categoryInfo
|
||||
childrenCategories {
|
||||
...categoryInfo
|
||||
childrenCategories {
|
||||
...categoryInfo
|
||||
childrenCategories {
|
||||
...categoryInfo
|
||||
childrenCategories {
|
||||
...categoryInfo
|
||||
childrenCategories {
|
||||
...categoryInfo
|
||||
childrenCategories {
|
||||
...categoryInfo
|
||||
childrenCategories {
|
||||
...categoryInfo
|
||||
childrenCategories {
|
||||
...categoryInfo
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
${CategoryInfo}`;
|
||||
}
|
||||
${CategoryInfo}
|
||||
`
|
||||
|
@ -1,12 +1,12 @@
|
||||
export const getCustomerAccountQuery = /* GraphQL */`
|
||||
query getUser {
|
||||
customerAccount:getCurrentAccount {
|
||||
id
|
||||
firstName
|
||||
lastName
|
||||
emailAddress
|
||||
userName
|
||||
isAnonymous
|
||||
export const getCustomerAccountQuery = /* GraphQL */ `
|
||||
query getUser {
|
||||
customerAccount: getCurrentAccount {
|
||||
id
|
||||
firstName
|
||||
lastName
|
||||
emailAddress
|
||||
userName
|
||||
isAnonymous
|
||||
}
|
||||
}
|
||||
`
|
||||
}
|
||||
`
|
||||
|
@ -1,25 +1,28 @@
|
||||
import {productDetails} from '../fragments/productDetails'
|
||||
export const getCustomerWishlistQuery= /* GraphQL */`
|
||||
query wishlist($customerId: Int!, $wishlistName: String!) {
|
||||
customerWishlist(customerAccountId:$customerId ,wishlistName: $wishlistName){
|
||||
import { productDetails } from '../fragments/productDetails'
|
||||
export const getCustomerWishlistQuery = /* GraphQL */ `
|
||||
query wishlist($customerId: Int!, $wishlistName: String!) {
|
||||
customerWishlist(
|
||||
customerAccountId: $customerId
|
||||
wishlistName: $wishlistName
|
||||
) {
|
||||
customerAccountId
|
||||
name
|
||||
id
|
||||
userId
|
||||
items {
|
||||
id
|
||||
id
|
||||
quantity
|
||||
total
|
||||
subtotal
|
||||
unitPrice{
|
||||
unitPrice {
|
||||
extendedAmount
|
||||
}
|
||||
quantity
|
||||
product {
|
||||
...productDetails
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
${productDetails}
|
||||
`
|
||||
${productDetails}
|
||||
`
|
||||
|
@ -1,14 +1,17 @@
|
||||
export const getPageQuery = /* GraphQL */`
|
||||
query($documentListName: String!, $filter: String!) {
|
||||
documentListDocuments(documentListName: $documentListName, filter: $filter){
|
||||
startIndex
|
||||
totalCount
|
||||
items {
|
||||
id
|
||||
name
|
||||
listFQN
|
||||
properties
|
||||
}
|
||||
}
|
||||
export const getPageQuery = /* GraphQL */ `
|
||||
query ($documentListName: String!, $filter: String!) {
|
||||
documentListDocuments(
|
||||
documentListName: $documentListName
|
||||
filter: $filter
|
||||
) {
|
||||
startIndex
|
||||
totalCount
|
||||
items {
|
||||
id
|
||||
name
|
||||
listFQN
|
||||
properties
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
`
|
||||
|
@ -1,15 +1,11 @@
|
||||
import { productInfo } from '../fragments/product';
|
||||
import { productInfo } from '../fragments/product'
|
||||
|
||||
export const getProductQuery = /* GraphQL */`
|
||||
${productInfo}
|
||||
export const getProductQuery = /* GraphQL */ `
|
||||
${productInfo}
|
||||
|
||||
query product(
|
||||
$productCode: String!
|
||||
) {
|
||||
product(
|
||||
productCode: $productCode
|
||||
) {
|
||||
query product($productCode: String!) {
|
||||
product(productCode: $productCode) {
|
||||
...productInfo
|
||||
}
|
||||
}
|
||||
`
|
||||
`
|
||||
|
@ -1,20 +1,27 @@
|
||||
import { searchResults } from '../fragments/search'
|
||||
|
||||
const query = /* GraphQL */`
|
||||
query ProductSearch($query:String, $startIndex:Int,
|
||||
$pageSize:Int, $sortBy:String, $filter:String,$facetTemplate:String,$facetValueFilter:String ) {
|
||||
products:productSearch (
|
||||
query:$query,
|
||||
startIndex: $startIndex,
|
||||
pageSize:$pageSize,
|
||||
sortBy: $sortBy,
|
||||
filter:$filter,
|
||||
facetTemplate:$facetTemplate,
|
||||
facetValueFilter:$facetValueFilter
|
||||
) {
|
||||
...searchResults
|
||||
}
|
||||
const query = /* GraphQL */ `
|
||||
query ProductSearch(
|
||||
$query: String
|
||||
$startIndex: Int
|
||||
$pageSize: Int
|
||||
$sortBy: String
|
||||
$filter: String
|
||||
$facetTemplate: String
|
||||
$facetValueFilter: String
|
||||
) {
|
||||
products: productSearch(
|
||||
query: $query
|
||||
startIndex: $startIndex
|
||||
pageSize: $pageSize
|
||||
sortBy: $sortBy
|
||||
filter: $filter
|
||||
facetTemplate: $facetTemplate
|
||||
facetValueFilter: $facetValueFilter
|
||||
) {
|
||||
...searchResults
|
||||
}
|
||||
${searchResults}
|
||||
`;
|
||||
export default query;
|
||||
}
|
||||
${searchResults}
|
||||
`
|
||||
export default query
|
||||
|
@ -41,8 +41,8 @@ export class APIAuthenticationHelper {
|
||||
this._clientId = clientId
|
||||
this._sharedSecret = sharedSecret
|
||||
this._authUrl = authUrl
|
||||
if(!authTicketCache) {
|
||||
this._authTicketCache = new RuntimeMemCache();
|
||||
if (!authTicketCache) {
|
||||
this._authTicketCache = new RuntimeMemCache()
|
||||
}
|
||||
}
|
||||
private _buildFetchOptions(body: any = {}): FetchOptions {
|
||||
|
@ -6,8 +6,8 @@ import { NextApiRequest } from 'next'
|
||||
import getAnonymousShopperToken from './get-anonymous-shopper-token'
|
||||
|
||||
const parseCookie = (cookieValue?: any) => {
|
||||
return cookieValue
|
||||
? JSON.parse(Buffer.from(cookieValue, 'base64').toString('ascii'))
|
||||
return cookieValue
|
||||
? JSON.parse(Buffer.from(cookieValue, 'base64').toString('ascii'))
|
||||
: null
|
||||
}
|
||||
export default class CookieHandler {
|
||||
@ -37,8 +37,8 @@ export default class CookieHandler {
|
||||
isShopperCookieAnonymous() {
|
||||
const customerCookieKey = this.config.customerCookie
|
||||
const shopperCookie = this.request.cookies[customerCookieKey]
|
||||
const shopperSession = parseCookie(shopperCookie);
|
||||
const isAnonymous = shopperSession?.customerAccount ? false : true
|
||||
const shopperSession = parseCookie(shopperCookie)
|
||||
const isAnonymous = shopperSession?.customerAccount ? false : true
|
||||
return isAnonymous
|
||||
}
|
||||
setAnonymousShopperCookie(anonymousShopperTokenResponse: any) {
|
||||
|
@ -2,42 +2,46 @@ import { FetcherError } from '@vercel/commerce/utils/errors'
|
||||
import type { GraphQLFetcher } from '@vercel/commerce/api'
|
||||
import type { KiboCommerceConfig } from '../index'
|
||||
import fetch from './fetch'
|
||||
import { APIAuthenticationHelper } from './api-auth-helper';
|
||||
import { APIAuthenticationHelper } from './api-auth-helper'
|
||||
|
||||
const fetchGraphqlApi: (
|
||||
getConfig: () => KiboCommerceConfig
|
||||
) => GraphQLFetcher = (getConfig) => async (
|
||||
query: string,
|
||||
{ variables, preview } = {},
|
||||
fetchOptions
|
||||
) => {
|
||||
const config = getConfig()
|
||||
const authHelper = new APIAuthenticationHelper(config);
|
||||
const apiToken = await authHelper.getAccessToken();
|
||||
const res = await fetch(config.commerceUrl + (preview ? '/preview' : ''), {
|
||||
...fetchOptions,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...fetchOptions?.headers,
|
||||
Authorization: `Bearer ${apiToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
variables,
|
||||
}),
|
||||
})
|
||||
|
||||
const json = await res.json()
|
||||
if (json.errors) {
|
||||
console.warn(`Kibo API Request Correlation ID: ${res.headers.get('x-vol-correlation')}`);
|
||||
throw new FetcherError({
|
||||
errors: json.errors ?? [{ message: 'Failed to fetch KiboCommerce API' }],
|
||||
status: res.status,
|
||||
) => GraphQLFetcher =
|
||||
(getConfig) =>
|
||||
async (query: string, { variables, preview } = {}, fetchOptions) => {
|
||||
const config = getConfig()
|
||||
const authHelper = new APIAuthenticationHelper(config)
|
||||
const apiToken = await authHelper.getAccessToken()
|
||||
const res = await fetch(config.commerceUrl + (preview ? '/preview' : ''), {
|
||||
...fetchOptions,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...fetchOptions?.headers,
|
||||
Authorization: `Bearer ${apiToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
variables,
|
||||
}),
|
||||
})
|
||||
|
||||
const json = await res.json()
|
||||
if (json.errors) {
|
||||
console.warn(
|
||||
`Kibo API Request Correlation ID: ${res.headers.get(
|
||||
'x-vol-correlation'
|
||||
)}`
|
||||
)
|
||||
throw new FetcherError({
|
||||
errors: json.errors ?? [
|
||||
{ message: 'Failed to fetch KiboCommerce API' },
|
||||
],
|
||||
status: res.status,
|
||||
})
|
||||
}
|
||||
|
||||
return { data: json.data, res }
|
||||
}
|
||||
|
||||
return { data: json.data, res }
|
||||
}
|
||||
|
||||
export default fetchGraphqlApi
|
||||
|
@ -3,12 +3,14 @@ import type { GraphQLFetcher } from '@vercel/commerce/api'
|
||||
import type { KiboCommerceConfig } from '../index'
|
||||
import fetch from './fetch'
|
||||
|
||||
const fetchGraphqlApi: (getConfig: () => KiboCommerceConfig) => GraphQLFetcher =
|
||||
const fetchGraphqlApi: (
|
||||
getConfig: () => KiboCommerceConfig
|
||||
) => GraphQLFetcher =
|
||||
(getConfig) =>
|
||||
async (query: string, { variables, preview } = {}, fetchOptions) => {
|
||||
const config = getConfig()
|
||||
const res = await fetch(config.commerceUrl, {
|
||||
//const res = await fetch(config.commerceUrl + (preview ? '/preview' : ''), {
|
||||
//const res = await fetch(config.commerceUrl + (preview ? '/preview' : ''), {
|
||||
...fetchOptions,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@ -25,7 +27,9 @@ const fetchGraphqlApi: (getConfig: () => KiboCommerceConfig) => GraphQLFetcher =
|
||||
const json = await res.json()
|
||||
if (json.errors) {
|
||||
throw new FetcherError({
|
||||
errors: json.errors ?? [{ message: 'Failed to fetch KiboCommerce API' }],
|
||||
errors: json.errors ?? [
|
||||
{ message: 'Failed to fetch KiboCommerce API' },
|
||||
],
|
||||
status: res.status,
|
||||
})
|
||||
}
|
||||
|
@ -8,17 +8,15 @@ async function getCustomerId({
|
||||
customerToken: string
|
||||
config: KiboCommerceConfig
|
||||
}): Promise<string | undefined> {
|
||||
const token = customerToken ? Buffer.from(customerToken, 'base64').toString('ascii'): null;
|
||||
const accessToken = token ? JSON.parse(token).accessToken : null;
|
||||
const { data } = await config.fetch(
|
||||
getCustomerAccountQuery,
|
||||
undefined,
|
||||
{
|
||||
headers: {
|
||||
'x-vol-user-claims': accessToken,
|
||||
},
|
||||
}
|
||||
)
|
||||
const token = customerToken
|
||||
? Buffer.from(customerToken, 'base64').toString('ascii')
|
||||
: null
|
||||
const accessToken = token ? JSON.parse(token).accessToken : null
|
||||
const { data } = await config.fetch(getCustomerAccountQuery, undefined, {
|
||||
headers: {
|
||||
'x-vol-user-claims': accessToken,
|
||||
},
|
||||
})
|
||||
|
||||
return data?.customerAccount?.id
|
||||
}
|
||||
|
@ -12,18 +12,20 @@ export const handler: MutationHook<LogoutHook> = {
|
||||
url: '/api/logout',
|
||||
method: 'GET',
|
||||
},
|
||||
useHook: ({ fetch }) => () => {
|
||||
const { mutate } = useCustomer()
|
||||
const { mutate: mutateCart } = useCart()
|
||||
useHook:
|
||||
({ fetch }) =>
|
||||
() => {
|
||||
const { mutate } = useCustomer()
|
||||
const { mutate: mutateCart } = useCart()
|
||||
|
||||
return useCallback(
|
||||
async function logout() {
|
||||
const data = await fetch()
|
||||
await mutate(null, false)
|
||||
await mutateCart(null, false)
|
||||
return data
|
||||
},
|
||||
[fetch, mutate, mutateCart]
|
||||
)
|
||||
},
|
||||
return useCallback(
|
||||
async function logout() {
|
||||
const data = await fetch()
|
||||
await mutate(null, false)
|
||||
await mutateCart(null, false)
|
||||
return data
|
||||
},
|
||||
[fetch, mutate, mutateCart]
|
||||
)
|
||||
},
|
||||
}
|
||||
|
@ -29,16 +29,18 @@ export const handler: MutationHook<AddItemHook> = {
|
||||
|
||||
return data
|
||||
},
|
||||
useHook: ({ fetch }) => () => {
|
||||
const { mutate } = useCart()
|
||||
useHook:
|
||||
({ fetch }) =>
|
||||
() => {
|
||||
const { mutate } = useCart()
|
||||
|
||||
return useCallback(
|
||||
async function addItem(input) {
|
||||
const data = await fetch({ input })
|
||||
await mutate(data, false)
|
||||
return data
|
||||
},
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
return useCallback(
|
||||
async function addItem(input) {
|
||||
const data = await fetch({ input })
|
||||
await mutate(data, false)
|
||||
return data
|
||||
},
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
}
|
||||
|
@ -12,22 +12,24 @@ export const handler: SWRHook<any> = {
|
||||
async fetcher({ options, fetch }) {
|
||||
return await fetch({ ...options })
|
||||
},
|
||||
useHook: ({ useData }) => (input) => {
|
||||
const response = useData({
|
||||
swrOptions: { revalidateOnFocus: false, ...input?.swrOptions },
|
||||
})
|
||||
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
|
||||
return useMemo(
|
||||
() =>
|
||||
Object.create(response, {
|
||||
isEmpty: {
|
||||
get() {
|
||||
return (response.data?.lineItems.length ?? 0) <= 0
|
||||
},
|
||||
enumerable: true,
|
||||
},
|
||||
enumerable: true,
|
||||
},
|
||||
}),
|
||||
[response]
|
||||
)
|
||||
},
|
||||
}),
|
||||
[response]
|
||||
)
|
||||
},
|
||||
}
|
||||
|
@ -4,8 +4,14 @@ import type {
|
||||
HookFetcherContext,
|
||||
} from '@vercel/commerce/utils/types'
|
||||
import { ValidationError } from '@vercel/commerce/utils/errors'
|
||||
import useRemoveItem, { UseRemoveItem } from '@vercel/commerce/cart/use-remove-item'
|
||||
import type { Cart, LineItem, RemoveItemHook } from '@vercel/commerce/types/cart'
|
||||
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'
|
||||
|
||||
export type RemoveItemFn<T = any> = T extends LineItem
|
||||
@ -30,27 +36,25 @@ export const handler = {
|
||||
}: HookFetcherContext<RemoveItemHook>) {
|
||||
return await fetch({ ...options, body: { itemId } })
|
||||
},
|
||||
useHook: ({ fetch }: MutationHookContext<RemoveItemHook>) => <
|
||||
T extends LineItem | undefined = undefined
|
||||
>(
|
||||
ctx: { item?: T } = {}
|
||||
) => {
|
||||
const { item } = ctx
|
||||
const { mutate } = useCart()
|
||||
const removeItem: RemoveItemFn<LineItem> = async (input) => {
|
||||
const itemId = input?.id ?? item?.id
|
||||
useHook:
|
||||
({ fetch }: MutationHookContext<RemoveItemHook>) =>
|
||||
<T extends LineItem | undefined = undefined>(ctx: { item?: T } = {}) => {
|
||||
const { item } = ctx
|
||||
const { mutate } = useCart()
|
||||
const removeItem: RemoveItemFn<LineItem> = async (input) => {
|
||||
const itemId = input?.id ?? item?.id
|
||||
|
||||
if (!itemId) {
|
||||
throw new ValidationError({
|
||||
message: 'Invalid input used for this operation',
|
||||
})
|
||||
if (!itemId) {
|
||||
throw new ValidationError({
|
||||
message: 'Invalid input used for this operation',
|
||||
})
|
||||
}
|
||||
|
||||
const data = await fetch({ input: { itemId } })
|
||||
await mutate(data, false)
|
||||
return data
|
||||
}
|
||||
|
||||
const data = await fetch({ input: { itemId } })
|
||||
await mutate(data, false)
|
||||
return data
|
||||
}
|
||||
|
||||
return useCallback(removeItem as RemoveItemFn<T>, [fetch, mutate])
|
||||
},
|
||||
return useCallback(removeItem as RemoveItemFn<T>, [fetch, mutate])
|
||||
},
|
||||
}
|
||||
|
@ -5,7 +5,9 @@ import type {
|
||||
HookFetcherContext,
|
||||
} from '@vercel/commerce/utils/types'
|
||||
import { ValidationError } from '@vercel/commerce/utils/errors'
|
||||
import useUpdateItem, { UseUpdateItem } from '@vercel/commerce/cart/use-update-item'
|
||||
import useUpdateItem, {
|
||||
UseUpdateItem,
|
||||
} from '@vercel/commerce/cart/use-update-item'
|
||||
import type { LineItem, UpdateItemHook } from '@vercel/commerce/types/cart'
|
||||
import { handler as removeItemHandler } from './use-remove-item'
|
||||
import useCart from './use-cart'
|
||||
@ -46,39 +48,39 @@ export const handler = {
|
||||
body: { itemId, item },
|
||||
})
|
||||
},
|
||||
useHook: ({ fetch }: MutationHookContext<UpdateItemHook>) => <
|
||||
T extends LineItem | undefined = undefined
|
||||
>(
|
||||
ctx: {
|
||||
item?: T
|
||||
wait?: number
|
||||
} = {}
|
||||
) => {
|
||||
const { item } = ctx
|
||||
const { mutate } = useCart() as any
|
||||
useHook:
|
||||
({ fetch }: MutationHookContext<UpdateItemHook>) =>
|
||||
<T extends LineItem | undefined = undefined>(
|
||||
ctx: {
|
||||
item?: T
|
||||
wait?: number
|
||||
} = {}
|
||||
) => {
|
||||
const { item } = ctx
|
||||
const { mutate } = useCart() as any
|
||||
|
||||
return useCallback(
|
||||
debounce(async (input: UpdateItemActionInput<T>) => {
|
||||
const itemId = input.id ?? item?.id
|
||||
const productId = input.productId ?? item?.productId
|
||||
const variantId = input.productId ?? item?.variantId
|
||||
return useCallback(
|
||||
debounce(async (input: UpdateItemActionInput<T>) => {
|
||||
const itemId = input.id ?? item?.id
|
||||
const productId = input.productId ?? item?.productId
|
||||
const variantId = input.productId ?? item?.variantId
|
||||
|
||||
if (!itemId || !productId || !variantId) {
|
||||
throw new ValidationError({
|
||||
message: 'Invalid input used for this operation',
|
||||
if (!itemId || !productId || !variantId) {
|
||||
throw new ValidationError({
|
||||
message: 'Invalid input used for this operation',
|
||||
})
|
||||
}
|
||||
|
||||
const data = await fetch({
|
||||
input: {
|
||||
itemId,
|
||||
item: { productId, variantId, quantity: input.quantity },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const data = await fetch({
|
||||
input: {
|
||||
itemId,
|
||||
item: { productId, variantId, quantity: input.quantity },
|
||||
},
|
||||
})
|
||||
await mutate(data, false)
|
||||
return data
|
||||
}, ctx.wait ?? 500),
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
await mutate(data, false)
|
||||
return data
|
||||
}, ctx.wait ?? 500),
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
}
|
||||
|
@ -1,5 +1,7 @@
|
||||
import { SWRHook } from '@vercel/commerce/utils/types'
|
||||
import useCheckout, { UseCheckout } from '@vercel/commerce/checkout/use-checkout'
|
||||
import useCheckout, {
|
||||
UseCheckout,
|
||||
} from '@vercel/commerce/checkout/use-checkout'
|
||||
|
||||
export default useCheckout as UseCheckout<typeof handler>
|
||||
|
||||
|
@ -6,4 +6,4 @@
|
||||
"search": true,
|
||||
"customerAuth": true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,6 @@
|
||||
import useAddItem, { UseAddItem } from '@vercel/commerce/customer/address/use-add-item'
|
||||
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>
|
||||
|
@ -1,4 +1,6 @@
|
||||
import useAddItem, { UseAddItem } from '@vercel/commerce/customer/card/use-add-item'
|
||||
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>
|
||||
|
@ -1,5 +1,7 @@
|
||||
import { SWRHook } from '@vercel/commerce/utils/types'
|
||||
import useCustomer, { UseCustomer } from '@vercel/commerce/customer/use-customer'
|
||||
import useCustomer, {
|
||||
UseCustomer,
|
||||
} from '@vercel/commerce/customer/use-customer'
|
||||
import type { CustomerHook } from '../types/customer'
|
||||
|
||||
export default useCustomer as UseCustomer<typeof handler>
|
||||
@ -13,12 +15,14 @@ export const handler: SWRHook<CustomerHook> = {
|
||||
const data = await fetch(options)
|
||||
return data?.customer ?? null
|
||||
},
|
||||
useHook: ({ useData }) => (input) => {
|
||||
return useData({
|
||||
swrOptions: {
|
||||
revalidateOnFocus: false,
|
||||
...input?.swrOptions,
|
||||
},
|
||||
})
|
||||
},
|
||||
useHook:
|
||||
({ useData }) =>
|
||||
(input) => {
|
||||
return useData({
|
||||
swrOptions: {
|
||||
revalidateOnFocus: false,
|
||||
...input?.swrOptions,
|
||||
},
|
||||
})
|
||||
},
|
||||
}
|
||||
|
@ -1,4 +1,7 @@
|
||||
import { getCommerceProvider, useCommerce as useCoreCommerce } from '@vercel/commerce'
|
||||
import {
|
||||
getCommerceProvider,
|
||||
useCommerce as useCoreCommerce,
|
||||
} from '@vercel/commerce'
|
||||
import { kiboCommerceProvider, KibocommerceProvider } from './provider'
|
||||
|
||||
export { kiboCommerceProvider }
|
||||
|
@ -1,8 +1,10 @@
|
||||
export function getCookieExpirationDate(maxAgeInDays: number){
|
||||
const today = new Date();
|
||||
const expirationDate = new Date();
|
||||
|
||||
const cookieExpirationDate = new Date ( expirationDate.setDate(today.getDate() + maxAgeInDays) )
|
||||
export function getCookieExpirationDate(maxAgeInDays: number) {
|
||||
const today = new Date()
|
||||
const expirationDate = new Date()
|
||||
|
||||
return cookieExpirationDate;
|
||||
}
|
||||
const cookieExpirationDate = new Date(
|
||||
expirationDate.setDate(today.getDate() + maxAgeInDays)
|
||||
)
|
||||
|
||||
return cookieExpirationDate
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
import type { PrCategory, CustomerAccountInput, Document } from '../../schema'
|
||||
import { Page } from '../types/page';
|
||||
import { Page } from '../types/page'
|
||||
import { Customer } from '../types/customer'
|
||||
|
||||
export function normalizeProduct(productNode: any, config: any): any {
|
||||
@ -57,7 +57,7 @@ export function normalizePage(page: Document): Page {
|
||||
url: page.properties.url,
|
||||
body: page.properties.body,
|
||||
is_visible: page.properties.is_visible,
|
||||
sort_order: page.properties.sort_order
|
||||
sort_order: page.properties.sort_order,
|
||||
}
|
||||
}
|
||||
|
||||
@ -91,7 +91,7 @@ export function normalizeCustomer(customer: CustomerAccountInput): Customer {
|
||||
lastName: customer.lastName,
|
||||
email: customer.emailAddress,
|
||||
userName: customer.userName,
|
||||
isAnonymous: customer.isAnonymous
|
||||
isAnonymous: customer.isAnonymous,
|
||||
}
|
||||
}
|
||||
|
||||
@ -133,7 +133,7 @@ export function normalizeCategory(category: PrCategory): any {
|
||||
export function normalizeWishlistItem(
|
||||
item: any,
|
||||
config: any,
|
||||
includeProducts=false
|
||||
includeProducts = false
|
||||
): any {
|
||||
if (includeProducts) {
|
||||
return {
|
||||
|
@ -1,15 +1,19 @@
|
||||
export function prepareSetCookie(name: string, value: string, options: any = {}): string {
|
||||
export function prepareSetCookie(
|
||||
name: string,
|
||||
value: string,
|
||||
options: any = {}
|
||||
): string {
|
||||
const encodedValue = Buffer.from(value).toString('base64')
|
||||
const cookieValue = [`${name}=${encodedValue}`];
|
||||
|
||||
const cookieValue = [`${name}=${encodedValue}`]
|
||||
|
||||
if (options.maxAge) {
|
||||
cookieValue.push(`Max-Age=${options.maxAge}`);
|
||||
cookieValue.push(`Max-Age=${options.maxAge}`)
|
||||
}
|
||||
|
||||
|
||||
if (options.expires && !options.maxAge) {
|
||||
cookieValue.push(`Expires=${options.expires.toUTCString()}`);
|
||||
cookieValue.push(`Expires=${options.expires.toUTCString()}`)
|
||||
}
|
||||
|
||||
|
||||
const cookie = cookieValue.join('; ')
|
||||
return cookie
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,9 @@
|
||||
function getFacetValueFilter(categoryCode: string, filters = []) {
|
||||
let facetValueFilter = '';
|
||||
if (categoryCode) {
|
||||
facetValueFilter = `categoryCode:${categoryCode},`;
|
||||
}
|
||||
return facetValueFilter + filters.join(',');
|
||||
let facetValueFilter = ''
|
||||
if (categoryCode) {
|
||||
facetValueFilter = `categoryCode:${categoryCode},`
|
||||
}
|
||||
return facetValueFilter + filters.join(',')
|
||||
}
|
||||
|
||||
export const buildProductSearchVars = ({
|
||||
@ -14,33 +14,38 @@ export const buildProductSearchVars = ({
|
||||
sort = '',
|
||||
search = '',
|
||||
}) => {
|
||||
let facetTemplate = '';
|
||||
let filter = '';
|
||||
let sortBy;
|
||||
let facetTemplate = ''
|
||||
let filter = ''
|
||||
let sortBy
|
||||
if (categoryCode) {
|
||||
facetTemplate = `categoryCode:${categoryCode}`;
|
||||
filter = `categoryCode req ${categoryCode}`;
|
||||
facetTemplate = `categoryCode:${categoryCode}`
|
||||
filter = `categoryCode req ${categoryCode}`
|
||||
}
|
||||
const facetFilterList = Object.keys(filters).filter(k => filters[k].length).reduce((accum, k): any => {
|
||||
return [...accum, ...filters[k].map((facetValue: any) => `Tenant~${k}:${facetValue}`)];
|
||||
}, []);
|
||||
const facetFilterList = Object.keys(filters)
|
||||
.filter((k) => filters[k].length)
|
||||
.reduce((accum, k): any => {
|
||||
return [
|
||||
...accum,
|
||||
...filters[k].map((facetValue: any) => `Tenant~${k}:${facetValue}`),
|
||||
]
|
||||
}, [])
|
||||
|
||||
const facetValueFilter = getFacetValueFilter(categoryCode, facetFilterList);
|
||||
const facetValueFilter = getFacetValueFilter(categoryCode, facetFilterList)
|
||||
|
||||
switch(sort) {
|
||||
switch (sort) {
|
||||
case 'latest-desc':
|
||||
sortBy= 'createDate desc';
|
||||
break;
|
||||
sortBy = 'createDate desc'
|
||||
break
|
||||
case 'price-asc':
|
||||
sortBy= 'price asc';
|
||||
break;
|
||||
sortBy = 'price asc'
|
||||
break
|
||||
case 'price-desc':
|
||||
sortBy= 'price desc';
|
||||
break;
|
||||
sortBy = 'price desc'
|
||||
break
|
||||
case 'trending-desc':
|
||||
default:
|
||||
sortBy= '';
|
||||
break;
|
||||
sortBy = ''
|
||||
break
|
||||
}
|
||||
|
||||
return {
|
||||
@ -50,6 +55,6 @@ export const buildProductSearchVars = ({
|
||||
sortBy,
|
||||
filter: filter,
|
||||
facetTemplate,
|
||||
facetValueFilter
|
||||
facetValueFilter,
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,3 @@
|
||||
export function setCookies(res: any, cookies: string[]): void {
|
||||
res.setHeader('Set-Cookie', cookies);
|
||||
}
|
||||
res.setHeader('Set-Cookie', cookies)
|
||||
}
|
||||
|
@ -4,9 +4,13 @@ module.exports = {
|
||||
commerce,
|
||||
serverRuntimeConfig: {
|
||||
// Will only be available on the server side
|
||||
kiboAuthTicket: null
|
||||
kiboAuthTicket: null,
|
||||
},
|
||||
images: {
|
||||
domains: ['d1slj7rdbjyb5l.cloudfront.net', 'cdn-tp1.mozu.com', 'cdn-sb.mozu.com'],
|
||||
domains: [
|
||||
'd1slj7rdbjyb5l.cloudfront.net',
|
||||
'cdn-tp1.mozu.com',
|
||||
'cdn-sb.mozu.com',
|
||||
],
|
||||
},
|
||||
}
|
||||
|
@ -23,15 +23,17 @@ export const handler: SWRHook<any> = {
|
||||
method: options.method,
|
||||
})
|
||||
},
|
||||
useHook: ({ useData }) => (input) => {
|
||||
return useData({
|
||||
input: [
|
||||
['search', input.search],
|
||||
['categoryId', input.categoryId],
|
||||
['brandId', input.brandId],
|
||||
['sort', input.sort],
|
||||
],
|
||||
swrOptions: { revalidateOnFocus: false, ...input?.swrOptions },
|
||||
})
|
||||
},
|
||||
useHook:
|
||||
({ useData }) =>
|
||||
(input) => {
|
||||
return useData({
|
||||
input: [
|
||||
['search', input.search],
|
||||
['categoryId', input.categoryId],
|
||||
['brandId', input.brandId],
|
||||
['sort', input.sort],
|
||||
],
|
||||
swrOptions: { revalidateOnFocus: false, ...input?.swrOptions },
|
||||
})
|
||||
},
|
||||
}
|
||||
|
@ -9,7 +9,7 @@ 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 { handler as useWishlist } from './wishlist/use-wishlist'
|
||||
import { handler as useWishlistAddItem } from './wishlist/use-add-item'
|
||||
import { handler as useWishlistAddItem } from './wishlist/use-add-item'
|
||||
import { handler as useWishlistRemoveItem } from './wishlist/use-remove-item'
|
||||
|
||||
export const kiboCommerceProvider = {
|
||||
|
@ -2,26 +2,26 @@ import * as Core from '@vercel/commerce/types/customer'
|
||||
export type Maybe<T> = T | null
|
||||
export * from '@vercel/commerce/types/customer'
|
||||
export type Scalars = {
|
||||
ID: string
|
||||
String: string
|
||||
Boolean: boolean
|
||||
Int: number
|
||||
Float: number
|
||||
/** The `AnyScalar` type allows any scalar value by examining the input and passing the serialize, parseValue, and parseLiteral operations to their respective types. */
|
||||
AnyScalar: any
|
||||
/** DateTime custom scalar type */
|
||||
DateTime: any
|
||||
/** Object custom scalar type */
|
||||
Object: any
|
||||
ID: string
|
||||
String: string
|
||||
Boolean: boolean
|
||||
Int: number
|
||||
Float: number
|
||||
/** The `AnyScalar` type allows any scalar value by examining the input and passing the serialize, parseValue, and parseLiteral operations to their respective types. */
|
||||
AnyScalar: any
|
||||
/** DateTime custom scalar type */
|
||||
DateTime: any
|
||||
/** Object custom scalar type */
|
||||
Object: any
|
||||
}
|
||||
|
||||
export type Customer = {
|
||||
id: Scalars['Int'],
|
||||
firstName?: Maybe<Scalars['String']>,
|
||||
lastName?: Maybe<Scalars['String']>,
|
||||
email?: Maybe<Scalars['String']>,
|
||||
userName?: Maybe<Scalars['String']>,
|
||||
isAnonymous?: Maybe<Scalars['Boolean']>
|
||||
id: Scalars['Int']
|
||||
firstName?: Maybe<Scalars['String']>
|
||||
lastName?: Maybe<Scalars['String']>
|
||||
email?: Maybe<Scalars['String']>
|
||||
userName?: Maybe<Scalars['String']>
|
||||
isAnonymous?: Maybe<Scalars['Boolean']>
|
||||
}
|
||||
|
||||
export type CustomerSchema = Core.CustomerSchema
|
||||
|
@ -1,17 +1,17 @@
|
||||
import * as Core from '@vercel/commerce/types/page'
|
||||
export type Maybe<T> = T | null
|
||||
export type Scalars = {
|
||||
ID: string
|
||||
String: string
|
||||
Boolean: boolean
|
||||
Int: number
|
||||
Float: number
|
||||
/** The `AnyScalar` type allows any scalar value by examining the input and passing the serialize, parseValue, and parseLiteral operations to their respective types. */
|
||||
AnyScalar: any
|
||||
/** DateTime custom scalar type */
|
||||
DateTime: any
|
||||
/** Object custom scalar type */
|
||||
Object: any
|
||||
ID: string
|
||||
String: string
|
||||
Boolean: boolean
|
||||
Int: number
|
||||
Float: number
|
||||
/** The `AnyScalar` type allows any scalar value by examining the input and passing the serialize, parseValue, and parseLiteral operations to their respective types. */
|
||||
AnyScalar: any
|
||||
/** DateTime custom scalar type */
|
||||
DateTime: any
|
||||
/** Object custom scalar type */
|
||||
Object: any
|
||||
}
|
||||
|
||||
export * from '@vercel/commerce/types/page'
|
||||
@ -19,16 +19,16 @@ export * from '@vercel/commerce/types/page'
|
||||
export type Page = Core.Page
|
||||
|
||||
export type PageTypes = {
|
||||
page: Page
|
||||
page: Page
|
||||
}
|
||||
|
||||
export type GetPagesQueryParams = {
|
||||
documentListName: Maybe<Scalars["String"]>
|
||||
documentListName: Maybe<Scalars['String']>
|
||||
}
|
||||
|
||||
export type GetPageQueryParams = {
|
||||
id: Maybe<Scalars["String"]>
|
||||
documentListName: Maybe<Scalars["String"]>
|
||||
id: Maybe<Scalars['String']>
|
||||
documentListName: Maybe<Scalars['String']>
|
||||
}
|
||||
|
||||
export type GetAllPagesOperation = Core.GetAllPagesOperation<PageTypes>
|
||||
|
@ -1,6 +1,8 @@
|
||||
import { useMemo } from 'react'
|
||||
import { SWRHook } from '@vercel/commerce/utils/types'
|
||||
import useWishlist, { UseWishlist } from '@vercel/commerce/wishlist/use-wishlist'
|
||||
import useWishlist, {
|
||||
UseWishlist,
|
||||
} from '@vercel/commerce/wishlist/use-wishlist'
|
||||
import type { GetWishlistHook } from '@vercel/commerce/types/wishlist'
|
||||
import useCustomer from '../customer/use-customer'
|
||||
|
||||
@ -11,42 +13,44 @@ export const handler: SWRHook<any> = {
|
||||
url: '/api/wishlist',
|
||||
method: 'GET',
|
||||
},
|
||||
fetcher({ input: { customerId, includeProducts}, options, fetch }) {
|
||||
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')
|
||||
if(customerId) url.searchParams.set('customerId', customerId)
|
||||
if (customerId) url.searchParams.set('customerId', customerId)
|
||||
|
||||
return fetch({
|
||||
url: url.pathname + url.search,
|
||||
method: options.method,
|
||||
})
|
||||
},
|
||||
useHook: ({ useData }) => (input) => {
|
||||
const { data: customer } = useCustomer()
|
||||
const response = useData({
|
||||
input: [
|
||||
['customerId', customer?.id],
|
||||
['includeProducts', input?.includeProducts],
|
||||
],
|
||||
swrOptions: {
|
||||
revalidateOnFocus: false,
|
||||
...input?.swrOptions,
|
||||
},
|
||||
})
|
||||
return useMemo(
|
||||
() =>
|
||||
Object.create(response, {
|
||||
isEmpty: {
|
||||
get() {
|
||||
return (response.data?.items?.length || 0) <= 0
|
||||
useHook:
|
||||
({ useData }) =>
|
||||
(input) => {
|
||||
const { data: customer } = useCustomer()
|
||||
const response = useData({
|
||||
input: [
|
||||
['customerId', customer?.id],
|
||||
['includeProducts', input?.includeProducts],
|
||||
],
|
||||
swrOptions: {
|
||||
revalidateOnFocus: false,
|
||||
...input?.swrOptions,
|
||||
},
|
||||
})
|
||||
return useMemo(
|
||||
() =>
|
||||
Object.create(response, {
|
||||
isEmpty: {
|
||||
get() {
|
||||
return (response.data?.items?.length || 0) <= 0
|
||||
},
|
||||
enumerable: true,
|
||||
},
|
||||
enumerable: true,
|
||||
},
|
||||
}),
|
||||
[response]
|
||||
)
|
||||
},
|
||||
}),
|
||||
[response]
|
||||
)
|
||||
},
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user