npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

friendly-di

v1.0.0

Published

Friendly DI is light and fast Inversion Of Control Container based on Reflect metadata inspired by Angular and Nest DI systems.

Downloads

57

Readme

Friendly DI is light and fast Inversion Of Control Container based on Reflect metadata inspired by Angular and Nest DI systems.

Friendly DI is very versatile tool. You can use it in Node.js projects (express, koa, whatever), in the Browser (pure JS projects, React projects etc.).

Benefits:

  • 2kb size without dependencies
  • Works the same in the Browser and Node.js
  • Very simple API

How it works

IoC Container pattern helps to solve the problem of tightly coupled dependencies. The idea behind this approach is that a class does not depend on another class directly, but depends on an interface. Thus, if there is a need to replace one of the dependencies, it is enough for the declare dependency with the same interfaces into the IoC Container.

  • Classes are linked via interfaces
  • IoC Container registers dependencies
  • When a class is extracted from a container, it will have all declared or substituted dependencies

Usage

Friendly DI based the same idea as Angular DI has and NestJS DI has. We used interfaces in the constructor and Container establish connection from real instances and interfaces via metadata.

Friendly DI has Typescript metadata support. It's not possible to run it without Typescript.

  1. Installation:
npm i friendly-di reflect-metadata
  1. Add 2 lines in tsconfig.json:
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}
  1. Add Injectable decorator to each class and declare dependencies in constructor:

! Important:

It is recommended to containerize the root of your application to comply with the composition root to avoid the service locator anti-pattern. In this example class App is our composition root.

import 'reflect-metadata';
import { Injectable, Container } from 'friendly-di';

@Injectable()
class ProductService {
  getProducts() {
    return ['product 1', 'product 2', 'product 3'];
  }
}

@Injectable()
class OrderService {
  constructor(private productService: ProductService) {
  }

  getOrdersForUser() {
    return this.productService.getProducts();
  }
}

@Injectable()
export class UserService {
  constructor(private orderService: OrderService) {
  }

  getUserOrders() {
    return this.orderService.getOrdersForUser();
  }
}


@Injectable()
export class App {
  constructor(private userService: UserService) {
  }

  run() {
    return this.userService.getUserOrders();
  }
}
  1. Declare container and root class:
const app = new Container(App).compile();

app.run() // 'product 1', 'product 2', 'product 3'

Use Cases

If we need to mock nested dependencies we should:

  1. Make mock-class with similar interface:
@Injectable()
class MockProductService {
  getProducts() {
    return ['new product 1', 'new product 2', 'new product 3'];
  }
}
  1. When we declare container with root we also can replace classes:
const app = new Container(App)
  .replace(ProductService, MockProductService)
  .compile();

app.run() // 'new product 1', 'new product 2', 'new product 3'

replace method receives 2 arguments: Replaceable class, Class to be replaced.

Method replace is chainable, so we can make replace many times:

const app = new Container(App)
  .replace(ProductService, MockProductService)
  .replace(OrderService, MockOrderService)
  .compile();

app.run() // 'new product 1', 'new product 2', 'new product 3'

Limitations

TSX issue

Currently, friendly-di has problems with tsx usage. If you need use friendly-di in Node.js project please use ts-node/esm loader:

node --loader ts-node/esm index.ts

Interfaces Dependency

friendly-di is not support interface as a dependency. Please use classes:

Wrong

interface ProductServiceInterface {
  getProducts(): string[];
}
@Injectable()
class OrderService {
  constructor(private productService: ProductServiceInterface) {
  }

  getOrdersForUser() {
    return this.productService.getProducts();
  }
}

Correct

@Injectable()
class ProductService {
  getProducts() {
    return ['product 1', 'product 2', 'product 3'];
  }
}

@Injectable()
class OrderService {
  constructor(private productService: ProductService) {
  }

  getOrdersForUser() {
    return this.productService.getProducts();
  }
}

Alternatives

If you use projects like Angular, NestJS... I congratulate you! You don't need friendly-di, as there is already a great and very similar DI system there.

Inversify - The most popular IoC Container library in JS.The downside is that you'll have to write a lot of boilerplate code. It has a large number of features that may be specific to large projects.

The MIT License

Copyright (c) Sergey Aleksandrov

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.