-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.d.ts
1283 lines (1127 loc) · 35.3 KB
/
index.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import accepts = require('accepts');
import { AsyncLocalStorage } from 'async_hooks';
import { EventEmitter } from 'events'
import { Readable } from 'stream';
import { Socket } from 'net';
import { IncomingMessage, ServerResponse } from 'http';
import KoaApplication = require('koa');
import KoaRouter = require('koa-router');
import {
EggLogger as Logger,
EggLoggers,
LoggerLevel as EggLoggerLevel,
EggLoggersOptions,
EggLoggerOptions,
EggContextLogger,
} from 'egg-logger';
import {
RequestOptions2 as RequestOptionsOld,
HttpClientResponse as HttpClientResponseOld,
} from 'urllib';
import {
RequestURL as HttpClientRequestURL,
RequestOptions as HttpClientRequestOptions,
HttpClientResponse,
} from 'urllib-next';
import {
EggCoreBase,
FileLoaderOption,
EggLoader as CoreLoader,
EggCoreOptions as CoreOptions,
EggLoaderOptions as CoreLoaderOptions,
BaseContextClass as CoreBaseContextClass,
} from 'egg-core';
import EggCookies = require('egg-cookies');
import 'egg-onerror';
import 'egg-session';
import 'egg-i18n';
import 'egg-watcher';
import 'egg-multipart';
import 'egg-security';
import 'egg-development';
import 'egg-logrotator';
import 'egg-schedule';
import 'egg-static';
import 'egg-jsonp';
import 'egg-view';
declare module 'egg' {
export type EggLogger = Logger;
// plain object
type PlainObject<T = any> = { [key: string]: T };
// Remove specific property from the specific class
type RemoveSpecProp<T, P> = Pick<T, Exclude<keyof T, P>>;
// Usage:
// ```ts
// import { HttpClientRequestURL, HttpClientRequestOptions, HttpClientResponse } from 'egg';
// async function request(url: HttpClientRequestURL, options: HttpClientRequestOptions): Promise<HttpClientResponse> {
// return await app.httpclient.request(url, options);
// }
// ```
export { HttpClientRequestURL, HttpClientRequestOptions, HttpClientResponse };
// Compatible with both urllib@2 and urllib@3 RequestOptions to request
export interface EggHttpClient extends EventEmitter {
request<T = any>(url: HttpClientRequestURL): Promise<HttpClientResponseOld<T> | HttpClientResponse<T>>;
request<T = any>(url: HttpClientRequestURL, options: RequestOptionsOld | HttpClientRequestOptions):
Promise<HttpClientResponseOld<T> | HttpClientResponse<T>>;
curl<T = any>(url: HttpClientRequestURL): Promise<HttpClientResponseOld<T> | HttpClientResponse<T>>;
curl<T = any>(url: HttpClientRequestURL, options: RequestOptionsOld | HttpClientRequestOptions):
Promise<HttpClientResponseOld<T> | HttpClientResponse<T>>;
}
interface EggHttpConstructor {
new(app: Application): EggHttpClient;
}
export interface EggContextHttpClient extends EggHttpClient { }
interface EggContextHttpClientConstructor {
new(ctx: Context): EggContextHttpClient;
}
/**
* BaseContextClass is a base class that can be extended,
* it's instantiated in context level,
* {@link Helper}, {@link Service} is extending it.
*/
export class BaseContextClass extends CoreBaseContextClass<Context, Application, EggAppConfig, IService> { // tslint:disable-line
/**
* logger
*/
protected logger: EggLogger;
}
export class Boot {
/**
* logger
* @member {EggLogger}
*/
protected logger: EggLogger;
/**
* The configuration of application
* @member {EggAppConfig}
*/
protected config: EggAppConfig;
/**
* The instance of agent
* @member {Agent}
*/
protected agent: Agent;
/**
* The instance of app
* @member {Application}
*/
protected app: Application;
}
export type RequestArrayBody = any[];
export type RequestObjectBody = PlainObject;
export interface Request extends KoaApplication.Request { // tslint:disable-line
/**
* detect if response should be json
* 1. url path ends with `.json`
* 2. response type is set to json
* 3. detect by request accept header
*
* @member {Boolean} Request#acceptJSON
* @since 1.0.0
*/
acceptJSON: boolean;
/**
* Request remote IPv4 address
* @member {String} Request#ip
* @example
* ```js
* this.request.ip
* => '127.0.0.1'
* => '111.10.2.1'
* ```
*/
ip: string;
/**
* Get all pass through ip addresses from the request.
* Enable only on `app.config.proxy = true`
*
* @member {Array} Request#ips
* @example
* ```js
* this.request.ips
* => ['100.23.1.2', '201.10.10.2']
* ```
*/
ips: string[];
protocol: string;
/**
* get params pass by querystring, all value are Array type. {@link Request#query}
* @member {Array} Request#queries
* @example
* ```js
* GET http://127.0.0.1:7001?a=b&a=c&o[foo]=bar&b[]=1&b[]=2&e=val
* this.queries
* =>
* {
* "a": ["b", "c"],
* "o[foo]": ["bar"],
* "b[]": ["1", "2"],
* "e": ["val"]
* }
* ```
*/
queries: PlainObject<string[]>;
/**
* get params pass by querystring, all value are String type.
* @member {Object} Request#query
* @example
* ```js
* GET http://127.0.0.1:7001?name=Foo&age=20&age=21
* this.query
* => { 'name': 'Foo', 'age': 20 }
*
* GET http://127.0.0.1:7001?a=b&a=c&o[foo]=bar&b[]=1&b[]=2&e=val
* this.query
* =>
* {
* "a": "b",
* "o[foo]": "bar",
* "b[]": "1",
* "e": "val"
* }
* ```
*/
query: PlainObject<string>;
body: any;
}
export interface Response<ResponseBodyT = any> extends KoaApplication.Response { // tslint:disable-line
/**
* read response real status code.
*
* e.g.: Using 302 status redirect to the global error page
* instead of show current 500 status page.
* And access log should save 500 not 302,
* then the `realStatus` can help us find out the real status code.
* @member {Number} Context#realStatus
*/
realStatus: number;
body: ResponseBodyT;
}
export type LoggerLevel = EggLoggerLevel;
/**
* egg app info
* @example
* ```js
* // config/config.default.ts
* import { EggAppInfo } from 'egg';
*
* export default (appInfo: EggAppInfo) => {
* return {
* keys: appInfo.name + '123456',
* };
* }
* ```
*/
export interface EggAppInfo {
pkg: any; // package.json
name: string; // the application name from package.json
baseDir: string; // current directory of application
env: EggEnvType; // equals to serverEnv
HOME: string; // home directory of the OS
root: string; // baseDir when local and unittest, HOME when other environment
}
type IgnoreItem = string | RegExp | ((ctx: Context) => boolean);
type IgnoreOrMatch = IgnoreItem | IgnoreItem[];
/** logger config of egg */
export interface EggLoggerConfig extends RemoveSpecProp<EggLoggersOptions, 'type'> {
/** custom config of coreLogger */
coreLogger?: Partial<EggLoggerOptions>;
/** allow debug log at prod, defaults to `false` */
allowDebugAtProd?: boolean;
/** disable logger console after app ready. defaults to `false` on local and unittest env, others is `true`. */
disableConsoleAfterReady?: boolean;
/** using performance.now() timer instead of Date.now() for more more precise milliseconds, defaults to `false`. e.g.: logger will set 1.456ms instead of 1ms. */
enablePerformanceTimer?: boolean;
/** using the app logger instead of EggContextLogger, defaults to `false` */
enableFastContextLogger?: boolean;
}
/** Custom Loader Configuration */
export interface CustomLoaderConfig extends RemoveSpecProp<FileLoaderOption, 'inject' | 'target'> {
/**
* an object you wanner load to, value can only be 'ctx' or 'app'. default to app
*/
inject?: 'ctx' | 'app';
/**
* whether need to load files in plugins or framework, default to false
*/
loadunit?: boolean;
}
export interface HttpClientBaseConfig {
/** Whether use http keepalive */
keepAlive?: boolean;
/** Free socket after keepalive timeout */
freeSocketKeepAliveTimeout?: number;
/** Free socket after request timeout */
freeSocketTimeout?: number;
/** Request timeout */
timeout?: number;
/** Determines how many concurrent sockets the agent can have open per origin */
maxSockets?: number;
/** The maximum number of sockets that will be left open in the free state */
maxFreeSockets?: number;
}
/** HttpClient config */
export interface HttpClientConfig extends HttpClientBaseConfig {
/** http.Agent */
httpAgent?: HttpClientBaseConfig;
/** https.Agent */
httpsAgent?: HttpClientBaseConfig;
/** Default request args for httpclient */
request?: HttpClientRequestOptions | RequestOptionsOld;
/** Whether enable dns cache */
enableDNSCache?: boolean;
/** Enable proxy request, default is false. */
enableProxy?: boolean;
/** proxy agent uri or options, default is null. */
proxy?: string | { [key: string]: any };
/** DNS cache lookup interval */
dnsCacheLookupInterval?: number;
/** DNS cache max age */
dnsCacheMaxLength?: number;
/** use urllib@3 HttpClient */
useHttpClientNext?: boolean;
}
export interface EggAppConfig {
workerStartTimeout: number;
baseDir: string;
middleware: string[];
/**
* The option of `bodyParser` middleware
*
* @member Config#bodyParser
* @property {Boolean} enable - enable bodyParser or not, default to true
* @property {String | RegExp | Function | Array} ignore - won't parse request body when url path hit ignore pattern, can not set `ignore` when `match` presented
* @property {String | RegExp | Function | Array} match - will parse request body only when url path hit match pattern
* @property {String} encoding - body encoding config, default utf8
* @property {String} formLimit - form body size limit, default 1mb
* @property {String} jsonLimit - json body size limit, default 1mb
* @property {String} textLimit - json body size limit, default 1mb
* @property {Boolean} strict - json body strict mode, if set strict value true, then only receive object and array json body
* @property {Number} queryString.arrayLimit - from item array length limit, default 100
* @property {Number} queryString.depth - json value deep length, default 5
* @property {Number} queryString.parameterLimit - parameter number limit, default 1000
* @property {String[]} enableTypes - parser will only parse when request type hits enableTypes, default is ['json', 'form']
* @property {Object} extendTypes - support extend types
* @property {String} onProtoPoisoning - Defines what action must take when parsing a JSON object with `__proto__`. Possible values are `'error'`, `'remove'` and `'ignore'`. Default is `'error'`, it will return `400` response when `Prototype-Poisoning` happen.
*/
bodyParser: {
enable: boolean;
encoding: string;
formLimit: string;
jsonLimit: string;
textLimit: string;
strict: boolean;
queryString: {
arrayLimit: number;
depth: number;
parameterLimit: number;
};
ignore: IgnoreOrMatch;
match: IgnoreOrMatch;
enableTypes: string[];
extendTypes: {
json: string[];
form: string[];
text: string[];
};
/** Default is `'error'`, it will return `400` response when `Prototype-Poisoning` happen. */
onProtoPoisoning: 'error' | 'remove' | 'ignore';
};
/**
* logger options
* @member Config#logger
* @property {String} dir - directory of log files
* @property {String} encoding - log file encloding, defaults to utf8
* @property {String} level - default log level, could be: DEBUG, INFO, WARN, ERROR or NONE, defaults to INFO in production
* @property {String} consoleLevel - log level of stdout, defaults to INFO in local serverEnv, defaults to WARN in unittest, defaults to NONE elsewise
* @property {Boolean} disableConsoleAfterReady - disable logger console after app ready. defaults to `false` on local and unittest env, others is `true`.
* @property {Boolean} outputJSON - log as JSON or not, defaults to false
* @property {Boolean} buffer - if enabled, flush logs to disk at a certain frequency to improve performance, defaults to true
* @property {String} errorLogName - file name of errorLogger
* @property {String} coreLogName - file name of coreLogger
* @property {String} agentLogName - file name of agent worker log
* @property {Object} coreLogger - custom config of coreLogger
* @property {Boolean} allowDebugAtProd - allow debug log at prod, defaults to false
* @property {Boolean} enablePerformanceTimer - using performance.now() timer instead of Date.now() for more more precise milliseconds, defaults to false. e.g.: logger will set 1.456ms instead of 1ms.
* @property {Boolean} enableFastContextLogger - using the app logger instead of EggContextLogger, defaults to false
*/
logger: EggLoggerConfig;
/** custom logger of egg */
customLogger: {
[key: string]: EggLoggerOptions;
};
/** Configuration of httpclient in egg. */
httpclient: HttpClientConfig;
development: {
/**
* dirs needed watch, when files under these change, application will reload, use relative path
*/
watchDirs: string[];
/**
* dirs don't need watch, including subdirectories, use relative path
*/
ignoreDirs: string[];
/**
* don't wait all plugins ready, default is true.
*/
fastReady: boolean;
/**
* whether reload on debug, default is true.
*/
reloadOnDebug: boolean;
/**
* whether override default watchDirs, default is false.
*/
overrideDefault: boolean;
/**
* whether override default ignoreDirs, default is false.
*/
overrideIgnore: boolean;
/**
* whether to reload, use https://github.com/sindresorhus/multimatch
*/
reloadPattern: string[] | string;
};
/**
* customLoader config
*/
customLoader: {
[key: string]: CustomLoaderConfig;
};
/**
* It will ignore special keys when dumpConfig
*/
dump: {
ignore: Set<string>;
};
/**
* The environment of egg
*/
env: EggEnvType;
/**
* The current HOME directory
*/
HOME: string;
hostHeaders: string;
/**
* I18n options
*/
i18n: {
/**
* default value EN_US
*/
defaultLocale: string;
/**
* i18n resource file dir, not recommend to change default value
*/
dirs: string[];
/**
* custom the locale value field, default `query.locale`, you can modify this config, such as `query.lang`
*/
queryField: string;
/**
* The locale value key in the cookie, default is locale.
*/
cookieField: string;
/**
* Locale cookie expire time, default `1y`, If pass number value, the unit will be ms
*/
cookieMaxAge: string | number;
};
/**
* Detect request' ip from specified headers, not case-sensitive. Only worked when config.proxy set to true.
*/
ipHeaders: string;
/**
* jsonp options
* @member Config#jsonp
* @property {String} callback - jsonp callback method key, default to `_callback`
* @property {Number} limit - callback method name's max length, default to `50`
* @property {Boolean} csrf - enable csrf check or not. default to false
* @property {String|RegExp|Array} whiteList - referrer white list
*/
jsonp: {
limit: number;
callback: string;
csrf: boolean;
whiteList: string | RegExp | Array<string | RegExp>;
};
/**
* The key that signing cookies. It can contain multiple keys seperated by .
*/
keys: string;
/**
* The name of the application
*/
name: string;
/**
* package.json
*/
pkg: any;
rundir: string;
security: {
domainWhiteList: string[];
protocolWhiteList: string[];
defaultMiddleware: string;
csrf: any;
ssrf: {
ipBlackList: string[];
ipExceptionList: string[];
checkAddress?(ip: string): boolean;
};
xframe: {
enable: boolean;
value: 'SAMEORIGIN' | 'DENY' | 'ALLOW-FROM';
};
hsts: any;
methodnoallow: { enable: boolean };
noopen: { enable: boolean; }
xssProtection: any;
csp: any;
};
siteFile: PlainObject<string | Buffer>;
watcher: PlainObject;
onClientError(err: Error, socket: Socket, app: EggApplication): ClientErrorResponse | Promise<ClientErrorResponse>;
/**
* server timeout in milliseconds, default to 0 (no timeout).
*
* for special request, just use `ctx.req.setTimeout(ms)`
*
* @see https://nodejs.org/api/http.html#http_server_timeout
*/
serverTimeout: number | null;
[prop: string]: any;
}
export interface ClientErrorResponse {
body: string | Buffer;
status: number;
headers: { [key: string]: string };
}
export interface Router extends Omit<KoaRouter<any, Context>, 'url'> {
/**
* restful router api
*/
resources(name: string, prefix: string, ...middleware: any[]): Router;
/**
* @param {String} name - Router name
* @param {Object} [params] - more parameters
* @example
* ```js
* router.url('edit_post', { id: 1, name: 'foo', page: 2 })
* => /posts/1/edit?name=foo&page=2
* router.url('posts', { name: 'foo&1', page: 2 })
* => /posts?name=foo%261&page=2
* ```
* @return {String} url by path name and query params.
* @since 1.0.0
*/
url(name: string, params?: any): string;
/**
* Alias for the url method
*/
pathFor(name: string, params?: any): string;
methods: string[];
}
export interface EggApplication extends Omit<EggCoreBase<EggAppConfig>, 'ctxStorage' | 'currentContext'> {
/**
* HttpClient instance
*/
httpclient: EggHttpClient;
/**
* Logger for Application, wrapping app.coreLogger with context infomation
*
* @member {ContextLogger} Context#logger
* @since 1.0.0
* @example
* ```js
* this.logger.info('some request data: %j', this.request.body);
* this.logger.warn('WARNING!!!!');
* ```
*/
logger: EggLogger;
/**
* core logger for framework and plugins, log file is $HOME/logs/{appname}/egg-web
*/
coreLogger: EggLogger;
/**
* All loggers contain logger, coreLogger and customLogger
*/
loggers: EggLoggers;
/**
* messenger instance
*/
messenger: Messenger;
/**
* get router
*/
router: Router;
/**
* create a singleton instance
*/
addSingleton(name: string, create: any): void;
runSchedule(schedulePath: string, ...args: any[]): Promise<any>;
/**
* http request helper base on httpclient, it will auto save httpclient log.
* Keep the same api with httpclient.request(url, args).
* See https://github.com/node-modules/urllib#api-doc for more details.
*/
curl: EggHttpClient['request'];
/**
* Get logger by name, it's equal to app.loggers['name'], but you can extend it with your own logical
*/
getLogger(name: string): EggLogger;
/**
* print the infomation when console.log(app)
*/
inspect(): any;
/**
* Alias to Router#url
*/
url(name: string, params: any): any;
/**
* Create an anonymous context, the context isn't request level, so the request is mocked.
* then you can use context level API like `ctx.service`
* @member {String} EggApplication#createAnonymousContext
* @param {Request} req - if you want to mock request like querystring, you can pass an object to this function.
* @return {Context} context
*/
createAnonymousContext(req?: Request): Context;
/**
* export context base classes, let framework can impl sub class and over context extend easily.
*/
ContextCookies: typeof EggCookies;
ContextLogger: typeof EggContextLogger;
ContextHttpClient: EggContextHttpClientConstructor;
HttpClient: EggHttpConstructor;
Subscription: typeof Subscription;
Controller: typeof Controller;
Service: typeof Service;
}
// compatible
export class EggApplication {
constructor(options?: CoreOptions);
}
export type RouterPath = string | RegExp;
export class Application extends EggApplication {
/**
* global locals for view
* @see Context#locals
*/
locals: IApplicationLocals;
/**
* HTTP get method
*/
get(path: RouterPath, fn: string): void;
get(path: RouterPath, ...middleware: any[]): void;
/**
* HTTP post method
*/
post(path: RouterPath, fn: string): void;
post(path: RouterPath, ...middleware: any[]): void;
/**
* HTTP put method
*/
put(path: RouterPath, fn: string): void;
put(path: RouterPath, ...middleware: any[]): void;
/**
* HTTP patch method
*/
patch(path: RouterPath, fn: string): void;
patch(path: RouterPath, ...middleware: any[]): void;
/**
* HTTP delete method
*/
delete(path: RouterPath, fn: string): void;
delete(path: RouterPath, ...middleware: any[]): void;
/**
* restful router api
*/
resources(name: string, prefix: string, fn: string): Router;
resources(path: string, prefix: string, ...middleware: any[]): Router;
redirect(path: string, redirectPath: string): void;
controller: IController;
middleware: KoaApplication.Middleware[] & IMiddleware;
/**
* Run async function in the background
* @see Context#runInBackground
* @param {Function} scope - the first args is an anonymous ctx
*/
runInBackground(scope: (ctx: Context) => void): void;
/**
* Run async function in the anonymous context scope
* @see Context#runInAnonymousContextScope
* @param {Function} scope - the first args is an anonymous ctx, scope should be async function
* @param {Request} req - if you want to mock request like querystring, you can pass an object to this function.
*/
runInAnonymousContextScope<R>(scope: (ctx: Context) => Promise<R>, req?: Request): Promise<R>;
/**
* Get current execute ctx async local storage
* @returns {AsyncLocalStorage} localStorage - store current execute Context
*/
get ctxStorage(): AsyncLocalStorage<Context>;
/**
* Get current execute ctx, maybe undefined
* @returns {Context} ctx - current execute Context
*/
get currentContext(): Context;
}
export interface IApplicationLocals extends PlainObject { }
export interface FileStream extends Readable { // tslint:disable-line
fields: any;
filename: string;
fieldname: string;
mime: string;
mimeType: string;
transferEncoding: string;
encoding: string;
truncated: boolean;
}
interface GetFileStreamOptions {
requireFile?: boolean; // required file submit, default is true
defCharset?: string;
limits?: {
fieldNameSize?: number;
fieldSize?: number;
fields?: number;
fileSize?: number;
files?: number;
parts?: number;
headerPairs?: number;
};
checkFile?(
fieldname: string,
file: any,
filename: string,
encoding: string,
mimetype: string
): void | Error;
}
/**
* KoaApplication's Context will carry the default 'cookie' property in
* the egg's Context interface, which is wrong here because we have our own
* special properties (e.g: encrypted). So we must remove this property and
* create our own with the same name.
* @see https://github.com/eggjs/egg/pull/2958
*
* However, the latest version of Koa has "[key: string]: any" on the
* context, and there'll be a type error for "keyof koa.Context".
* So we have to directly inherit from "KoaApplication.BaseContext" and
* rewrite all the properties to be compatible with types in Koa.
* @see https://github.com/eggjs/egg/pull/3329
*/
export interface Context<ResponseBodyT = any> extends KoaApplication.BaseContext {
[key: string]: any;
body: ResponseBodyT;
app: Application;
// properties of koa.Context
req: IncomingMessage;
res: ServerResponse;
originalUrl: string;
respond?: boolean;
service: IService;
request: Request;
response: Response<ResponseBodyT>;
// The new 'cookies' instead of Koa's.
cookies: EggCookies;
helper: IHelper;
/**
* Resource Parameters
* @example
* ##### ctx.params.id {string}
*
* `GET /api/users/1` => `'1'`
*
* ##### ctx.params.ids {Array<String>}
*
* `GET /api/users/1,2,3` => `['1', '2', '3']`
*
* ##### ctx.params.fields {Array<String>}
*
* Expect request return data fields, for example
* `GET /api/users/1?fields=name,title` => `['name', 'title']`.
*
* ##### ctx.params.data {Object}
*
* Tht request data object
*
* ##### ctx.params.page {Number}
*
* Page number, `GET /api/users?page=10` => `10`
*
* ##### ctx.params.per_page {Number}
*
* The number of every page, `GET /api/users?per_page=20` => `20`
*/
params: any;
/**
* @see Request#query
*/
query: PlainObject<string>;
/**
* @see Request#queries
*/
queries: PlainObject<string[]>;
/**
* @see Request#accept
*/
accept: accepts.Accepts;
/**
* @see Request#acceptJSON
*/
acceptJSON: boolean;
/**
* @see Request#ip
*/
ip: string;
/**
* @see Response#realStatus
*/
realStatus: number;
/**
* Set the ctx.body.data value
*
* @member {Object} Context#data=
* @example
* ```js
* ctx.data = {
* id: 1,
* name: 'fengmk2'
* };
* ```
*
* will get responce
*
* ```js
* HTTP/1.1 200 OK
*
* {
* "data": {
* "id": 1,
* "name": "fengmk2"
* }
* }
* ```
*/
data: any;
/**
* set ctx.body.meta value
*
* @example
* ```js
* ctx.meta = {
* count: 100
* };
* ```
* will get responce
*
* ```js
* HTTP/1.1 200 OK
*
* {
* "meta": {
* "count": 100
* }
* }
* ```
*/
meta: any;
/**
* locals is an object for view, you can use `app.locals` and `ctx.locals` to set variables,
* which will be used as data when view is rendering.
* The difference between `app.locals` and `ctx.locals` is the context level, `app.locals` is global level, and `ctx.locals` is request level. when you get `ctx.locals`, it will merge `app.locals`.
*
* when you set locals, only object is available
*
* ```js
* this.locals = {
* a: 1
* };
* this.locals = {
* b: 1
* };
* this.locals.c = 1;
* console.log(this.locals);
* {
* a: 1,
* b: 1,
* c: 1,
* };
* ```
*
* `ctx.locals` has cache, it only merges `app.locals` once in one request.
*
* @member {Object} Context#locals
*/
locals: IApplicationLocals & IContextLocals;
/**
* alias to {@link locals}, compatible with koa that use this variable
*/
state: any;
/**
* Logger for Application, wrapping app.coreLogger with context infomation
*
* @member {ContextLogger} Context#logger
* @since 1.0.0
* @example
* ```js
* this.logger.info('some request data: %j', this.request.body);
* this.logger.warn('WARNING!!!!');
* ```
*/
logger: EggLogger;
/**
* Get logger by name, it's equal to app.loggers['name'], but you can extend it with your own logical
*/
getLogger(name: string): EggLogger;
/**
* Request start time
*/
starttime: number;
/**
* Request start timer using `performance.now()`
*/
performanceStarttime?: number;