4
0
forked from crowetic/commerce

Added logout API

This commit is contained in:
Luis Alvarez 2020-10-22 18:02:41 -05:00
parent f81c507157
commit b81d04b952
5 changed files with 68 additions and 1 deletions

View File

@ -0,0 +1,16 @@
import { LogoutHandlers } from '../logout'
const logoutHandler: LogoutHandlers['logout'] = async ({
res,
body: { redirectTo },
config,
}) => {
// Only allow redirects to a relative URL
if (redirectTo?.startsWith('/')) {
res.redirect(redirectTo)
} else {
res.status(200).json({ data: null })
}
}
export default logoutHandler

View File

@ -0,0 +1,42 @@
import createApiHandler, {
BigcommerceApiHandler,
BigcommerceHandler,
} from '../utils/create-api-handler'
import isAllowedMethod from '../utils/is-allowed-method'
import { BigcommerceApiError } from '../utils/errors'
import logout from './handlers/logout'
export type LogoutHandlers = {
logout: BigcommerceHandler<null, { redirectTo?: string }>
}
const METHODS = ['GET']
const logoutApi: BigcommerceApiHandler<null, LogoutHandlers> = async (
req,
res,
config,
handlers
) => {
if (!isAllowedMethod(req, res, METHODS)) return
try {
const redirectTo = req.query.redirect_to
const body = typeof redirectTo === 'string' ? { redirectTo } : {}
return await handlers['logout']({ req, res, config, body })
} catch (error) {
console.error(error)
const message =
error instanceof BigcommerceApiError
? 'An unexpected error ocurred with the Bigcommerce API'
: 'An unexpected error ocurred'
res.status(500).json({ data: null, errors: [{ message }] })
}
}
const handlers = { logout }
export default createApiHandler(logoutApi, handlers, {})

View File

@ -14,7 +14,7 @@ export type BigcommerceApiHandler<
options: Options
) => void | Promise<void>
export type BigcommerceHandler<T = any, Body = any> = (options: {
export type BigcommerceHandler<T = any, Body = null> = (options: {
req: NextApiRequest
res: NextApiResponse<BigcommerceApiResponse<T>>
config: BigcommerceConfig

View File

@ -18,6 +18,12 @@ module.exports = {
source: '/checkout',
destination: '/api/bigcommerce/checkout',
},
// The logout is also an action so this route is not required, but it's also another way
// you can allow a logout!
{
source: '/logout',
destination: '/api/bigcommerce/customers/logout?redirect_to=/',
},
]
},
}

View File

@ -0,0 +1,3 @@
import logoutApi from '@lib/bigcommerce/api/customers/logout'
export default logoutApi()