Moved wishlist

This commit is contained in:
Luis Alvarez 2021-05-22 22:52:21 -05:00
parent 90f8166762
commit 6af5794ac5
15 changed files with 275 additions and 12 deletions

View File

@ -0,0 +1,56 @@
import getCustomerWishlist from '../../../customer/get-customer-wishlist'
import { parseWishlistItem } from '../../utils/parse-item'
import getCustomerId from './utils/get-customer-id'
import type { WishlistEndpoint } from '.'
// Return wishlist info
const addItem: WishlistEndpoint['handlers']['addItem'] = async ({
res,
body: { customerToken, item },
config,
}) => {
if (!item) {
return res.status(400).json({
data: null,
errors: [{ message: 'Missing item' }],
})
}
const customerId =
customerToken && (await getCustomerId({ customerToken, config }))
if (!customerId) {
return res.status(400).json({
data: null,
errors: [{ message: 'Invalid request' }],
})
}
const { wishlist } = await getCustomerWishlist({
variables: { customerId },
config,
})
const options = {
method: 'POST',
body: JSON.stringify(
wishlist
? {
items: [parseWishlistItem(item)],
}
: {
name: 'Wishlist',
customer_id: customerId,
items: [parseWishlistItem(item)],
is_public: false,
}
),
}
const { data } = wishlist
? await config.storeApiFetch(`/v3/wishlists/${wishlist.id}/items`, options)
: await config.storeApiFetch('/v3/wishlists', options)
res.status(200).json({ data })
}
export default addItem

View File

@ -0,0 +1,38 @@
import type { Wishlist } from '../../../types/wishlist'
import type { WishlistEndpoint } from '.'
import getCustomerId from './utils/get-customer-id'
import getCustomerWishlist from '../../../customer/get-customer-wishlist'
// Return wishlist info
const getWishlist: WishlistEndpoint['handlers']['getWishlist'] = async ({
res,
body: { customerToken, includeProducts },
config,
}) => {
let result: { data?: Wishlist } = {}
if (customerToken) {
const customerId =
customerToken && (await getCustomerId({ customerToken, config }))
if (!customerId) {
// If the customerToken is invalid, then this request is too
return res.status(404).json({
data: null,
errors: [{ message: 'Wishlist not found' }],
})
}
const { wishlist } = await getCustomerWishlist({
variables: { customerId },
includeProducts,
config,
})
result = { data: wishlist }
}
res.status(200).json({ data: result.data ?? null })
}
export default getWishlist

View File

@ -0,0 +1,12 @@
import type { GetAPISchema } from '@commerce/api'
import type { WishlistSchema } from '../../../types/wishlist'
import type { BigcommerceAPI } from '../..'
import getWishlist from './get-wishlist'
import addItem from './add-item'
import removeItem from './remove-item'
export type WishlistAPI = GetAPISchema<BigcommerceAPI, WishlistSchema>
export type WishlistEndpoint = WishlistAPI['endpoint']
export const handlers = { getWishlist, addItem, removeItem }

View File

@ -0,0 +1,38 @@
import type { Wishlist } from '../../../types/wishlist'
import getCustomerWishlist from '../../../customer/get-customer-wishlist'
import getCustomerId from './utils/get-customer-id'
import type { WishlistEndpoint } from '.'
// Return wishlist info
const removeItem: WishlistEndpoint['handlers']['removeItem'] = async ({
res,
body: { customerToken, itemId },
config,
}) => {
const customerId =
customerToken && (await getCustomerId({ customerToken, config }))
const { wishlist } =
(customerId &&
(await getCustomerWishlist({
variables: { customerId },
config,
}))) ||
{}
if (!wishlist || !itemId) {
return res.status(400).json({
data: null,
errors: [{ message: 'Invalid request' }],
})
}
const result = await config.storeApiFetch<{ data: Wishlist } | null>(
`/v3/wishlists/${wishlist.id}/items/${itemId}`,
{ method: 'DELETE' }
)
const data = result?.data ?? null
res.status(200).json({ data })
}
export default removeItem

View File

@ -1,5 +1,5 @@
import { GetCustomerIdQuery } from '../schema'
import { BigcommerceConfig, getConfig } from '../api'
import type { GetCustomerIdQuery } from '../../../../schema'
import type { BigcommerceConfig } from '../../..'
export const getCustomerIdQuery = /* GraphQL */ `
query getCustomerId {
@ -14,10 +14,8 @@ async function getCustomerId({
config,
}: {
customerToken: string
config?: BigcommerceConfig
config: BigcommerceConfig
}): Promise<number | undefined> {
config = getConfig(config)
const { data } = await config.fetch<GetCustomerIdQuery>(
getCustomerIdQuery,
undefined,

View File

@ -15,6 +15,7 @@ import type { LoginAPI } from './endpoints/login'
import type { LogoutAPI } from './endpoints/logout'
import type { SignupAPI } from './endpoints/signup'
import type { ProductsAPI } from './endpoints/catalog/products'
import type { WishlistAPI } from './endpoints/wishlist'
import login from './operations/login'
import getAllPages from './operations/get-all-pages'
@ -127,6 +128,7 @@ export type APIs =
| LogoutAPI
| SignupAPI
| ProductsAPI
| WishlistAPI
export type BigcommerceAPI<P extends Provider = Provider> = CommerceAPI<P>

View File

@ -1,5 +1,5 @@
import type { WishlistHandlers } from '..'
import getCustomerId from '../../../customer/get-customer-id'
import getCustomerId from '../../endpoints/wishlist/utils/get-customer-id'
import getCustomerWishlist from '../../../customer/get-customer-wishlist'
import { parseWishlistItem } from '../../utils/parse-item'

View File

@ -1,4 +1,4 @@
import getCustomerId from '../../../customer/get-customer-id'
import getCustomerId from '../../endpoints/wishlist/utils/get-customer-id'
import getCustomerWishlist from '../../../customer/get-customer-wishlist'
import type { Wishlist, WishlistHandlers } from '..'

View File

@ -1,4 +1,4 @@
import getCustomerId from '../../../customer/get-customer-id'
import getCustomerId from '../../endpoints/wishlist/utils/get-customer-id'
import getCustomerWishlist, {
Wishlist,
} from '../../../customer/get-customer-wishlist'

View File

@ -0,0 +1,22 @@
import * as Core from '@commerce/types/wishlist'
import { definitions } from '../api/definitions/wishlist'
import type { ProductEdge } from '../product/get-all-products'
export * from '@commerce/types/wishlist'
export type WishlistItem = NonNullable<
definitions['wishlist_Full']['items']
>[0] & {
product?: ProductEdge['node']
}
export type Wishlist = Omit<definitions['wishlist_Full'], 'items'> & {
items?: WishlistItem[]
}
export type WishlistTypes = {
wishlist: Wishlist
itemBody: Core.WishlistItemBody
}
export type WishlistSchema = Core.WishlistSchema<WishlistTypes>

View File

@ -0,0 +1,58 @@
import type { WishlistSchema } from '../../types/wishlist'
import { CommerceAPIError } from '../utils/errors'
import isAllowedOperation from '../utils/is-allowed-operation'
import type { GetAPISchema } from '..'
const wishlistEndpoint: GetAPISchema<
any,
WishlistSchema
>['endpoint']['handler'] = async (ctx) => {
const { req, res, handlers, config } = ctx
if (
!isAllowedOperation(req, res, {
GET: handlers['getWishlist'],
POST: handlers['addItem'],
DELETE: handlers['removeItem'],
})
) {
return
}
const { cookies } = req
const customerToken = cookies[config.customerCookie]
try {
// Return current wishlist info
if (req.method === 'GET') {
const body = {
customerToken,
includeProducts: req.query.products === '1',
}
return await handlers['getWishlist']({ ...ctx, body })
}
// Add an item to the wishlist
if (req.method === 'POST') {
const body = { ...req.body, customerToken }
return await handlers['addItem']({ ...ctx, body })
}
// Remove an item from the wishlist
if (req.method === 'DELETE') {
const body = { ...req.body, customerToken }
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 wishlistEndpoint

View File

@ -6,7 +6,8 @@ import type { CustomerSchema } from '../types/customer'
import type { LoginSchema } from '../types/login'
import type { LogoutSchema } from '../types/logout'
import type { SignupSchema } from '../types/signup'
import type { ProductsSchema } from '@commerce/types/product'
import type { ProductsSchema } from '../types/product'
import type { WishlistSchema } from '../types/wishlist'
import {
defaultOperations,
OPERATIONS,
@ -21,6 +22,7 @@ export type APISchemas =
| LogoutSchema
| SignupSchema
| ProductsSchema
| WishlistSchema
export type GetAPISchema<
C extends CommerceAPI<any>,

View File

@ -0,0 +1,32 @@
// TODO: define this type
export type Wishlist = any
export type WishlistItemBody = {
variantId: string
productId: string
}
export type WishlistTypes = {
wishlist: Wishlist
itemBody: WishlistItemBody
}
export type WishlistSchema<T extends WishlistTypes = WishlistTypes> = {
endpoint: {
options: {}
handlers: {
getWishlist: {
data: T['wishlist'] | null
body: { customerToken?: string; includeProducts?: boolean }
}
addItem: {
data: T['wishlist']
body: { customerToken?: string; item: T['itemBody'] }
}
removeItem: {
data: T['wishlist'] | null
body: { customerToken?: string; itemId: string }
}
}
}
}

View File

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

8
pages/api/wishlist.ts Normal file
View File

@ -0,0 +1,8 @@
import wishlist from '@commerce/api/endpoints/wishlist'
import { WishlistAPI, handlers } from '@framework/api/endpoints/wishlist'
import commerce from '@lib/api/commerce'
export default commerce.endpoint({
handler: wishlist as WishlistAPI['endpoint']['handler'],
handlers,
})