1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | import {
|
7 | DecoratorFactory,
|
8 | InspectionOptions,
|
9 | MetadataAccessor,
|
10 | MetadataInspector,
|
11 | MetadataMap,
|
12 | ParameterDecoratorFactory,
|
13 | PropertyDecoratorFactory,
|
14 | Reflector,
|
15 | } from '@loopback/metadata';
|
16 | import {Binding, BindingTag} from './binding';
|
17 | import {
|
18 | BindingFilter,
|
19 | BindingSelector,
|
20 | filterByTag,
|
21 | isBindingAddress,
|
22 | isBindingTagFilter,
|
23 | } from './binding-filter';
|
24 | import {BindingAddress, BindingKey} from './binding-key';
|
25 | import {BindingComparator} from './binding-sorter';
|
26 | import {BindingCreationPolicy, Context} from './context';
|
27 | import {ContextView, createViewGetter} from './context-view';
|
28 | import {JSONObject} from './json-types';
|
29 | import {ResolutionOptions, ResolutionSession} from './resolution-session';
|
30 | import {BoundValue, Constructor, ValueOrPromise} from './value-promise';
|
31 |
|
32 | const INJECT_PARAMETERS_KEY = MetadataAccessor.create<
|
33 | Injection,
|
34 | ParameterDecorator
|
35 | >('inject:parameters');
|
36 |
|
37 | const INJECT_PROPERTIES_KEY = MetadataAccessor.create<
|
38 | Injection,
|
39 | PropertyDecorator
|
40 | >('inject:properties');
|
41 |
|
42 |
|
43 | const INJECT_METHODS_KEY = MetadataAccessor.create<Injection, MethodDecorator>(
|
44 | 'inject:methods',
|
45 | );
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 | export interface ResolverFunction {
|
60 | (
|
61 | ctx: Context,
|
62 | injection: Readonly<Injection>,
|
63 | session: ResolutionSession,
|
64 | ): ValueOrPromise<BoundValue>;
|
65 | }
|
66 |
|
67 |
|
68 |
|
69 |
|
70 | export interface InjectionMetadata extends Omit<ResolutionOptions, 'session'> {
|
71 | |
72 |
|
73 |
|
74 |
|
75 | decorator?: string;
|
76 | |
77 |
|
78 |
|
79 | bindingComparator?: BindingComparator;
|
80 | |
81 |
|
82 |
|
83 | [attribute: string]: BoundValue;
|
84 | }
|
85 |
|
86 |
|
87 |
|
88 |
|
89 | export interface Injection<ValueType = BoundValue> {
|
90 | target: Object;
|
91 | member?: string;
|
92 | methodDescriptorOrParameterIndex?:
|
93 | | TypedPropertyDescriptor<ValueType>
|
94 | | number;
|
95 |
|
96 | bindingSelector: BindingSelector<ValueType>;
|
97 | metadata: InjectionMetadata;
|
98 | resolve?: ResolverFunction;
|
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 | export function inject(
|
129 | bindingSelector: BindingSelector,
|
130 | metadata?: InjectionMetadata,
|
131 | resolve?: ResolverFunction,
|
132 | ) {
|
133 | if (typeof bindingSelector === 'function' && !resolve) {
|
134 | resolve = resolveValuesByFilter;
|
135 | }
|
136 | const injectionMetadata = Object.assign({decorator: '@inject'}, metadata);
|
137 | if (injectionMetadata.bindingComparator && !resolve) {
|
138 | throw new Error('Binding comparator is only allowed with a binding filter');
|
139 | }
|
140 | if (!bindingSelector && typeof resolve !== 'function') {
|
141 | throw new Error(
|
142 | 'A non-empty binding selector or resolve function is required for @inject',
|
143 | );
|
144 | }
|
145 | return function markParameterOrPropertyAsInjected(
|
146 | target: Object,
|
147 | member: string | undefined,
|
148 | methodDescriptorOrParameterIndex?:
|
149 | | TypedPropertyDescriptor<BoundValue>
|
150 | | number,
|
151 | ) {
|
152 | if (typeof methodDescriptorOrParameterIndex === 'number') {
|
153 |
|
154 |
|
155 | const paramDecorator: ParameterDecorator =
|
156 | ParameterDecoratorFactory.createDecorator<Injection>(
|
157 | INJECT_PARAMETERS_KEY,
|
158 | {
|
159 | target,
|
160 | member,
|
161 | methodDescriptorOrParameterIndex,
|
162 | bindingSelector,
|
163 | metadata: injectionMetadata,
|
164 | resolve,
|
165 | },
|
166 |
|
167 |
|
168 | {cloneInputSpec: false, decoratorName: injectionMetadata.decorator},
|
169 | );
|
170 | paramDecorator(target, member!, methodDescriptorOrParameterIndex);
|
171 | } else if (member) {
|
172 |
|
173 | if (target instanceof Function) {
|
174 | throw new Error(
|
175 | '@inject is not supported for a static property: ' +
|
176 | DecoratorFactory.getTargetName(target, member),
|
177 | );
|
178 | }
|
179 | if (methodDescriptorOrParameterIndex) {
|
180 |
|
181 | throw new Error(
|
182 | '@inject cannot be used on a method: ' +
|
183 | DecoratorFactory.getTargetName(
|
184 | target,
|
185 | member,
|
186 | methodDescriptorOrParameterIndex,
|
187 | ),
|
188 | );
|
189 | }
|
190 | const propDecorator: PropertyDecorator =
|
191 | PropertyDecoratorFactory.createDecorator<Injection>(
|
192 | INJECT_PROPERTIES_KEY,
|
193 | {
|
194 | target,
|
195 | member,
|
196 | methodDescriptorOrParameterIndex,
|
197 | bindingSelector,
|
198 | metadata: injectionMetadata,
|
199 | resolve,
|
200 | },
|
201 |
|
202 |
|
203 | {cloneInputSpec: false, decoratorName: injectionMetadata.decorator},
|
204 | );
|
205 | propDecorator(target, member!);
|
206 | } else {
|
207 |
|
208 |
|
209 | throw new Error(
|
210 | '@inject can only be used on a property or a method parameter',
|
211 | );
|
212 | }
|
213 | };
|
214 | }
|
215 |
|
216 |
|
217 |
|
218 |
|
219 |
|
220 |
|
221 | export type Getter<T> = () => Promise<T>;
|
222 |
|
223 | export namespace Getter {
|
224 | |
225 |
|
226 |
|
227 |
|
228 | export function fromValue<T>(value: T): Getter<T> {
|
229 | return () => Promise.resolve(value);
|
230 | }
|
231 | }
|
232 |
|
233 |
|
234 |
|
235 |
|
236 |
|
237 |
|
238 |
|
239 |
|
240 |
|
241 |
|
242 |
|
243 |
|
244 | export type Setter<T> = (value: T) => void;
|
245 |
|
246 |
|
247 |
|
248 |
|
249 | export interface InjectBindingMetadata extends InjectionMetadata {
|
250 | |
251 |
|
252 |
|
253 | bindingCreation?: BindingCreationPolicy;
|
254 | }
|
255 |
|
256 | export namespace inject {
|
257 | |
258 |
|
259 |
|
260 |
|
261 |
|
262 |
|
263 |
|
264 |
|
265 |
|
266 |
|
267 |
|
268 |
|
269 |
|
270 |
|
271 | export const getter = function injectGetter(
|
272 | bindingSelector: BindingSelector<unknown>,
|
273 | metadata?: InjectionMetadata,
|
274 | ) {
|
275 | metadata = Object.assign({decorator: '@inject.getter'}, metadata);
|
276 | return inject(
|
277 | bindingSelector,
|
278 | metadata,
|
279 | isBindingAddress(bindingSelector)
|
280 | ? resolveAsGetter
|
281 | : resolveAsGetterByFilter,
|
282 | );
|
283 | };
|
284 |
|
285 | |
286 |
|
287 |
|
288 |
|
289 |
|
290 |
|
291 |
|
292 |
|
293 |
|
294 |
|
295 |
|
296 |
|
297 |
|
298 | export const setter = function injectSetter(
|
299 | bindingKey: BindingAddress,
|
300 | metadata?: InjectBindingMetadata,
|
301 | ) {
|
302 | metadata = Object.assign({decorator: '@inject.setter'}, metadata);
|
303 | return inject(bindingKey, metadata, resolveAsSetter);
|
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 | export const binding = function injectBinding(
|
332 | bindingKey?: string | BindingKey<unknown>,
|
333 | metadata?: InjectBindingMetadata,
|
334 | ) {
|
335 | metadata = Object.assign({decorator: '@inject.binding'}, metadata);
|
336 | return inject(bindingKey ?? '', metadata, resolveAsBinding);
|
337 | };
|
338 |
|
339 | |
340 |
|
341 |
|
342 |
|
343 |
|
344 |
|
345 |
|
346 |
|
347 |
|
348 |
|
349 |
|
350 |
|
351 |
|
352 |
|
353 | export const tag = function injectByTag(
|
354 | bindingTag: BindingTag | RegExp,
|
355 | metadata?: InjectionMetadata,
|
356 | ) {
|
357 | metadata = Object.assign(
|
358 | {decorator: '@inject.tag', tag: bindingTag},
|
359 | metadata,
|
360 | );
|
361 | return inject(filterByTag(bindingTag), metadata);
|
362 | };
|
363 |
|
364 | |
365 |
|
366 |
|
367 |
|
368 |
|
369 |
|
370 |
|
371 |
|
372 |
|
373 |
|
374 |
|
375 |
|
376 |
|
377 | export const view = function injectContextView(
|
378 | bindingFilter: BindingFilter,
|
379 | metadata?: InjectionMetadata,
|
380 | ) {
|
381 | metadata = Object.assign({decorator: '@inject.view'}, metadata);
|
382 | return inject(bindingFilter, metadata, resolveAsContextView);
|
383 | };
|
384 |
|
385 | |
386 |
|
387 |
|
388 |
|
389 |
|
390 |
|
391 |
|
392 |
|
393 |
|
394 |
|
395 | export const context = function injectContext() {
|
396 | return inject('', {decorator: '@inject.context'}, (ctx: Context) => ctx);
|
397 | };
|
398 | }
|
399 |
|
400 |
|
401 |
|
402 |
|
403 |
|
404 |
|
405 |
|
406 |
|
407 |
|
408 | export function assertTargetType(
|
409 | injection: Readonly<Injection>,
|
410 | expectedType: Function,
|
411 | expectedTypeName?: string,
|
412 | ) {
|
413 | const targetName = ResolutionSession.describeInjection(injection).targetName;
|
414 | const targetType = inspectTargetType(injection);
|
415 | if (targetType && targetType !== expectedType) {
|
416 | expectedTypeName = expectedTypeName ?? expectedType.name;
|
417 | throw new Error(
|
418 | `The type of ${targetName} (${targetType.name}) is not ${expectedTypeName}`,
|
419 | );
|
420 | }
|
421 | return targetName;
|
422 | }
|
423 |
|
424 |
|
425 |
|
426 |
|
427 |
|
428 |
|
429 |
|
430 | function resolveAsGetter(
|
431 | ctx: Context,
|
432 | injection: Readonly<Injection>,
|
433 | session: ResolutionSession,
|
434 | ) {
|
435 | assertTargetType(injection, Function, 'Getter function');
|
436 | const bindingSelector = injection.bindingSelector as BindingAddress;
|
437 | const options: ResolutionOptions = {
|
438 |
|
439 |
|
440 |
|
441 | session: undefined,
|
442 | ...injection.metadata,
|
443 | };
|
444 | return function getter() {
|
445 | return ctx.get(bindingSelector, options);
|
446 | };
|
447 | }
|
448 |
|
449 |
|
450 |
|
451 |
|
452 |
|
453 |
|
454 | function resolveAsSetter(ctx: Context, injection: Injection) {
|
455 | const targetName = assertTargetType(injection, Function, 'Setter function');
|
456 | const bindingSelector = injection.bindingSelector;
|
457 | if (!isBindingAddress(bindingSelector)) {
|
458 | throw new Error(
|
459 | `@inject.setter (${targetName}) does not allow BindingFilter.`,
|
460 | );
|
461 | }
|
462 | if (bindingSelector === '') {
|
463 | throw new Error('Binding key is not set for @inject.setter');
|
464 | }
|
465 |
|
466 | return function setter(value: unknown) {
|
467 | const binding = findOrCreateBindingForInjection(ctx, injection);
|
468 | binding!.to(value);
|
469 | };
|
470 | }
|
471 |
|
472 | function resolveAsBinding(
|
473 | ctx: Context,
|
474 | injection: Injection,
|
475 | session: ResolutionSession,
|
476 | ) {
|
477 | const targetName = assertTargetType(injection, Binding);
|
478 | const bindingSelector = injection.bindingSelector;
|
479 | if (!isBindingAddress(bindingSelector)) {
|
480 | throw new Error(
|
481 | `@inject.binding (${targetName}) does not allow BindingFilter.`,
|
482 | );
|
483 | }
|
484 | return findOrCreateBindingForInjection(ctx, injection, session);
|
485 | }
|
486 |
|
487 | function findOrCreateBindingForInjection(
|
488 | ctx: Context,
|
489 | injection: Injection<unknown>,
|
490 | session?: ResolutionSession,
|
491 | ) {
|
492 | if (injection.bindingSelector === '') return session?.currentBinding;
|
493 | const bindingCreation =
|
494 | injection.metadata &&
|
495 | (injection.metadata as InjectBindingMetadata).bindingCreation;
|
496 | const binding: Binding<unknown> = ctx.findOrCreateBinding(
|
497 | injection.bindingSelector as BindingAddress,
|
498 | bindingCreation,
|
499 | );
|
500 | return binding;
|
501 | }
|
502 |
|
503 |
|
504 |
|
505 |
|
506 |
|
507 |
|
508 |
|
509 | function shouldSkipBaseConstructorInjection(targetClass: Object) {
|
510 |
|
511 | const classDef = targetClass.toString();
|
512 | return (
|
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 | !classDef.match(
|
540 | /\s+constructor\s*\(\s*\)\s*\{\s*super\(\.\.\.arguments\)/,
|
541 | ) &&
|
542 | |
543 |
|
544 |
|
545 |
|
546 |
|
547 |
|
548 |
|
549 |
|
550 |
|
551 |
|
552 |
|
553 |
|
554 |
|
555 |
|
556 |
|
557 |
|
558 |
|
559 |
|
560 |
|
561 | classDef.match(/\s+constructor\s*\([^\)]*\)\s+\{/m)
|
562 | );
|
563 | }
|
564 |
|
565 |
|
566 |
|
567 |
|
568 |
|
569 |
|
570 |
|
571 | export function describeInjectedArguments(
|
572 | target: Object,
|
573 | method?: string,
|
574 | ): Readonly<Injection>[] {
|
575 | method = method ?? '';
|
576 |
|
577 |
|
578 | const cache =
|
579 | MetadataInspector.getAllMethodMetadata<Readonly<Injection>[]>(
|
580 | INJECT_METHODS_KEY,
|
581 | target,
|
582 | {
|
583 | ownMetadataOnly: true,
|
584 | },
|
585 | ) ?? {};
|
586 | let meta: Readonly<Injection>[] = cache[method];
|
587 | if (meta) return meta;
|
588 |
|
589 |
|
590 | const options: InspectionOptions = {};
|
591 | if (method === '') {
|
592 | if (shouldSkipBaseConstructorInjection(target)) {
|
593 | options.ownMetadataOnly = true;
|
594 | }
|
595 | } else if (Object.prototype.hasOwnProperty.call(target, method)) {
|
596 |
|
597 |
|
598 | options.ownMetadataOnly = true;
|
599 | }
|
600 | meta =
|
601 | MetadataInspector.getAllParameterMetadata<Readonly<Injection>>(
|
602 | INJECT_PARAMETERS_KEY,
|
603 | target,
|
604 | method,
|
605 | options,
|
606 | ) ?? [];
|
607 |
|
608 |
|
609 | cache[method] = meta;
|
610 | MetadataInspector.defineMetadata<MetadataMap<Readonly<Injection>[]>>(
|
611 | INJECT_METHODS_KEY,
|
612 | cache,
|
613 | target,
|
614 | );
|
615 | return meta;
|
616 | }
|
617 |
|
618 |
|
619 |
|
620 |
|
621 |
|
622 |
|
623 | export function inspectTargetType(injection: Readonly<Injection>) {
|
624 | if (typeof injection.methodDescriptorOrParameterIndex === 'number') {
|
625 | const designType = MetadataInspector.getDesignTypeForMethod(
|
626 | injection.target,
|
627 | injection.member!,
|
628 | );
|
629 | return designType?.parameterTypes?.[
|
630 | injection.methodDescriptorOrParameterIndex as number
|
631 | ];
|
632 | }
|
633 | return MetadataInspector.getDesignTypeForProperty(
|
634 | injection.target,
|
635 | injection.member!,
|
636 | );
|
637 | }
|
638 |
|
639 |
|
640 |
|
641 |
|
642 |
|
643 |
|
644 |
|
645 | function resolveValuesByFilter(
|
646 | ctx: Context,
|
647 | injection: Readonly<Injection>,
|
648 | session: ResolutionSession,
|
649 | ) {
|
650 | assertTargetType(injection, Array);
|
651 | const bindingFilter = injection.bindingSelector as BindingFilter;
|
652 | const view = new ContextView(
|
653 | ctx,
|
654 | bindingFilter,
|
655 | injection.metadata.bindingComparator,
|
656 | );
|
657 | return view.resolve(session);
|
658 | }
|
659 |
|
660 |
|
661 |
|
662 |
|
663 |
|
664 |
|
665 |
|
666 |
|
667 |
|
668 | function resolveAsGetterByFilter(
|
669 | ctx: Context,
|
670 | injection: Readonly<Injection>,
|
671 | session: ResolutionSession,
|
672 | ) {
|
673 | assertTargetType(injection, Function, 'Getter function');
|
674 | const bindingFilter = injection.bindingSelector as BindingFilter;
|
675 | return createViewGetter(
|
676 | ctx,
|
677 | bindingFilter,
|
678 | injection.metadata.bindingComparator,
|
679 | session,
|
680 | );
|
681 | }
|
682 |
|
683 |
|
684 |
|
685 |
|
686 |
|
687 |
|
688 |
|
689 | function resolveAsContextView(ctx: Context, injection: Readonly<Injection>) {
|
690 | assertTargetType(injection, ContextView);
|
691 |
|
692 | const bindingFilter = injection.bindingSelector as BindingFilter;
|
693 | const view = new ContextView(
|
694 | ctx,
|
695 | bindingFilter,
|
696 | injection.metadata.bindingComparator,
|
697 | );
|
698 | view.open();
|
699 | return view;
|
700 | }
|
701 |
|
702 |
|
703 |
|
704 |
|
705 |
|
706 |
|
707 | export function describeInjectedProperties(
|
708 | target: Object,
|
709 | ): MetadataMap<Readonly<Injection>> {
|
710 | const metadata =
|
711 | MetadataInspector.getAllPropertyMetadata<Readonly<Injection>>(
|
712 | INJECT_PROPERTIES_KEY,
|
713 | target,
|
714 | ) ?? {};
|
715 | return metadata;
|
716 | }
|
717 |
|
718 |
|
719 |
|
720 |
|
721 |
|
722 | export function inspectInjections(binding: Readonly<Binding<unknown>>) {
|
723 | const json: JSONObject = {};
|
724 | const ctor = binding.valueConstructor ?? binding.providerConstructor;
|
725 | if (ctor == null) return json;
|
726 | const constructorInjections = describeInjectedArguments(ctor, '').map(
|
727 | inspectInjection,
|
728 | );
|
729 | if (constructorInjections.length) {
|
730 | json.constructorArguments = constructorInjections;
|
731 | }
|
732 | const propertyInjections = describeInjectedProperties(ctor.prototype);
|
733 | const properties: JSONObject = {};
|
734 | for (const p in propertyInjections) {
|
735 | properties[p] = inspectInjection(propertyInjections[p]);
|
736 | }
|
737 | if (Object.keys(properties).length) {
|
738 | json.properties = properties;
|
739 | }
|
740 | return json;
|
741 | }
|
742 |
|
743 |
|
744 |
|
745 |
|
746 |
|
747 | function inspectInjection(injection: Readonly<Injection<unknown>>) {
|
748 | const injectionInfo = ResolutionSession.describeInjection(injection);
|
749 | const descriptor: JSONObject = {};
|
750 | if (injectionInfo.targetName) {
|
751 | descriptor.targetName = injectionInfo.targetName;
|
752 | }
|
753 | if (isBindingAddress(injectionInfo.bindingSelector)) {
|
754 |
|
755 | descriptor.bindingKey = injectionInfo.bindingSelector.toString();
|
756 | } else if (isBindingTagFilter(injectionInfo.bindingSelector)) {
|
757 |
|
758 | descriptor.bindingTagPattern = JSON.parse(
|
759 | JSON.stringify(injectionInfo.bindingSelector.bindingTagPattern),
|
760 | );
|
761 | } else {
|
762 |
|
763 | descriptor.bindingFilter =
|
764 | injectionInfo.bindingSelector?.name ?? '<function>';
|
765 | }
|
766 |
|
767 | if (injectionInfo.metadata) {
|
768 | if (
|
769 | injectionInfo.metadata.decorator &&
|
770 | injectionInfo.metadata.decorator !== '@inject'
|
771 | ) {
|
772 | descriptor.decorator = injectionInfo.metadata.decorator;
|
773 | }
|
774 | if (injectionInfo.metadata.optional) {
|
775 | descriptor.optional = injectionInfo.metadata.optional;
|
776 | }
|
777 | }
|
778 | return descriptor;
|
779 | }
|
780 |
|
781 |
|
782 |
|
783 |
|
784 |
|
785 |
|
786 |
|
787 | export function hasInjections(cls: Constructor<unknown>): boolean {
|
788 | return (
|
789 | MetadataInspector.getClassMetadata(INJECT_PARAMETERS_KEY, cls) != null ||
|
790 | Reflector.getMetadata(INJECT_PARAMETERS_KEY.toString(), cls.prototype) !=
|
791 | null ||
|
792 | MetadataInspector.getAllPropertyMetadata(
|
793 | INJECT_PROPERTIES_KEY,
|
794 | cls.prototype,
|
795 | ) != null
|
796 | );
|
797 | }
|