@@ -72,37 +72,48 @@ function parseCookie(req: IncomingMessage): NowRequestCookies {
72
72
return parse ( Array . isArray ( header ) ? header . join ( ';' ) : header ) ;
73
73
}
74
74
75
+ export const enhanceRequest = async (
76
+ req : IncomingMessage
77
+ ) : Promise < NowRequest > => {
78
+ const bufferOrString = await buffer ( req ) ;
79
+ return Object . assign ( req , {
80
+ body :
81
+ typeof bufferOrString === 'string'
82
+ ? bufferOrString
83
+ : parseBody ( req , bufferOrString ) ,
84
+ cookies : parseCookie ( req ) ,
85
+ query : parseQuery ( req ) ,
86
+ } ) ;
87
+ } ;
88
+
89
+ export const enhanceResponse = ( res : ServerResponse ) : NowResponse => {
90
+ let _status : number ;
91
+ const nowRes = Object . assign ( res , {
92
+ status : ( status : number ) => {
93
+ _status = status ;
94
+ return nowRes ;
95
+ } ,
96
+ json : ( jsonBody : any ) => {
97
+ send ( nowRes , _status || 200 , jsonBody ) ;
98
+ return nowRes ;
99
+ } ,
100
+ send : ( body : string | object | Buffer ) => {
101
+ send ( nowRes , _status || 200 , body ) ;
102
+ return nowRes ;
103
+ } ,
104
+ text : ( body : string ) => {
105
+ send ( nowRes , _status || 200 , body ) ;
106
+ return nowRes ;
107
+ } ,
108
+ } ) ;
109
+ return nowRes ;
110
+ } ;
111
+
75
112
export const createServer = (
76
113
route : ( req : NowRequest , res : NowResponse ) => any | Promise < any >
77
114
) =>
78
115
micro ( async ( req : IncomingMessage , res : ServerResponse ) => {
79
- const bufferOrString = await buffer ( req ) ;
80
- const nowReq = Object . assign ( req , {
81
- body :
82
- typeof bufferOrString === 'string'
83
- ? bufferOrString
84
- : parseBody ( req , bufferOrString ) ,
85
- cookies : parseCookie ( req ) ,
86
- query : parseQuery ( req ) ,
87
- } ) ;
88
- let _status : number ;
89
- const nowRes = Object . assign ( res , {
90
- status : ( status : number ) => {
91
- _status = status ;
92
- return nowRes ;
93
- } ,
94
- json : ( jsonBody : any ) => {
95
- send ( nowRes , _status || 200 , jsonBody ) ;
96
- return nowRes ;
97
- } ,
98
- send : ( body : string | object | Buffer ) => {
99
- send ( nowRes , _status || 200 , body ) ;
100
- return nowRes ;
101
- } ,
102
- text : ( body : string ) => {
103
- send ( nowRes , _status || 200 , body ) ;
104
- return nowRes ;
105
- } ,
106
- } ) ;
116
+ const nowReq = await enhanceRequest ( req ) ;
117
+ const nowRes = enhanceResponse ( res ) ;
107
118
return await route ( nowReq , nowRes ) ;
108
119
} ) ;
0 commit comments