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

cheap-di

Package Overview
Dependencies
Maintainers
1
Versions
71
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cheap-di

JavaScript dependency injection like Autofac in .Net

  • 3.3.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
76
increased by1420%
Maintainers
1
Weekly downloads
 
Created
Source

cheap-di

JavaScript's dependency injection like Autofac in .Net

  • Minimal Sample
  • How to use
  • TypeScript
  • Decorators

Minimal Sample

abstract class Logger {
  abstract debug: (message: string) => void;
}

class ConsoleLogger implements Logger {
  constructor(prefix) {
    this.prefix = prefix;
  }

  debug(message: string) {
    console.log(`${this.prefix}: ${message}`);
  }
}

const metadata = <T>(constructor: T): T => constructor;

@metadata
class Service {
  constructor(private logger: Logger) {}

  doSome() {
    this.logger.debug('Hello world!');
  }
}

// somewhere

import { container } from 'cheap-di';

const myLogPrefix = 'INFO: ';
container.registerType(ConsoleLogger).as(Logger).with(myLogPrefix);
container.registerType(Service);

const service = container.resolve(Service);
service.doSome();

How to use

You have an interface (base/abstract class) and its implementation (derived class)

user-repository.js

export class UserRepository {
  constructor() {
    if (new.target === UserRepository) {
      throw new TypeError('Cannot construct UserRepository instance directly');
    }
  }

  list() {
    throw new Error("Not implemented");
  }

  getById(userId) {
    throw new Error("Not implemented");
  }
}

fake-user-repository.js

import { UserRepository } from './user-repository';

export class FakeUserRepository extends UserRepository {
  constructor() {
    super();
    this.users = [
      {
        id: 1,
        name: 'user-1'
      },
      {
        id: 2,
        name: 'user-2'
      },
    ];
  }

  list() {
    return this.users;
  }

  getById(userId) {
    return this.users.find(user => user.id === userId);
  }
}

There is simple logger.

logger.js

export class Logger {
  debug(message) {
    throw new Error("Not implemented");
  }
}

console-logger.js

import { Logger } from './logger';

export class ConsoleLogger extends Logger {
  constructor(prefix) {
    super();
    this.prefix = prefix;
  }

  debug(message) {
    console.log(`${this.prefix}: ${message}`);
  }
}

You have the repository consumer. To allow DI container inject dependencies in your consumer class you should specify __dependencies static property. That property should contain constructor array in the order of your constructor.

user-service.js

import { dependenciesSymbol } from 'cheap-di';
import { Logger } from './logger';
import { UserRepository } from './user-repository';

export class UserService {
  static [dependenciesSymbol] = [UserRepository, Logger];

  constructor(userRepository, logger) {
    this.userRepository = userRepository;
    this.logger = logger;
  }

  list() {
    this.logger.debug('Access to users list');
    return this.userRepository.list();
  }

  get(userId) {
    return this.userRepository.getById(userId);
  }
}

Dependency registration

some-config.js

import { container } from 'cheap-di';
import { ConsoleLogger } from './console-logger';
import { FakeUserRepository } from './fake-user-repository';
import { Logger } from './logger';
import { UserRepository } from './user-repository';

container.registerType(ConsoleLogger).as(Logger).with('most valuable message prefix');
container.registerType(FakeUserRepository).as(UserRepository);

To get instance of your service with injected parameters you should call resolve method.

some-place.js

import { container } from 'cheap-di';
import { UserService } from './user-service';

const service = container.resolve(UserService);
const users = service.list();

Your injection parameter can be placed in middle of constructor params. In this case you should put undefined or null in [dependencies] with accordance order

import { dependenciesSymbol, container } from 'cheap-di';
// ...

export class UserService {
  static [dependenciesSymbol] = [UserRepository, undefined, Logger];

  constructor(userRepository, someMessage, logger) {
    // ...
  }
}

// ...

container.registerType(UserService).with('my injection string');

TypeScript

logger.ts

export abstract class Logger {
  abstract debug: (message: string) => void;
}

console-logger.ts

import { Logger } from './logger';

export class ConsoleLogger extends Logger {
  constructor(prefix) {
    super();
    this.prefix = prefix;
  }

  debug(message: string) {
    console.log(`${this.prefix}: ${message}`);
  }
}

You can use typescript reflection for auto resolve your class dependencies and inject them. For that you should add lines below to your tsconfig.json:

"emitDecoratorMetadata": true,
"experimentalDecorators": true,

and add any class-decorator to your class. For example:

metadata.ts

export const metadata = <T>(constructor: T): T => constructor;

service.ts

import { metadata } from './metadata';
import { Logger } from './logger';

@metadata
export class Service {
  constructor(private logger: Logger) {}

  doSome() {
    this.logger.debug('Hello world!');
  }
}

But you should explicitly register each type like this to resolve his dependencies by container:

import { container } from 'cheap-di';
import { Service } from './service';

container.registerType(Service);

const service = container.resolve(Service);
service.doSome();

In this scenario you don't need decorators from next section!


Decorators

If you want to use any of next decorators, you should add line below to your tsconfig.json:

"experimentalDecorators": true,

dependencies

@dependencies decorator can be used to simplify dependency syntax

user-service.ts

import { dependencies } from 'cheap-di';
import { Logger } from './logger';
import { UserRepository } from './user-repository';

@dependencies(UserRepository, Logger)
export class UserService {
  constructor(
    private userRepository: UserRepository,
    private logger: Logger,
  ) {}

  list() {
    this.logger.debug('Access to users list');
    return this.userRepository.list();
  }

  get(userId) {
    return this.userRepository.getById(userId);
  }
}

inject

@inject decorator can be used instead of @dependencies like below:

import { inject } from 'cheap-di';

export class UserService {
  constructor(
    @inject(UserRepository) private userRepository: UserRepository,
    @inject(Logger) private logger: Logger,
  ) {}
}

This approach allows you to mix dependency with injection params with any order:

class Service {
  constructor(
    message1: string,
    @inject(Repository) public repository: Repository,
    message2: string,
    @inject(Database) public db: Database,
  ) {
  }
}

const message1 = '123';
const message2 = '456';
container.registerType(Service).with(message1, message2);

di

This decorator uses typescript reflection, so you should add line below to your tsconfig.json:

"emitDecoratorMetadata": true,

@di decorator can be used instead of @dependencies and @inject like below:

import { di } from 'cheap-di';

@di
export class UserService {
  constructor(
    private userRepository: UserRepository,
    private logger: Logger,
  ) {}
}

@di
class Service {
  constructor(
    message1: string,
    public repository: UserRepository,
    message2: string,
    public db: Database,
  ) {}
}

const message1 = '123';
const message2 = '456';
container.registerType(Service).with(message1, message2);

It automatically adds @inject decorators to your service.

singleton

@singleton decorator allows you to inject the same instance everywhere.

import { singleton } from 'cheap-di';
import { Logger } from './logger';
import { UserRepository } from './user-repository';

@singleton
export class UserService {
  names: string[];

  constructor() {
    this.names = [];
  }

  list() {
    return this.names;
  }

  add(name: string) {
    this.names.push(name);
  }
}

You can see more examples in cheap-di/src/ContainerImpl.test.ts

Changelog

Keywords

FAQs

Package last updated on 25 Jun 2022

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