Last active
April 23, 2024 23:39
-
-
Save tzkmx/211f0cfcce293bf4cb13e6354bff09f0 to your computer and use it in GitHub Desktop.
Decorating App Router Route Handlers (next.js)
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
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 | |
} |
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
/** | |
* 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