mirror of
https://github.com/LukeHagar/vercel.git
synced 2025-12-06 21:07:47 +00:00
I was doing a diff and noticed this returns the wrong status code. This PR changes the unknown method response to [405 Method Not Allowed](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405) status code.
45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
import { NowRequest, NowResponse } from '@now/node';
|
|
import { errorHandler } from './error-handler';
|
|
|
|
type Handler = (req: NowRequest, res: NowResponse) => Promise<any>;
|
|
|
|
export function withApiHandler(handler: Handler): Handler {
|
|
return async (req: NowRequest, res: NowResponse) => {
|
|
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
res.setHeader('Access-Control-Allow-Methods', 'GET');
|
|
res.setHeader(
|
|
'Access-Control-Allow-Headers',
|
|
'Authorization, Accept, Content-Type'
|
|
);
|
|
|
|
if (req.method === 'OPTIONS') {
|
|
return res.status(200).json({});
|
|
}
|
|
|
|
if (req.method !== 'GET') {
|
|
return res.status(405).json({
|
|
error: {
|
|
code: 'method_not_allowed',
|
|
message: 'Only GET requests are supported for this endpoint.',
|
|
},
|
|
});
|
|
}
|
|
|
|
try {
|
|
const result = await handler(req, res);
|
|
return result;
|
|
} catch (error) {
|
|
errorHandler(error, {
|
|
url: req.url,
|
|
});
|
|
|
|
return res.status(500).json({
|
|
error: {
|
|
code: 'unexpected_error',
|
|
message: 'An unexpected error occurred.',
|
|
},
|
|
});
|
|
}
|
|
};
|
|
}
|