-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathegg.ts
More file actions
619 lines (554 loc) · 18.6 KB
/
egg.ts
File metadata and controls
619 lines (554 loc) · 18.6 KB
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
import assert from 'node:assert';
import { debuglog } from 'node:util';
import {
Application as KoaApplication,
Context as KoaContext,
Request as KoaRequest,
Response as KoaResponse,
type MiddlewareFunc as KoaMiddlewareFunc,
type Next,
} from '@eggjs/koa';
import { EggRouter as Router, type RegisterOptions, type ResourcesController } from '@eggjs/router';
import { EggConsoleLogger, type Logger } from 'egg-logger';
import type { ReadyFunctionArg } from 'get-ready';
import { BaseContextClass } from './base_context_class.ts';
import { Lifecycle } from './lifecycle.ts';
import { EggLoader } from './loader/egg_loader.ts';
import { Singleton, type SingletonCreateMethod, type SingletonOptions } from './singleton.ts';
import type { EggAppConfig } from './types.ts';
import utils, { type Fun } from './utils/index.ts';
import { Timing } from './utils/timing.ts';
const debug = debuglog('egg/core/egg');
export const EGG_LOADER: symbol = Symbol.for('egg#loader');
export interface EggCoreOptions {
baseDir: string;
type: 'application' | 'agent';
plugins?: any;
serverScope?: string;
env?: string;
/** Skip lifecycle hooks, only trigger loadMetadata for manifest generation */
metadataOnly?: boolean;
/**
* When true, lifecycle stops after the `configWillLoad` phase.
* `configDidLoad`, `didLoad`, `willReady`, `didReady`, and `serverDidReady`
* are skipped. Used for V8 startup snapshot construction — SDKs typically
* execute during `configDidLoad`, opening connections and starting timers
* which are not serializable. Analogous to `metadataOnly` mode.
*/
snapshot?: boolean;
}
export type EggCoreInitOptions = Partial<EggCoreOptions>;
// export @eggjs/koa classes
export { KoaRequest, KoaResponse, KoaContext, KoaApplication, Router };
// export @eggjs/koa types
export type { Next, KoaMiddlewareFunc };
// export @eggjs/core classes
export class Request extends KoaRequest {
declare ctx: Context;
declare app: EggCore;
declare response: Response;
}
export class Response extends KoaResponse {
declare app: EggCore;
declare request: Request;
}
export class Context extends KoaContext {
declare app: EggCore;
declare request: Request;
declare response: Response;
declare service: Record<string, any>;
// #region router
/**
* Returns map of URL parameters for given `path` and `paramNames`.
* @example
* ##### ctx.params.id {string}
*
* `GET /api/users/1` => `'1'`
*
* ##### ctx.params.per_page {string}
*
* The number of every page, `GET /api/users?per_page=20` => `20`
*/
params?: Record<string, string>;
/**
* Returns array of router regexp url path captures.
*/
captures?: string[];
/**
* Returns the name of the matched router.
*/
routerName?: string;
/**
* Returns the path of the matched router.
*/
routerPath?: string | RegExp;
// #endregion
}
// export @eggjs/core types
export type MiddlewareFunc<T extends KoaContext = Context> = KoaMiddlewareFunc<T>;
export class EggCore extends KoaApplication {
options: EggCoreOptions;
timing: Timing;
console: EggConsoleLogger;
BaseContextClass: typeof BaseContextClass;
Controller: typeof BaseContextClass;
Service: typeof BaseContextClass;
Helper?: typeof BaseContextClass;
lifecycle: Lifecycle;
loader: EggLoader;
#closePromise?: Promise<void>;
#router?: Router;
/** auto inject on loadService() */
readonly serviceClasses: Record<string, any> = {};
/** auto inject on loadController() */
readonly controller: Record<string, any> = {};
/** auto inject on loadMiddleware() */
readonly middlewares: Record<string, (opt: unknown, app: EggCore) => MiddlewareFunc> = {};
/**
* @class
* @param {Object} options - options
* @param {String} [options.baseDir] - the directory of application
* @param {String} [options.type] - whether it's running in app worker or agent worker
* @param {Object} [options.plugins] - custom plugins
* @since 1.0.0
*/
constructor(options: EggCoreInitOptions = {}) {
options.baseDir = options.baseDir ?? process.cwd();
options.type = options.type ?? 'application';
assert(typeof options.baseDir === 'string', 'options.baseDir required, and must be a string');
// assert(fs.existsSync(options.baseDir), `Directory ${options.baseDir} not exists`);
// assert(fs.statSync(options.baseDir).isDirectory(), `Directory ${options.baseDir} is not a directory`);
assert(options.type === 'application' || options.type === 'agent', 'options.type should be application or agent');
super();
this.timing = new Timing();
/**
* @member {Object} EggCore#options
* @private
* @since 1.0.0
*/
this.options = options as EggCoreOptions;
/**
* logging for EggCore, avoid using console directly
* @member {Logger} EggCore#console
* @private
* @since 1.0.0
*/
this.console = new EggConsoleLogger();
/**
* @member {BaseContextClass} EggCore#BaseContextClass
* @since 1.0.0
*/
this.BaseContextClass = BaseContextClass;
/**
* Base controller to be extended by controller in `app.controller`
* @class Controller
* @augments BaseContextClass
* @example
* class UserController extends app.Controller {}
*/
const Controller = this.BaseContextClass;
/**
* Retrieve base controller
* @member {Controller} EggCore#Controller
* @since 1.0.0
*/
this.Controller = Controller;
/**
* Base service to be extended by services in `app.service`
* @class Service
* @augments BaseContextClass
* @example
* class UserService extends app.Service {}
*/
const Service = this.BaseContextClass;
/**
* Retrieve base service
* @member {Service} EggCore#Service
* @since 1.0.0
*/
this.Service = Service;
this.lifecycle = new Lifecycle({
baseDir: options.baseDir,
app: this,
logger: this.console,
snapshot: options.snapshot,
});
this.lifecycle.on('error', (err) => this.emit('error', err));
this.lifecycle.on('ready_timeout', (id) => this.emit('ready_timeout', id));
this.lifecycle.on('ready_stat', (data) => this.emit('ready_stat', data));
/**
* The loader instance, the default class is {@link EggLoader}.
* If you want define
* @member {EggLoader} EggCore#loader
* @since 1.0.0
*/
let Loader: typeof EggLoader;
if (EGG_LOADER in this) {
this.deprecate(
'Symbol.for("egg#loader") is deprecated, please use "override the `customEggLoader()` method" instead',
);
Loader = this[EGG_LOADER] as typeof EggLoader;
} else {
Loader = this.customEggLoader();
}
this.loader = new Loader({
baseDir: options.baseDir,
app: this,
plugins: options.plugins,
logger: this.console,
serverScope: options.serverScope,
env: options.env ?? '',
EggCoreClass: EggCore,
metadataOnly: options.metadataOnly,
});
}
get logger(): Logger {
return this.console;
}
get coreLogger(): Logger {
return this.console;
}
/**
* create a singleton instance
* @param {String} name - unique name for singleton
* @param {Function|AsyncFunction} create - method will be invoked when singleton instance create
*/
addSingleton(name: string, create: SingletonCreateMethod): void {
const options: SingletonOptions = {
name,
create,
app: this,
};
const singleton = new Singleton(options);
const initPromise = singleton.init();
if (initPromise) {
this.lifecycle.registerBeforeStart(async () => {
await initPromise;
}, `${name}-singleton-init`);
}
}
/**
* override koa's app.use, support generator function
* @since 1.0.0
*/
use<T extends KoaContext = Context>(fn: MiddlewareFunc<T>): this {
assert(typeof fn === 'function', 'app.use() requires a function');
debug('[use] add middleware: %o', fn._name || fn.name || '-');
this.middleware.push(fn as unknown as KoaMiddlewareFunc);
return this;
}
/**
* Whether `application` or `agent`
* @member {String}
* @since 1.0.0
*/
get type(): 'application' | 'agent' {
return this.options.type;
}
/**
* The current directory of application
* @member {String}
* @see {@link AppInfo#baseDir}
* @since 1.0.0
*/
get baseDir(): string {
return this.options.baseDir;
}
/**
* Alias to {@link https://npmjs.com/package/depd}
* @member {Function}
* @since 1.0.0
*/
get deprecate(): (message: string) => void {
return utils.deprecated;
}
/**
* The name of application
* @member {String}
* @see {@link AppInfo#name}
* @since 1.0.0
*/
get name(): string {
return this.loader ? this.loader.pkg.name : '';
}
/**
* Retrieve enabled plugins
* @member {Object}
* @since 1.0.0
*/
get plugins(): Record<string, any> {
return this.loader ? this.loader.plugins : {};
}
/**
* The configuration of application
* @member {Config}
* @since 1.0.0
*/
get config(): EggAppConfig {
return this.loader ? this.loader.config : ({} as EggAppConfig);
}
/**
* Execute scope after loaded and before app start.
*
* Notice:
* This method is now NOT recommended and regarded as a deprecated one,
* For plugin development, we should use `didLoad` instead.
* For application development, we should use `willReady` instead.
*
* @see https://eggjs.org/en/advanced/loader.html#beforestart
*
* @param {Function} scope function will execute before app start
* @param {string} [name] scope name, default is empty string
*/
beforeStart(scope: Fun, name?: string): void {
this.deprecate(
'`beforeStart` was deprecated, please use "Life Cycles" instead, see https://www.eggjs.org/advanced/loader#life-cycles',
);
this.lifecycle.registerBeforeStart(scope, name ?? '');
}
/**
* register an callback function that will be invoked when application is ready.
* @see https://github.com/node-modules/get-ready
* @since 1.0.0
* @example
* const app = new Application(...);
* app.ready(err => {
* if (err) throw err;
* console.log('done');
* });
*/
ready(): Promise<void>;
ready(flagOrFunction: ReadyFunctionArg): void;
ready(flagOrFunction?: ReadyFunctionArg) {
if (flagOrFunction === undefined) {
return this.lifecycle.ready();
}
return this.lifecycle.ready(flagOrFunction);
}
/**
* If a client starts asynchronously, you can register `readyCallback`,
* then the application will wait for the callback to ready
*
* It will log when the callback is not invoked after 10s
*
* Recommend to use {@link EggCore#beforeStart}
* @since 1.0.0
*
* @param {String} name - readyCallback task name
* @param {object} opts -
* - {Number} [timeout=10000] - emit `ready_timeout` when it doesn't finish but reach the timeout
* - {Boolean} [isWeakDep=false] - whether it's a weak dependency
* @returns {Function} - a callback
* @example
* const done = app.readyCallback('mysql');
* mysql.ready(done);
*/
readyCallback(name: string, opts: object): (...args: unknown[]) => void {
this.deprecate(
'`readyCallback` was deprecated, please use "Life Cycles" instead, see https://www.eggjs.org/advanced/loader#life-cycles',
);
return this.lifecycle.legacyReadyCallback(name, opts);
}
/**
* Register a function that will be called when app close.
*
* Notice:
* This method is now NOT recommended directly used,
* Developers SHOULDN'T use app.beforeClose directly now,
* but in the form of class to implement beforeClose instead.
*
* @see https://eggjs.org/en/advanced/loader.html#beforeclose
*
* @param {Function} fn - the function that can be generator function or async function.
*/
beforeClose(fn: Fun, name?: string): void {
this.deprecate(
'`beforeClose` was deprecated, please use "Life Cycles" instead, see https://www.eggjs.org/advanced/loader#life-cycles',
);
this.lifecycle.registerBeforeClose(fn, name);
}
/**
* Trigger snapshotWillSerialize lifecycle hooks on all boots in reverse order.
* Called by the build script before V8 serializes the heap.
* Cleans up non-serializable resources: file handles, timers, listeners, connections.
*/
async triggerSnapshotWillSerialize(): Promise<void> {
return this.lifecycle.triggerSnapshotWillSerialize();
}
/**
* Trigger snapshotDidDeserialize lifecycle hooks on all boots in forward order.
* Called by the restore entry after V8 deserializes the heap.
* Restores non-serializable resources and resumes the lifecycle from configDidLoad.
*/
async triggerSnapshotDidDeserialize(): Promise<void> {
return this.lifecycle.triggerSnapshotDidDeserialize();
}
/**
* Close all, it will close
* - callbacks registered by beforeClose
* - emit `close` event
* - remove add listeners
*
* If error is thrown when it's closing, the promise will reject.
* It will also reject after following call.
* @returns {Promise} promise
* @since 1.0.0
*/
async close(): Promise<void> {
if (this.#closePromise) return this.#closePromise;
this.#closePromise = this.lifecycle.close();
return this.#closePromise;
}
/**
* get router
* @member {Router} EggCore#router
* @since 1.0.0
*/
get router(): Router {
if (this.#router) {
return this.#router;
}
this.#router = new Router({ sensitive: true }, this);
return this.#router;
}
/**
* Alias to {@link Router#url}
* @param {String} name - Router name
* @param {Object} params - more parameters
* @returns {String} url
*/
url(name: string, params?: Parameters<Router['url']>[1]): string {
return this.router.url(name, params);
}
// delegate all router method to application
// 'head', 'options', 'get', 'put', 'patch', 'post', 'delete'
// 'all', 'resources', 'register', 'redirect'
head(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
head(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
head(...args: any): EggCore {
this.router.head.apply(this.router, args);
return this;
}
// options(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
// options(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
// options(...args: any): EggCore {
// this.router.options.apply(this.router, args);
// return this;
// }
get(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
get(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
get(...args: any): EggCore {
this.router.get.apply(this.router, args);
return this;
}
put(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
put(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
put(...args: any): EggCore {
this.router.put.apply(this.router, args);
return this;
}
patch(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
patch(
name: string,
path: string | RegExp | (string | RegExp)[],
...middlewares: (MiddlewareFunc | string)[]
): EggCore;
patch(...args: any): EggCore {
this.router.patch.apply(this.router, args);
return this;
}
post(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
post(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
post(...args: any): EggCore {
this.router.post.apply(this.router, args);
return this;
}
delete(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
delete(
name: string,
path: string | RegExp | (string | RegExp)[],
...middlewares: (MiddlewareFunc | string)[]
): EggCore;
delete(...args: any): EggCore {
this.router.delete.apply(this.router, args);
return this;
}
del(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
del(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
del(...args: any): EggCore {
this.router.del.apply(this.router, args);
return this;
}
all(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
all(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
all(...args: any): EggCore {
this.router.all.apply(this.router, args);
return this;
}
resources(prefix: string, controller: string | ResourcesController): EggCore;
resources(prefix: string, middleware: MiddlewareFunc, controller: string | ResourcesController): EggCore;
resources(name: string, prefix: string, controller: string | ResourcesController): EggCore;
resources(
name: string,
prefix: string,
middleware: MiddlewareFunc,
controller: string | ResourcesController,
): EggCore;
resources(...args: any): EggCore {
this.router.resources.apply(this.router, args);
return this;
}
redirect(source: string, destination: string, status = 301): this {
this.router.redirect(source, destination, status);
return this;
}
register(
path: string | RegExp | (string | RegExp)[],
methods: string[],
middleware: MiddlewareFunc | MiddlewareFunc[],
opts?: RegisterOptions,
): this {
this.router.register(path, methods, middleware, opts);
return this;
}
/**
* Override this method to customize the loader
*
* ```ts
* // src/ExampleApplication.ts
* import { Application } from 'egg';
*
* class ExampleApplication extends Application {
* protected override customEggLoader() {
* return ExampleLoader;
* }
* }
* ```
*
* @since 4.0.0
* @returns {typeof EggLoader}
*/
protected customEggLoader(): typeof EggLoader {
return EggLoader;
}
/**
* Override this method to customize the egg paths
*
* ```ts
* // src/ExampleApplication.ts
* import { Application } from 'egg';
*
* class ExampleApplication extends Application {
* protected override customEggPaths() {
* return [path.dirname(import.meta.dirname), ...super.customEggPaths()];
* }
* }
* ```
*
* @since 4.0.0
* @returns {string[]}
*/
protected customEggPaths(): string[] {
return [];
}
}