-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
injector.ts
779 lines (735 loc) 路 21.4 KB
/
injector.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
import {
OPTIONAL_DEPS_METADATA,
OPTIONAL_PROPERTY_DEPS_METADATA,
PARAMTYPES_METADATA,
PROPERTY_DEPS_METADATA,
SELF_DECLARED_DEPS_METADATA,
} from '@nestjs/common/constants';
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import { Injectable } from '@nestjs/common/interfaces/injectable.interface';
import { Type } from '@nestjs/common/interfaces/type.interface';
import {
isFunction,
isNil,
isObject,
isString,
isUndefined,
} from '@nestjs/common/utils/shared.utils';
import { RuntimeException } from '../errors/exceptions/runtime.exception';
import { UndefinedDependencyException } from '../errors/exceptions/undefined-dependency.exception';
import { UnknownDependenciesException } from '../errors/exceptions/unknown-dependencies.exception';
import { STATIC_CONTEXT } from './constants';
import { INQUIRER } from './inquirer';
import {
ContextId,
InstancePerContext,
InstanceWrapper,
PropertyMetadata,
} from './instance-wrapper';
import { Module } from './module';
/**
* The type of an injectable dependency
*/
export type InjectorDependency = Type<any> | Function | string | symbol;
/**
* The property-based dependency
*/
export interface PropertyDependency {
key: string;
name: InjectorDependency;
isOptional?: boolean;
instance?: any;
}
/**
* Context of a dependency which gets injected by
* the injector
*/
export interface InjectorDependencyContext {
/**
* The name of the property key (property-based injection)
*/
key?: string | symbol;
/**
* The name of the function or injection token
*/
name?: string | symbol;
/**
* The index of the dependency which gets injected
* from the dependencies array
*/
index?: number;
/**
* The dependency array which gets injected
*/
dependencies?: InjectorDependency[];
}
export class Injector {
public async loadMiddleware(
wrapper: InstanceWrapper,
collection: Map<string, InstanceWrapper>,
module: Module,
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
) {
const { metatype } = wrapper;
const targetWrapper = collection.get(metatype.name);
if (!isUndefined(targetWrapper.instance)) {
return;
}
const loadInstance = (instances: any[]) => {
targetWrapper.instance = targetWrapper.isDependencyTreeStatic()
? new (metatype as Type<any>)(...instances)
: Object.create(metatype.prototype);
};
await this.resolveConstructorParams(
wrapper,
module,
null,
loadInstance,
contextId,
inquirer,
);
}
public async loadController(
wrapper: InstanceWrapper<Controller>,
module: Module,
contextId = STATIC_CONTEXT,
) {
const controllers = module.controllers;
await this.loadInstance<Controller>(
wrapper,
controllers,
module,
contextId,
wrapper,
);
await this.loadEnhancersPerContext(wrapper, contextId, wrapper);
}
public async loadInjectable(
wrapper: InstanceWrapper<Controller>,
module: Module,
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
) {
const injectables = module.injectables;
await this.loadInstance<Controller>(
wrapper,
injectables,
module,
contextId,
inquirer,
);
}
public async loadProvider(
wrapper: InstanceWrapper<Injectable>,
module: Module,
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
) {
const providers = module.providers;
await this.loadInstance<Injectable>(
wrapper,
providers,
module,
contextId,
inquirer,
);
await this.loadEnhancersPerContext(wrapper, contextId, wrapper);
}
public loadPrototype<T>(
{ name }: InstanceWrapper<T>,
collection: Map<string, InstanceWrapper<T>>,
contextId = STATIC_CONTEXT,
) {
if (!collection) {
return;
}
const target = collection.get(name);
const instance = target.createPrototype(contextId);
if (instance) {
const wrapper = new InstanceWrapper({
...target,
instance,
});
collection.set(name, wrapper);
}
}
public applyDoneHook<T>(wrapper: InstancePerContext<T>): () => void {
let done: () => void;
wrapper.donePromise = new Promise<void>((resolve, reject) => {
done = resolve;
});
wrapper.isPending = true;
return done;
}
public async loadInstance<T>(
wrapper: InstanceWrapper<T>,
collection: Map<string, InstanceWrapper>,
module: Module,
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
) {
const inquirerId = this.getInquirerId(inquirer);
const instanceHost = wrapper.getInstanceByContextId(contextId, inquirerId);
if (instanceHost.isPending) {
return instanceHost.donePromise;
}
const done = this.applyDoneHook(instanceHost);
const { name, inject } = wrapper;
const targetWrapper = collection.get(name);
if (isUndefined(targetWrapper)) {
throw new RuntimeException();
}
if (instanceHost.isResolved) {
return done();
}
const callback = async (instances: unknown[]) => {
const properties = await this.resolveProperties(
wrapper,
module,
inject,
contextId,
wrapper,
inquirer,
);
const instance = await this.instantiateClass(
instances,
wrapper,
targetWrapper,
contextId,
inquirer,
);
this.applyProperties(instance, properties);
done();
};
await this.resolveConstructorParams<T>(
wrapper,
module,
inject,
callback,
contextId,
wrapper,
inquirer,
);
}
public async resolveConstructorParams<T>(
wrapper: InstanceWrapper<T>,
module: Module,
inject: InjectorDependency[],
callback: (args: unknown[]) => void,
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
parentInquirer?: InstanceWrapper,
) {
const inquirerId = this.getInquirerId(inquirer);
const metadata = wrapper.getCtorMetadata();
if (metadata && contextId !== STATIC_CONTEXT) {
const deps = await this.loadCtorMetadata(
metadata,
contextId,
inquirer,
parentInquirer,
);
return callback(deps);
}
const dependencies = isNil(inject)
? this.reflectConstructorParams(wrapper.metatype as Type<any>)
: inject;
const optionalDependenciesIds = isNil(inject)
? this.reflectOptionalParams(wrapper.metatype as Type<any>)
: [];
let isResolved = true;
const resolveParam = async (param: unknown, index: number) => {
try {
if (this.isInquirer(param, parentInquirer)) {
return parentInquirer && parentInquirer.instance;
}
const paramWrapper = await this.resolveSingleParam<T>(
wrapper,
param,
{ index, dependencies },
module,
contextId,
inquirer,
index,
);
const instanceHost = paramWrapper.getInstanceByContextId(
contextId,
inquirerId,
);
if (!instanceHost.isResolved && !paramWrapper.forwardRef) {
isResolved = false;
}
return instanceHost && instanceHost.instance;
} catch (err) {
const isOptional = optionalDependenciesIds.includes(index);
if (!isOptional) {
throw err;
}
return undefined;
}
};
const instances = await Promise.all(dependencies.map(resolveParam));
isResolved && (await callback(instances));
}
public reflectConstructorParams<T>(type: Type<T>): any[] {
const paramtypes = Reflect.getMetadata(PARAMTYPES_METADATA, type) || [];
const selfParams = this.reflectSelfParams<T>(type);
selfParams.forEach(({ index, param }) => (paramtypes[index] = param));
return paramtypes;
}
public reflectOptionalParams<T>(type: Type<T>): any[] {
return Reflect.getMetadata(OPTIONAL_DEPS_METADATA, type) || [];
}
public reflectSelfParams<T>(type: Type<T>): any[] {
return Reflect.getMetadata(SELF_DECLARED_DEPS_METADATA, type) || [];
}
public async resolveSingleParam<T>(
wrapper: InstanceWrapper<T>,
param: Type<any> | string | symbol | any,
dependencyContext: InjectorDependencyContext,
module: Module,
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
keyOrIndex?: string | number,
) {
if (isUndefined(param)) {
throw new UndefinedDependencyException(
wrapper.name,
dependencyContext,
module,
);
}
const token = this.resolveParamToken(wrapper, param);
return this.resolveComponentInstance<T>(
module,
isFunction(token) ? (token as Type<any>).name : token,
dependencyContext,
wrapper,
contextId,
inquirer,
keyOrIndex,
);
}
public resolveParamToken<T>(
wrapper: InstanceWrapper<T>,
param: Type<any> | string | symbol | any,
) {
if (!param.forwardRef) {
return param;
}
wrapper.forwardRef = true;
return param.forwardRef();
}
public async resolveComponentInstance<T>(
module: Module,
name: any,
dependencyContext: InjectorDependencyContext,
wrapper: InstanceWrapper<T>,
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
keyOrIndex?: string | number,
): Promise<InstanceWrapper> {
const providers = module.providers;
const instanceWrapper = await this.lookupComponent(
providers,
module,
{ ...dependencyContext, name },
wrapper,
contextId,
inquirer,
keyOrIndex,
);
return this.resolveComponentHost(
module,
instanceWrapper,
contextId,
inquirer,
);
}
public async resolveComponentHost<T>(
module: Module,
instanceWrapper: InstanceWrapper<T>,
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
): Promise<InstanceWrapper> {
const inquirerId = this.getInquirerId(inquirer);
const instanceHost = instanceWrapper.getInstanceByContextId(
contextId,
inquirerId,
);
if (!instanceHost.isResolved && !instanceWrapper.forwardRef) {
await this.loadProvider(instanceWrapper, module, contextId, inquirer);
} else if (
!instanceHost.isResolved &&
instanceWrapper.forwardRef &&
(contextId !== STATIC_CONTEXT || !!inquirerId)
) {
/**
* When circular dependency has been detected between
* either request/transient providers, we have to asynchronously
* resolve instance host for a specific contextId or inquirer, to ensure
* that eventual lazily created instance will be merged with the prototype
* instantiated beforehand.
*/
instanceHost.donePromise &&
instanceHost.donePromise.then(() =>
this.loadProvider(instanceWrapper, module, contextId, inquirer),
);
}
if (instanceWrapper.async) {
const host = instanceWrapper.getInstanceByContextId(
contextId,
inquirerId,
);
host.instance = await host.instance;
instanceWrapper.setInstanceByContextId(contextId, host, inquirerId);
}
return instanceWrapper;
}
public async lookupComponent<T = any>(
providers: Map<string | symbol, InstanceWrapper>,
module: Module,
dependencyContext: InjectorDependencyContext,
wrapper: InstanceWrapper<T>,
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
keyOrIndex?: string | number,
): Promise<InstanceWrapper<T>> {
const { name } = dependencyContext;
if (wrapper && wrapper.name === name) {
throw new UnknownDependenciesException(
wrapper.name,
dependencyContext,
module,
);
}
if (providers.has(name)) {
const instanceWrapper = providers.get(name);
this.addDependencyMetadata(keyOrIndex, wrapper, instanceWrapper);
return instanceWrapper;
}
return this.lookupComponentInParentModules(
dependencyContext,
module,
wrapper,
contextId,
inquirer,
keyOrIndex,
);
}
public async lookupComponentInParentModules<T = any>(
dependencyContext: InjectorDependencyContext,
module: Module,
wrapper: InstanceWrapper<T>,
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
keyOrIndex?: string | number,
) {
const instanceWrapper = await this.lookupComponentInImports(
module,
dependencyContext.name,
wrapper,
[],
contextId,
inquirer,
keyOrIndex,
);
if (isNil(instanceWrapper)) {
throw new UnknownDependenciesException(
wrapper.name,
dependencyContext,
module,
);
}
return instanceWrapper;
}
public async lookupComponentInImports(
module: Module,
name: any,
wrapper: InstanceWrapper,
moduleRegistry: any[] = [],
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
keyOrIndex?: string | number,
isTraversing?: boolean,
): Promise<any> {
let instanceWrapperRef: InstanceWrapper = null;
const imports = module.imports || new Set<Module>();
const identity = (item: any) => item;
let children = [...imports.values()].filter(identity);
if (isTraversing) {
const contextModuleExports = module.exports;
children = children.filter(child =>
contextModuleExports.has(child.metatype && child.metatype.name),
);
}
for (const relatedModule of children) {
if (moduleRegistry.includes(relatedModule.id)) {
continue;
}
moduleRegistry.push(relatedModule.id);
const { providers, exports } = relatedModule;
if (!exports.has(name) || !providers.has(name)) {
const instanceRef = await this.lookupComponentInImports(
relatedModule,
name,
wrapper,
moduleRegistry,
contextId,
inquirer,
keyOrIndex,
true,
);
if (instanceRef) {
this.addDependencyMetadata(keyOrIndex, wrapper, instanceRef);
return instanceRef;
}
continue;
}
instanceWrapperRef = providers.get(name);
this.addDependencyMetadata(keyOrIndex, wrapper, instanceWrapperRef);
const inquirerId = this.getInquirerId(inquirer);
const instanceHost = instanceWrapperRef.getInstanceByContextId(
contextId,
inquirerId,
);
if (!instanceHost.isResolved && !instanceWrapperRef.forwardRef) {
await this.loadProvider(
instanceWrapperRef,
relatedModule,
contextId,
wrapper,
);
break;
}
}
return instanceWrapperRef;
}
public async resolveProperties<T>(
wrapper: InstanceWrapper<T>,
module: Module,
inject?: InjectorDependency[],
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
parentInquirer?: InstanceWrapper,
): Promise<PropertyDependency[]> {
if (!isNil(inject)) {
return [];
}
const metadata = wrapper.getPropertiesMetadata();
if (metadata && contextId !== STATIC_CONTEXT) {
return this.loadPropertiesMetadata(metadata, contextId, inquirer);
}
const properties = this.reflectProperties(wrapper.metatype as Type<any>);
const instances = await Promise.all(
properties.map(async (item: PropertyDependency) => {
try {
const dependencyContext = {
key: item.key,
name: item.name as string,
};
if (this.isInquirer(item.name, parentInquirer)) {
return parentInquirer && parentInquirer.instance;
}
const paramWrapper = await this.resolveSingleParam<T>(
wrapper,
item.name,
dependencyContext,
module,
contextId,
inquirer,
item.key,
);
if (!paramWrapper) {
return undefined;
}
const inquirerId = this.getInquirerId(inquirer);
const instanceHost = paramWrapper.getInstanceByContextId(
contextId,
inquirerId,
);
return instanceHost.instance;
} catch (err) {
if (!item.isOptional) {
throw err;
}
return undefined;
}
}),
);
return properties.map((item: PropertyDependency, index: number) => ({
...item,
instance: instances[index],
}));
}
public reflectProperties<T>(type: Type<T>): PropertyDependency[] {
const properties = Reflect.getMetadata(PROPERTY_DEPS_METADATA, type) || [];
const optionalKeys: string[] =
Reflect.getMetadata(OPTIONAL_PROPERTY_DEPS_METADATA, type) || [];
return properties.map((item: any) => ({
...item,
name: item.type,
isOptional: optionalKeys.includes(item.key),
}));
}
public applyProperties<T = any>(
instance: T,
properties: PropertyDependency[],
): void {
if (!isObject(instance)) {
return undefined;
}
properties
.filter(item => !isNil(item.instance))
.forEach(item => (instance[item.key] = item.instance));
}
public async instantiateClass<T = any>(
instances: any[],
wrapper: InstanceWrapper,
targetMetatype: InstanceWrapper,
contextId = STATIC_CONTEXT,
inquirer?: InstanceWrapper,
): Promise<T> {
const { metatype, inject } = wrapper;
const inquirerId = this.getInquirerId(inquirer);
const instanceHost = targetMetatype.getInstanceByContextId(
contextId,
inquirerId,
);
const isStatic = wrapper.isStatic(contextId, inquirer);
const isInRequestScope = wrapper.isInRequestScope(contextId, inquirer);
const isLazyTransient = wrapper.isLazyTransient(contextId, inquirer);
const isExplicitlyRequested = wrapper.isExplicitlyRequested(
contextId,
inquirer,
);
const isInContext =
isStatic || isInRequestScope || isLazyTransient || isExplicitlyRequested;
if (isNil(inject) && isInContext) {
instanceHost.instance = wrapper.forwardRef
? Object.assign(
instanceHost.instance,
new (metatype as Type<any>)(...instances),
)
: new (metatype as Type<any>)(...instances);
} else if (isInContext) {
const factoryReturnValue = ((targetMetatype.metatype as any) as Function)(
...instances,
);
instanceHost.instance = await factoryReturnValue;
}
instanceHost.isResolved = true;
return instanceHost.instance;
}
public async loadPerContext<T = any>(
instance: T,
module: Module,
collection: Map<string, InstanceWrapper>,
ctx: ContextId,
): Promise<T> {
const wrapper = collection.get(
instance.constructor && instance.constructor.name,
);
await this.loadInstance(wrapper, collection, module, ctx, wrapper);
await this.loadEnhancersPerContext(wrapper, ctx, wrapper);
const host = wrapper.getInstanceByContextId(ctx, wrapper.id);
return host && (host.instance as T);
}
public async loadEnhancersPerContext(
wrapper: InstanceWrapper,
ctx: ContextId,
inquirer?: InstanceWrapper,
) {
const enhancers = wrapper.getEnhancersMetadata() || [];
const loadEnhancer = (item: InstanceWrapper) => {
const hostModule = item.host;
return this.loadInstance(
item,
hostModule.injectables,
hostModule,
ctx,
inquirer,
);
};
await Promise.all(enhancers.map(loadEnhancer));
}
public async loadCtorMetadata(
metadata: InstanceWrapper<any>[],
contextId: ContextId,
inquirer?: InstanceWrapper,
parentInquirer?: InstanceWrapper,
): Promise<any[]> {
const hosts = await Promise.all(
metadata.map(async item =>
this.resolveScopedComponentHost(
item,
contextId,
inquirer,
parentInquirer,
),
),
);
const inquirerId = this.getInquirerId(inquirer);
return hosts.map(
item => item.getInstanceByContextId(contextId, inquirerId).instance,
);
}
public async loadPropertiesMetadata(
metadata: PropertyMetadata[],
contextId: ContextId,
inquirer?: InstanceWrapper,
): Promise<PropertyDependency[]> {
const dependenciesHosts = await Promise.all(
metadata.map(async ({ wrapper: item, key }) => ({
key,
host: await this.resolveComponentHost(
item.host,
item,
contextId,
inquirer,
),
})),
);
const inquirerId = this.getInquirerId(inquirer);
return dependenciesHosts.map(({ key, host }) => ({
key,
name: key,
instance: host.getInstanceByContextId(contextId, inquirerId).instance,
}));
}
private getInquirerId(inquirer: InstanceWrapper | undefined): string {
return inquirer && inquirer.id;
}
private resolveScopedComponentHost(
item: InstanceWrapper,
contextId: ContextId,
inquirer?: InstanceWrapper,
parentInquirer?: InstanceWrapper,
) {
return this.isInquirerRequest(item, parentInquirer)
? parentInquirer
: this.resolveComponentHost(item.host, item, contextId, inquirer);
}
private isInquirerRequest(
item: InstanceWrapper,
parentInquirer: InstanceWrapper | undefined,
) {
return item.isTransient && item.name === INQUIRER && parentInquirer;
}
private isInquirer(
param: unknown,
parentInquirer: InstanceWrapper | undefined,
) {
return param === INQUIRER && parentInquirer;
}
private addDependencyMetadata(
keyOrIndex: number | string,
hostWrapper: InstanceWrapper,
instanceWrapper: InstanceWrapper,
) {
isString(keyOrIndex)
? hostWrapper.addPropertiesMetadata(keyOrIndex, instanceWrapper)
: hostWrapper.addCtorMetadata(keyOrIndex, instanceWrapper);
}
}