This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextApiRequest, NextApiResponse } from "next"; | |
export async function handleApiRequest( | |
req: NextApiRequest, | |
res: NextApiResponse, | |
expectedReqMethod: string, | |
handleRequest: (body: any) => Promise<any> | |
): Promise<void> { | |
if (req.method === expectedReqMethod) { | |
try { | |
const responseData = await handleRequest(req.body); | |
res.status(200).json(responseData); | |
} catch (error: unknown) { | |
handleErrorResponse(res, error); | |
} | |
} else { | |
res.status(405).json({ error: "Method not allowed" }); | |
} | |
} | |
export function handleErrorResponse( | |
res: NextApiResponse, | |
error: unknown | |
): void { | |
if (error instanceof Error) { | |
res.status(500).json({ error: error.message }); | |
} else { | |
res.status(500).json({ error: "An unknown error occurred" }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage for handling both GET and POST requests: