# All files / utils/container ContainerInstance.ts

56.6% Statements 60/106
57% Branches 57/100
34.78% Functions 8/23
59.41% Lines 60/101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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

    7x

    7x
    7x
    7x

    7x

    7x

    7x

    7x

    6x

    42x
    42x
    42x

    42x

    42x
    35x

    7x

    7x

    74x

    74x
    4x

    70x

    70x
    70x
    70x

    70x

    70x

    160x
    924x
    29x

    895x
    418x

    477x

    42x
    14x

    28x

    28x
    28x
    21x

    7x

    7x
    7x

    28x
    7x

    7x
    7x

    28x
    28x

    28x

    28x

    28x

    28x

    28x
    28x
    3x

    28x
    28x

    28x
    28x

    28x

    28x

     import { ServiceMetadata } from './types/ServiceMetadata';
    import { ObjectType } from './types/ObjectType';
    import { Token } from './Token';
    import { ServiceIdentifier } from './types/ServiceIdentifier';
    import { ServiceNotFoundError } from './error/ServiceNotFoundError';
    import { MissingProvidedServiceTypeError } from './error/MissingProvidedServiceTypeError';
    import { Container } from './Container';
    import { ControllerContainerService } from '..';
    import { controllerHooks } from '../services/controller-service/controller-hooks';

    /**
     * TypeDI can have multiple containers.
     * One container is ContainerInstance.
     */
    export class ContainerInstance {

        // -------------------------------------------------------------------------
        // Public Properties
        // -------------------------------------------------------------------------

        /**
         * Container instance id.
         */
        id: any;

        // -------------------------------------------------------------------------
        // Private Properties
        // -------------------------------------------------------------------------

        /**
         * All registered services.
         */
        private services: ServiceMetadata<any, any>[] = [];

        // -------------------------------------------------------------------------
        // Constructor
        // -------------------------------------------------------------------------

        constructor(id: any) {
            this.id = id;
        }

        // -------------------------------------------------------------------------
        // Public Methods
        // -------------------------------------------------------------------------

        /**
         * Checks if the service with given name or type is registered service container.
         * Optionally, parameters can be passed in case if instance is initialized in the container for the first time.
         */
        has<T>(type: ObjectType<T>): boolean;

        /**
         * Checks if the service with given name or type is registered service container.
         * Optionally, parameters can be passed in case if instance is initialized in the container for the first time.
         */
        has<T>(id: string): boolean;

        /**
         * Checks if the service with given name or type is registered service container.
         * Optionally, parameters can be passed in case if instance is initialized in the container for the first time.
         */
        has<T>(id: Token<T>): boolean;

        /**
         * Checks if the service with given name or type is registered service container.
         * Optionally, parameters can be passed in case if instance is initialized in the container for the first time.
         */
        has<T>(identifier: ServiceIdentifier): boolean {
            return !!this.findService(identifier);
        }

        /**
         * Retrieves the service with given name or type from the service container.
         * Optionally, parameters can be passed in case if instance is initialized in the container for the first time.
         */
        get<T>(type: ObjectType<T>): T;

        /**
         * Retrieves the service with given name or type from the service container.
         * Optionally, parameters can be passed in case if instance is initialized in the container for the first time.
         */
        get<T>(id: string): T;

        /**
         * Retrieves the service with given name or type from the service container.
         * Optionally, parameters can be passed in case if instance is initialized in the container for the first time.
         */
        get<T>(id: Token<T>): T;

        /**
         * Retrieves the service with given name or type from the service container.
         * Optionally, parameters can be passed in case if instance is initialized in the container for the first time.
         */
        get<T>(identifier: ServiceIdentifier): T {

            const globalContainer = Container.of(undefined);
            const service = globalContainer.findService(identifier);
            const scopedService = this.findService(identifier);

            Iif (service && service.global === true)
                return this.getServiceValue(identifier, service);

            if (scopedService)
                return this.getServiceValue(identifier, scopedService);

            Iif (service && this !== globalContainer) {
                const clonedService = Object.assign({}, service);
                clonedService.value = undefined;
                return this.getServiceValue(identifier, clonedService);
            }

            return this.getServiceValue(identifier, service);
        }

        /**
         * Gets all instances registered in the container of the given service identifier.
         * Used when service defined with multiple: true flag.
         */
        getMany<T>(id: string): T[];

        /**
         * Gets all instances registered in the container of the given service identifier.
         * Used when service defined with multiple: true flag.
         */
        getMany<T>(id: Token<T>): T[];

        /**
         * Gets all instances registered in the container of the given service identifier.
         * Used when service defined with multiple: true flag.
         */
        getMany<T>(id: string | Token<T>): T[] {
            return this.filterServices(id).map(service => this.getServiceValue(id, service));
        }

        /**
         * Sets a value for the given type or service name in the container.
         */
        set<T, K extends keyof T>(service: ServiceMetadata<T, K>): this;

        /**
         * Sets a value for the given type or service name in the container.
         */
        set(type: Function, value: any): this;

        /**
         * Sets a value for the given type or service name in the container.
         */
        set(name: string, value: any): this;

        /**
         * Sets a value for the given type or service name in the container.
         */
        set(token: Token<any>, value: any): this;

        /**
         * Sets a value for the given type or service name in the container.
         */
        set<T, K extends keyof T>(values: ServiceMetadata<T, K>[]): this;

        /**
         * Sets a value for the given type or service name in the container.
         */
        set(identifierOrServiceMetadata: ServiceIdentifier | ServiceMetadata<any, any> | (ServiceMetadata<any, any>[]), value?: any): this {
            Iif (identifierOrServiceMetadata instanceof Array) {
                identifierOrServiceMetadata.forEach((v: any) => this.set(v));
                return this;
            }
            if (typeof identifierOrServiceMetadata === 'string' || identifierOrServiceMetadata instanceof Token) {
                return this.set({ id: identifierOrServiceMetadata, value: value });
            }
            Iif (identifierOrServiceMetadata instanceof Function) {
                return this.set({ type: identifierOrServiceMetadata, id: identifierOrServiceMetadata, value: value });
            }

            // const newService: ServiceMetadata<any, any> = arguments.length === 1 && typeof identifierOrServiceMetadata === 'object'  && !(identifierOrServiceMetadata instanceof Token) ? identifierOrServiceMetadata : undefined;
            const newService: ServiceMetadata<any, any> = identifierOrServiceMetadata;
            const service = this.findService(newService.id);
            Iif (service && service.multiple !== true) {
                Object.assign(service, newService);
            } else {
                this.services.push(newService);
            }

            return this;
        }

        /**
         * Removes services with a given service identifiers (tokens or types).
         */
        remove(...ids: ServiceIdentifier[]): this {
            ids.forEach(id => {
                this.filterServices(id).forEach(service => {
                    this.services.splice(this.services.indexOf(service), 1);
                });
            });
            return this;
        }

        /**
         * Completely resets the container by removing all previously registered services from it.
         */
        reset(): this {
            this.services = [];
            return this;
        }

        // -------------------------------------------------------------------------
        // Private Methods
        // -------------------------------------------------------------------------

        /**
         * Filters registered service in the with a given service identifier.
         */
        private filterServices(identifier: ServiceIdentifier): ServiceMetadata<any, any>[] {
            return this.services.filter(service => {
                if (service.id)
                    return service.id === identifier;

                if (service.type && identifier instanceof Function)
                    return service.type === identifier || identifier.prototype instanceof service.type;

                return false;
            });
        }

        /**
         * Finds registered service in the with a given service identifier.
         */
        private findService(identifier: ServiceIdentifier): ServiceMetadata<any, any> | undefined {
            return this.services.find(service => {
                if (service.id)
                    return service.id === identifier;

                if (service.type && identifier instanceof Function)
                    return service.type === identifier; // || identifier.prototype instanceof service.type;

                return false;
            });
        }

        /**
         * Gets service value.
         */
        private getServiceValue(identifier: ServiceIdentifier, service: ServiceMetadata<any, any> | undefined): any {

            // find if instance of this object already initialized in the container and return it if it is
            if (service && service.value !== null && service.value !== undefined)
                return service.value;

            // if named service was requested and its instance was not found plus there is not type to know what to initialize,
            // this means service was not pre-registered and we throw an exception
            Iif ((!service || !service.type) &&
                (!service || !service.factory) &&
                (typeof identifier === 'string' || identifier instanceof Token))
                throw new ServiceNotFoundError(identifier);

            // at this point we either have type in service registered, either identifier is a target type
            let type = undefined;
            if (service && service.type) {
                type = service.type;

            } else Iif (service && service.id instanceof Function) {
                type = service.id;

            } else Eif (identifier instanceof Function) {
                type = identifier;
            }

            // if service was not found then create a new one and register it
            if (!service) {
                Iif (!type)
                    throw new MissingProvidedServiceTypeError(identifier);

                service = { type: type };
                this.services.push(service);
            }

            // setup constructor parameters for a newly initialized service
            const paramTypes = type && Reflect && (Reflect as any).getMetadata ? (Reflect as any).getMetadata('design:paramtypes', type) : undefined;
            let params: any[] = paramTypes ? this.initializeParams(type, paramTypes) : [];

            // if factory is set then use it to create service instance
            let value: any;
            Iif (service.factory) {

                // filter out non-service parameters from created service constructor
                // non-service parameters can be, lets say Car(name: string, isNew: boolean, engine: Engine)
                // where name and isNew are non-service parameters and engine is a service parameter
                params = params.filter(param => param !== undefined);

                if (service.factory instanceof Array) {
                    // use special [Type, 'create'] syntax to allow factory services
                    // in this case Type instance will be obtained from Container and its method 'create' will be called
                    value = (this.get(service.factory[0]) as any)[service.factory[1]](...params);

                } else { // regular factory function
                    value = service.factory(...params);
                }

            } else {  // otherwise simply create a new object instance
                Iif (!type)
                    throw new MissingProvidedServiceTypeError(identifier);

                params.unshift(null);

                // 'extra feature' - always pass container instance as the last argument to the service function
                // this allows us to support javascript where we don't have decorators and emitted metadata about dependencies
                // need to be injected, and user can use provided container to get instances he needs
                params.push(this);

                value = new (type.bind.apply(type, params))();
                if (type.prototype._controller) {
                    controllerHooks.setHook(type.name, value);
                }
            }

            Eif (service && !service.transient && value)
                service.value = value;

            Eif (type)
                this.applyPropertyHandlers(type, value);

            return value;
        }

        /**
         * Initializes all parameter types for a given target service class.
         */
        private initializeParams(type: Function, paramTypes: any[]): any[] {
            return paramTypes.map((paramType, index) => {
                const paramHandler = Container.handlers.find(handler => handler.object === type && handler.index === index);
                if (paramHandler)
                    return paramHandler.value(this);

                if (paramType && paramType.name && !this.isTypePrimitive(paramType.name)) {
                    return this.get(paramType);
                }

                return undefined;
            });
        }

        /**
         * Checks if given type is primitive (e.g. string, boolean, number, object).
         */
        private isTypePrimitive(param: string): boolean {
            return ['string', 'boolean', 'number', 'object'].indexOf(param.toLowerCase()) !== -1;
        }

        /**
         * Applies all registered handlers on a given target class.
         */
        private applyPropertyHandlers(target: Function, instance: { [key: string]: any }) {
            Container.handlers.forEach(handler => {
                if (typeof handler.index === 'number') return;
                if (handler.object.constructor !== target && !(target.prototype instanceof handler.object.constructor))
                    return;

                instance[handler.propertyName] = handler.value(this);
            });
        }

    }