Catalin Pinte c75b0fc001
Dynamic API routes (#836)
* Add dynamic API endpoints

* Add missing dependency

* Update api handlers

* Updates

* Fix build errors

* Update package.json

* Add checkout endpoint parser & update errors

* Update tsconfig.json

* Update cart.ts

* Update parser

* Update errors.ts

* Update errors.ts

* Move to Edge runtime

* Revert to local

* Fix switchable runtimes

* Make nodejs default runtime

* Update pnpm-lock.yaml

* Update handlers

* Fix build errors

* Change headers
2022-10-30 13:41:21 -05:00

54 lines
1.3 KiB
TypeScript

import { parseWishlistItem } from '../../utils/parse-item'
import getCustomerId from '../../utils/get-customer-id'
import type { WishlistEndpoint } from '.'
const addItem: WishlistEndpoint['handlers']['addItem'] = async ({
body: { customerToken, item },
config,
commerce,
}) => {
const customerId =
customerToken && (await getCustomerId({ customerToken, config }))
if (!customerId) {
throw new Error('Invalid request. No CustomerId')
}
let { wishlist } = await commerce.getCustomerWishlist({
variables: { customerId },
config,
})
if (!wishlist) {
// If user has no wishlist, then let's create one with new item
const { data } = await config.storeApiFetch<any>('/v3/wishlists', {
method: 'POST',
body: JSON.stringify({
name: 'Next.js Commerce Wishlist',
is_public: false,
customer_id: Number(customerId),
items: [parseWishlistItem(item)],
}),
})
return {
data,
}
}
// Existing Wishlist, let's add Item to Wishlist
const { data } = await config.storeApiFetch<any>(
`/v3/wishlists/${wishlist.id}/items`,
{
method: 'POST',
body: JSON.stringify({
items: [parseWishlistItem(item)],
}),
}
)
// Returns Wishlist
return { data }
}
export default addItem