Created
November 3, 2022 20:01
-
-
Save brandonchadlange/14a46e7d39a72d857f868eb62de52f7f to your computer and use it in GitHub Desktop.
Next.js route handler for better method safety
This file contains hidden or 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 type { NextApiRequest, NextApiResponse } from "next"; | |
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE"; | |
type HttpHandler = (request: NextApiRequest, response: NextApiResponse) => void; | |
interface RouteHandlerParams { | |
GET?: HttpHandler; | |
POST?: HttpHandler; | |
PUT?: HttpHandler; | |
DELETE?: HttpHandler; | |
} | |
const RouteHandler = (handlers: RouteHandlerParams) => { | |
return async (request: NextApiRequest, response: NextApiResponse) => { | |
const method = request.method as HttpMethod; | |
const handler = handlers[method]; | |
if (!handler) { | |
return response.status(405).send("Method not allowed"); | |
} | |
return await handler!(request, response); | |
}; | |
} | |
export default RouteHandler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment