Updated cart endpoint

This commit is contained in:
Luis Alvarez 2021-03-31 22:57:36 -06:00
parent c9f13989ec
commit 779c6bed2d
2 changed files with 14 additions and 14 deletions

View File

@ -1,19 +1,19 @@
import type { APIEndpoint } from '../utils/types'
import type { CartSchema } from '../../types/cart'
import { CommerceAPIError } from '../utils/errors'
import isAllowedOperation from '../utils/is-allowed-operation'
import type { GetAPISchema, CartSchema } from '..'
import type { GetAPISchema } from '..'
const cartApi: GetAPISchema<any, CartSchema>['endpoint']['handler'] = async (
ctx
) => {
const { req, res, handlers, config } = ctx
const { req, res, operations, config } = ctx
if (
!isAllowedOperation(req, res, {
GET: handlers['getCart'],
POST: handlers['addItem'],
PUT: handlers['updateItem'],
DELETE: handlers['removeItem'],
GET: operations['getCart'],
POST: operations['addItem'],
PUT: operations['updateItem'],
DELETE: operations['removeItem'],
})
) {
return
@ -27,25 +27,25 @@ const cartApi: GetAPISchema<any, CartSchema>['endpoint']['handler'] = async (
// Return current cart info
if (req.method === 'GET') {
const body = { cartId }
return await handlers['getCart']({ ...ctx, body })
return await operations['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 })
return await operations['addItem']({ ...ctx, body })
}
// Update item in cart
if (req.method === 'PUT') {
const body = { ...req.body, cartId }
return await handlers['updateItem']({ ...ctx, body })
return await operations['updateItem']({ ...ctx, body })
}
// Remove an item from the cart
if (req.method === 'DELETE') {
const body = { ...req.body, cartId }
return await handlers['removeItem']({ ...ctx, body })
return await operations['removeItem']({ ...ctx, body })
}
} catch (error) {
console.error(error)

View File

@ -5,11 +5,11 @@ import { APIHandler } from './types'
export default function isAllowedOperation(
req: NextApiRequest,
res: NextApiResponse,
allowedHandlers: { [k in HTTP_METHODS]?: APIHandler<any, any> }
allowedOperations: { [k in HTTP_METHODS]?: APIHandler<any, any> }
) {
const methods = Object.keys(allowedHandlers) as HTTP_METHODS[]
const methods = Object.keys(allowedOperations) as HTTP_METHODS[]
const allowedMethods = methods.reduce<HTTP_METHODS[]>((arr, method) => {
if (allowedHandlers[method]) {
if (allowedOperations[method]) {
arr.push(method)
}
return arr