mirror of
https://github.com/vercel/commerce.git
synced 2025-07-26 19:51:23 +00:00
Implement cart
This commit is contained in:
51
framework/ordercloud/api/endpoints/cart/get-cart.ts
Normal file
51
framework/ordercloud/api/endpoints/cart/get-cart.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import type { OrdercloudLineItem } from '../../../types/cart'
|
||||
import type { CartEndpoint } from '.'
|
||||
|
||||
import { serialize } from 'cookie'
|
||||
|
||||
import { formatCart } from '../../utils/cart'
|
||||
|
||||
// Return current cart info
|
||||
const getCart: CartEndpoint['handlers']['getCart'] = async ({
|
||||
res,
|
||||
body: { cartId },
|
||||
config: { fetch, cartCookie },
|
||||
}) => {
|
||||
if (!cartId) {
|
||||
return res.status(400).json({
|
||||
data: null,
|
||||
errors: [{ message: 'Invalid request' }],
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
// Get cart
|
||||
const cart = await fetch('GET', `/orders/Outgoing/${cartId}`)
|
||||
|
||||
// Get line items
|
||||
const lineItems = await fetch(
|
||||
'GET',
|
||||
`/orders/Outgoing/${cartId}/lineitems`
|
||||
).then((response: { Items: OrdercloudLineItem[] }) => response.Items)
|
||||
|
||||
// Format cart
|
||||
const formattedCart = formatCart(cart, lineItems)
|
||||
|
||||
// Return cart and errors
|
||||
res.status(200).json({ data: formattedCart, errors: [] })
|
||||
} catch (error) {
|
||||
// Reset cart cookie
|
||||
res.setHeader(
|
||||
'Set-Cookie',
|
||||
serialize(cartCookie, cartId, {
|
||||
maxAge: -1,
|
||||
path: '/',
|
||||
})
|
||||
)
|
||||
|
||||
// Return empty cart
|
||||
res.status(200).json({ data: null, errors: [] })
|
||||
}
|
||||
}
|
||||
|
||||
export default getCart
|
Reference in New Issue
Block a user