2022-06-06 16:54:47 +00:00
|
|
|
import type { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
|
|
|
|
|
|
|
|
type Handlers = {
|
|
|
|
[method in "GET" | "POST" | "PATCH" | "PUT" | "DELETE"]?: Promise<{ default: NextApiHandler }>;
|
|
|
|
};
|
|
|
|
|
2022-10-17 06:25:23 +00:00
|
|
|
/** Allows us to split big API handlers by method */
|
2022-11-17 21:38:34 +00:00
|
|
|
export const defaultHandler = (handlers: Handlers) => async (req: NextApiRequest, res: NextApiResponse) => {
|
2022-06-06 16:54:47 +00:00
|
|
|
const handler = (await handlers[req.method as keyof typeof handlers])?.default;
|
2022-10-17 06:25:23 +00:00
|
|
|
// auto catch unsupported methods.
|
|
|
|
if (!handler) {
|
|
|
|
return res
|
|
|
|
.status(405)
|
|
|
|
.json({ message: `Method Not Allowed (Allow: ${Object.keys(handlers).join(",")})` });
|
|
|
|
}
|
2022-06-06 16:54:47 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
await handler(req, res);
|
|
|
|
return;
|
|
|
|
} catch (error) {
|
|
|
|
console.error(error);
|
|
|
|
return res.status(500).json({ message: "Something went wrong" });
|
|
|
|
}
|
|
|
|
};
|