11import { GlobalEventHandler } from './event' ;
2+ import { merge } from 'lodash' ;
23
34
45
@@ -54,7 +55,7 @@ export class Ajax {
5455 * @param requestBody body mime type, default auto derive
5556 * @returns {Promise<any> }
5657 */
57- static async send ( url : string , data : any = { } , method = 'GET' , expectedDataType = 'json' , requestBody = 'formdata' ) : Promise < any > {
58+ static async send < T = any > ( url : string , data : any = { } , method = 'GET' , expectedDataType = 'json' , requestBody = 'formdata' , options : Partial < RequestInit > = { } ) : Promise < T > {
5859 // for compatibility
5960 method = method . toUpperCase ( ) ;
6061
@@ -67,50 +68,50 @@ export class Ajax {
6768 }
6869 }
6970
70- const options : RequestInit = {
71+ const mergedOptions : RequestInit = merge ( {
7172 credentials : 'same-origin' ,
7273 method,
7374 headers : {
7475 'Accept' : 'application/json'
7576 } ,
76- } ;
77+ } , options ) ;
7778
7879 if ( data ) {
7980 let mimetype : string = '' ;
8081 switch ( requestBody . trim ( ) . toLowerCase ( ) ) {
8182 case 'json' :
8283 case 'application/json' :
8384 mimetype = 'application/json' ;
84- options . body = typeof data === 'string' ? data : JSON . stringify ( data ) ;
85+ mergedOptions . body = typeof data === 'string' ? data : JSON . stringify ( data ) ;
8586 break ;
8687 case 'text' :
8788 case 'text/plain' :
8889 mimetype = 'text/plain' ;
89- options . body = String ( data ) ;
90+ mergedOptions . body = String ( data ) ;
9091 break ;
9192 case 'blob' :
9293 case 'arraybuffer' :
9394 mimetype = 'application/octet-stream' ;
94- options . body = data ;
95+ mergedOptions . body = data ;
9596 break ;
9697 default :
9798 if ( data instanceof FormData ) {
98- options . body = data ;
99+ mergedOptions . body = data ;
99100 } else {
100101 mimetype = 'application/x-www-form-urlencoded' ;
101- options . body = Ajax . encodeParams ( data ) ;
102+ mergedOptions . body = Ajax . encodeParams ( data ) ;
102103 }
103104 }
104105 if ( mimetype ) {
105- ( < any > options . headers ) [ 'Content-Type' ] = mimetype ;
106+ mergedOptions . headers [ 'Content-Type' ] = mimetype ;
106107 }
107108 }
108109
109110 // there are no typings for fetch so far
110- GlobalEventHandler . getInstance ( ) . fire ( Ajax . GLOBAL_EVENT_AJAX_PRE_SEND , url , options ) ;
111- const r = Ajax . checkStatus ( await self . fetch ( url , options ) ) ;
111+ GlobalEventHandler . getInstance ( ) . fire ( Ajax . GLOBAL_EVENT_AJAX_PRE_SEND , url , mergedOptions ) ;
112+ const r = Ajax . checkStatus ( await self . fetch ( url , mergedOptions ) ) ;
112113 const output = Ajax . parseType ( expectedDataType , r ) ;
113- GlobalEventHandler . getInstance ( ) . fire ( Ajax . GLOBAL_EVENT_AJAX_POST_SEND , url , options , r , output ) ;
114+ GlobalEventHandler . getInstance ( ) . fire ( Ajax . GLOBAL_EVENT_AJAX_POST_SEND , url , mergedOptions , r , output ) ;
114115 return output ;
115116 }
116117 /**
0 commit comments