1.0.7 • Published 6 years ago

nest-provider-builders v1.0.7

Weekly downloads
2
License
MIT
Repository
github
Last release
6 years ago

NestJS Provider Builders

A library that facilitates declaring providers for NestJS.

npm install nest-provider-builders

or

yarn add nest-provider-builders

Before, you had to

Create providers manually, like so:

  @Module({
    providers: [
      {
        provide: 'AnInterface',
        useClass: AnImplementedInterface
      }
    ]
  })

But now, with provider builders:

  @Module({
    providers: [
      bind<AnInterface>('AnInterface').withClass(AnImplementedInterface),
    ]
  })

Why was this made?

  • To add type safety for declaring providers. The typings of the provider object do not ensure that the value provided will be of the same type as the provide key. This is why you must specify a type when using bind<T>, as it will ensure that the binded value is of the same type.
  • To provide (pun intended) better readability. Declaring providers takes a lot of space, so a module with many providers will be uselessly big. By using this library, most providers will be one liners that can be read like a sentence.

Binding to a...

Value / Constant

  @Module({
    providers: [
      bind<string>('WelcomeMessage').withConstant('Welcome to the world of dependency injection!'),
    ]
  })

Class (using bindClass)

  class AClass {};

  @Module({
    providers: [
        bindClass(AClass),
    ]
  })

Class (using bind)

  class AClass {};

  @Module({
    providers: [
      bind<AClass>(AClass).withClass(AClass),
    ]
  })

Factory

  class AClass {};

  const aClassFactory = () => new AClass();

  @Module({
    providers: [
      bind<AClass>(AClass).withFactory(aClassFactory),
    ]
  })

Factory with injectable dependencies

  class DBConnexion { constructor(public readonly connexionString: string) };

  interface Configuration {
    username: string,
    password: string,
  }

  const connexionFactory = (config: Configuration) => new DBConnexion(`${config.username}:${config.password}`);

  @Module({
    providers: [
      bind<Configuration>('Configuration').withConstant({
        username: 'username!',
        password: 'passw0rd!'
      }),
      bind<DBConnexion>(DBConnexion).withInjectableFactory(aClassFactory)
                                    .inject('Configuration'),
                                    .build()
    ]
  })
1.0.7

6 years ago

1.0.6

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago