Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

dependency-injection-cat

Package Overview
Dependencies
Maintainers
1
Versions
67
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

dependency-injection-cat

![npm](https://img.shields.io/npm/v/dependency-injection-cat?style=flat) # dependency-injection-cat

  • 0.0.5
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
172
increased by4.88%
Maintainers
1
Weekly downloads
 
Created
Source

npm

dependency-injection-cat

Dependency Injection Cat is a TypeScript-only library which allows you to implement the Dependency Inversion pattern with Dependency Injection

Installation

Yarn

yarn add dependency-injection-cat

NPM

npm install dependency-injection-cat
Config options
interface TransformerConfig {
    diConfigPattern?: string; // Glob pattern, default value = '**/*.diconfig.ts'
    ignorePatterns?: string[]; // Array of Glob patterns, default value = ['**/node_modules/**']
}
Configuration with Webpack

Dependency Injection Cat supports transpileOnly mode for faster builds! More Info
With Webpack, You can use any TypeScript-related loader that supports custom transformers, e.g. awesome-typescript-loader or ts-loader

webpack.config.js
const dependencyInjectionCatTransformer = require('dependency-injection-cat/transformer').default;
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'ts-loader', // or 'awesome-typescript-loader'
        options: {
          transpileOnly: true, // If set transpileOnly: true, you're loosing TypeChecking
          getCustomTransformers: program => ({
              before: [
                  dependencyInjectionCatTransformer(program)
              ]
          })
        }
      }
    ]
  }
};
With custom options
In webpack.config.js you can pass a second parameter to the transformer:
before: [
  dependencyInjectionCatTransformer(program, {
    diConfigPattern: '**/config/**/*.diconfig.ts'
  })
]
Configuration with ttypescript

Check out ttypescript's README for more information

tsconfig.json
{
  "compilerOptions": {
    "plugins": [
      {
        "transform": "dependency-injection-cat/transformer"
      }
    ]
  }
}
With custom options
{
  "compilerOptions": {
    "plugins": [
      {
        "transform": "dependency-injection-cat/transformer",
        "diConfigPattern": "**/config/**/*.diconfig.ts"
      }
    ]
  }
}

Usage

// requesters.diconfig.ts
import { Bean, Qualifier } from 'dependency-injection-cat';
import { IRequester } from '../IRequester';
import { Requester } from '../Requester';
import { ILogger } from '../ILogger';

export class Requesters {
    @Bean
    requester(logger: ILogger): IRequester {
        return new Requester(logger);
    }
    //or
    requester = Bean<IRequester>(Requester);
}

// loggers.diconfig.ts
import { Bean } from 'dependency-injection-cat';
import { ILogger } from '../ILogger';
import { Logger } from '../Logger';

export class Loggers {
    @Bean
    logger(): ILogger {
        return new Logger();
    }
    //or
    @Bean
    logger = Bean<ILogger>(Logger);
}

// main.ts
import { container } from 'dependency-injection-cat';
import { IRequester } from './IRequester';

const requester = container.get<IRequester>();

requester.makeRequest();

Bean

Rules
  • Bean should be a class member (property or method)
  • Beans should not have cyclic dependencies (it will throw compilation error)
  • Beans should not have duplicate declarations
  • Beans can be used only in diconfig.ts files (or files with another pattern declared in transformer config)
  • Bean type should not be empty (it will throw compilation error)
  • Bean type should not be primitive (it will throw compilation error)
  • All bean dependencies should be typed, and type should not be primitive
Syntax
Beans support 2 kinds of syntax
First
import { Bean } from 'dependency-injection-cat';

class SuperClass {
    //Without any dependencies
    @Bean
    someMethod(): Interface {
       return new ImplementationOfInterface();
    }

    //With Bean dependencies
    @Bean
    someMethod(
        dependency1: InterfaceOfDependency1,
        dependency2: InterfaceOfDependency2,
    ): Interface {
       return new ImplementationOfInterface(dependency1, dependency2);
    }

    //With Bean configuration
    @Bean({ qualifier: 'someCoolImpl', scope: 'prototype' })
    someMethod(
        dependency1: InterfaceOfDependency1,
        dependency2: InterfaceOfDependency2,
    ): Interface {
       return new ImplementationOfInterface(dependency1, dependency2);
    }

    //Beans do not support arrow-functions methods, this will throw an error
    @Bean
    someMethod = (): Interface => new ImplementationOfInterface();

    //Beans should have complex types, this will throw an error
    @Bean
    someMethod(): number | string | any {
        return new ImplementationOfInterface();
    }

    //Should not have cyclyc dependencies, this will throw an error
    @Bean
    someMethod(
        dependency1: InterfaceOfDependency1, //Cyclic dependency
    ): Interface {
        return new ImplementationOfInterface(dependency1);
    }

    @Bean
    someMethod2(
        dependency1: Interface, //Cyclic dependency
    ): InterfaceOfDependency1 {
        return new ImplementationOfDependency(dependency1);
    }
}
Second
import { Bean } from 'dependency-injection-cat';

class SuperClass {
    //If you don't need to pass specific dependencies in Bean, it will resolve all dependencies automatically 
    someBeanProperty = Bean<Interface>(ImplementationOfInterface);

    //With Bean configuration
    //First argument in Bean should always be implementation of interface, second is configuration object
    //When using this syntax, implementation should be a class 
    //You should pass Bean type in generic
    someBeanProperty = Bean<Interface>(ImplementationOfInterface, { qualifier: 'someCoolImpl' });
}
Bean configuration object
interface BeanConfiguration {
    //By default all beans are singleton, if you will set scope 'prototype' Bean will no longer be a singleton
    scope?: 'prototype' | 'singleton';
    //Read about Qualifiers and their rules below
    qualifier?: string;
}

Qualifier

What is it?

In fact, Qualifier it's just a name of Bean You can use it, if you have a few different implementations of interface

Rules
  • Qualifier be a string, and should not be empty string
  • Qualifier should not be dynamically calculated (no template strings, or references to constants/properties)
Syntax
import { Bean, Qualifier } from 'dependency-injection-cat';

class SuperClass {
    //Correct example
    @Bean
    someMethod(
        @Qualifier('someQualifier') dependency1: InterfaceOfDependency1,
    ): Interface {
       return new ImplementationOfInterface();
    }
}
//Wrong examples
import { Bean, Qualifier } from 'dependency-injection-cat';

const superQualifierName = 'superQualifierNameValue';

class SuperClass {
    @Bean
    someMethod(
        @Qualifier(superQualifierName) dependency1: InterfaceOfDependency1,
    ): Interface {
       return new ImplementationOfInterface();
    }
    @Bean
    someMethod(
        @Qualifier('') dependency1: InterfaceOfDependency1,
    ): Interface {
       return new ImplementationOfInterface();
    }
}

Container

Container has only one method "get"

Rules
  • You should pass type as generic in get method of Container
Syntax
//Any TypeScript file in project
import { container } from 'dependency-injection-cat';

//Without Qualifier
const someBean = container.get<Interface>();

//With Qualifier
const someBean = container.get<Interface>('someQualifier');

Author

License

This project is under the MIT License

FAQs

Package last updated on 29 Sep 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc