@@ -3,31 +3,46 @@ import type { NextApiRequest, NextApiResponse } from 'next';
33import { withNextCors } from './cors' ;
44import { type ApiRequestProps } from '../../type/next' ;
55import { addLog } from '../system/log' ;
6+ import { withCSRFCheck } from './csrf' ;
67
78export type NextApiHandler < T = any > = (
89 req : ApiRequestProps ,
910 res : NextApiResponse < T >
1011) => unknown | Promise < unknown > ;
1112
13+ type NextAPIOptsType = {
14+ isCSRFCheck : boolean ;
15+ } ;
16+ type Args = [ ...NextApiHandler [ ] , NextAPIOptsType ] | NextApiHandler [ ] ;
17+
1218export const NextEntry = ( {
1319 beforeCallback = [ ]
1420} : {
1521 beforeCallback ?: ( ( req : NextApiRequest , res : NextApiResponse ) => Promise < any > ) [ ] ;
1622} ) => {
17- return ( ...args : NextApiHandler [ ] ) : NextApiHandler => {
23+ return ( ...args : Args ) : NextApiHandler => {
24+ const opts = ( ( ) => {
25+ if ( typeof args . at ( - 1 ) === 'function' ) {
26+ return {
27+ isCSRFCheck : true
28+ } as NextAPIOptsType ;
29+ }
30+ return args . at ( - 1 ) as NextAPIOptsType ;
31+ } ) ( ) ;
1832 return async function api ( req : ApiRequestProps , res : NextApiResponse ) {
1933 const start = Date . now ( ) ;
2034 addLog . debug ( `Request start ${ req . url } ` ) ;
2135
2236 try {
2337 await Promise . all ( [
2438 withNextCors ( req , res ) ,
39+ withCSRFCheck ( req , res , opts . isCSRFCheck ) ,
2540 ...beforeCallback . map ( ( item ) => item ( req , res ) )
2641 ] ) ;
2742
2843 let response = null ;
2944 for await ( const handler of args ) {
30- response = await handler ( req , res ) ;
45+ if ( typeof handler === 'function' ) response = await handler ( req , res ) ;
3146 if ( res . writableFinished ) {
3247 break ;
3348 }
0 commit comments