Skip to content

Providers

Overview

Providers are a way of creating injectable, reusable logic for any of your needs, that are meant to go hand-in-hand with your controllers. They are a way of encapsulating logic that is meant to be reused across multiple controllers, or even across multiple applications if you have a larger application.

Note: providers can be injected into other providers, controllers, or any other class but be aware, to not create circular dependencies.

Creating a Provider

To create a provider, you will utilise the @Provider decorator from the @sodacore/di package, like so:

typescript
import { Provider } from '@sodacore/di';

@Provider()
export class MyProvider {
	public quickMaths(num1: number, num2: number) {
		return num1 + num2;
	}
}

Congrats, you have a provider! Now, how do you use it?

Using a Provider

To use a provider, you will need to inject it into your controller, like so:

typescript
import { Controller, Get } from '@sodacore/http';
import { Inject } from '@sodacore/di';
import { MyProvider } from '../provider/my-provider';

@Controller('/example')
export class ExampleController {
	@Inject() private myProvider!: MyProvider;

	@Get()
	public async index() {
		return this.myProvider.quickMaths(2, 2);
	}
}

Note: the !: is a definite assignment assertion, this is because the provider is not resolved until it is first used (as a lazy getter is created specifically for preventing race conditions, etc), any errors, will be made pretty clear once you run your application though, so keep an eye out.

The DI library in Sodacore is meant to be a simple way to handle injections, and uses a global container that is shared across your sodacore application, also note that when using the @Inject decorator, you can pass in a string to the provider if you want to specify a specific thing you want to provide, this means you can technically inject general data that you have stored in the Registry class.

Released under the Apache-2.0 License.