Allow API operations to be more customizable

This commit is contained in:
Luis Alvarez
2020-10-11 00:19:11 -05:00
parent 4c43278e67
commit 1c3714bf51
5 changed files with 149 additions and 26 deletions

View File

@@ -1,23 +1,47 @@
import type { NextApiHandler, NextApiRequest, NextApiResponse } from 'next'
import { BigcommerceConfig, getConfig } from '..'
export type BigcommerceApiHandler<T = any> = (
export type BigcommerceApiHandler<
T = any,
H extends BigcommerceHandlers = {}
> = (
req: NextApiRequest,
res: NextApiResponse<BigcommerceApiResponse<T>>,
config: BigcommerceConfig
config: BigcommerceConfig,
handlers: H
) => void | Promise<void>
export type BigcommerceHandler<T = any, Body = any> = (options: {
req: NextApiRequest
res: NextApiResponse<BigcommerceApiResponse<T>>
config: BigcommerceConfig
body: Body
}) => void | Promise<void>
export type BigcommerceHandlers<T = any> = {
[k: string]: BigcommerceHandler<T, any>
}
export type BigcommerceApiResponse<T> = {
data: T | null
errors?: { message: string }[]
}
export default function createApiHandler(handler: BigcommerceApiHandler) {
export default function createApiHandler<H extends BigcommerceHandlers>(
handler: BigcommerceApiHandler<any, H>,
handlers: H
) {
return function getApiHandler({
config,
}: { config?: BigcommerceConfig } = {}): NextApiHandler {
operations,
}: {
config?: BigcommerceConfig
operations?: Partial<H>
} = {}): NextApiHandler {
const ops = { ...operations, ...handlers }
return function apiHandler(req, res) {
return handler(req, res, getConfig(config))
return handler(req, res, getConfig(config), ops)
}
}
}