Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Last active April 23, 2024 23:39
Show Gist options
  • Save tzkmx/211f0cfcce293bf4cb13e6354bff09f0 to your computer and use it in GitHub Desktop.
Save tzkmx/211f0cfcce293bf4cb13e6354bff09f0 to your computer and use it in GitHub Desktop.
Decorating App Router Route Handlers (next.js)
class HawkExperiment
{
async getEndpoint(request: Request, params: any)
{
// headers = array of key value pairs extracted from headers
let headers: {[p: string]: string} = {}
request.headers.forEach((val, key, allHeaders) => {
headers[key] = val
})
return Response.json({
headers: headers,
params
})
}
async postEndpoint(request: Request, params: any){
let headers: Record<string, string> = {}
request.headers.forEach((val, key, allHeaders) => {
headers[key] = val
})
const data = request.formData()
return Response.json({
headers: headers,
body: params
})
}
}
function handler(cls: new () => any) {
const instance = new cls()
let routes: { GET?: any, POST?: any } = {}
if (instance.getEndpoint) {
routes.GET = instance.getEndpoint
}
if (instance.postEndpoint) {
routes.POST = instance.postEndpoint
}
return routes
}
const { GET, POST } = handler(HawkExperiment)
export {
GET,
POST
}
/**
* With the previous file deployed in a catch-all route, the handler can be deployed to handle sub-routes,
* but this special wrapper should be required to make use of the top-level route.
*/
import { GET, POST } from './[...sub]/route'
export {
GET,
POST
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment