# Factory

Factory is similar to Service except that the factory uses an already instantiated object and you have to use the @Inject() decorator to inject the factory to other Service or Controller.

# Declare a factory from an instance

This example shows you how you can add an already constructed service like a npm module.

// MyFooFactory.ts
import {registerProvider} from "@tsed/common";

export interface MyFooFactory {
  getFoo(): string;
}

export const MyFooFactory = Symbol("MyFooFactory");

registerProvider(MyFooFactory, {
  getFoo: () => "test"
});
1
2
3
4
5
6
7
8
9
10
11
12

Then inject your factory in another service (or controller):

import {Inject, Injectable} from "@tsed/di";
import {MyFooFactory} from "./FooFactory.ts";

@Injectable()
export default class OtherService {
  constructor(@Inject(MyFooFactory) myFooFactory: MyFooFactory) {
    console.log(myFooFactory.getFoo()); /// "test"
  }
}
1
2
3
4
5
6
7
8
9

TIP

Note TypeScript transforms and stores MyFooFactory as Function type in the metadata. So to inject a factory, you must use the Inject decorator.

# Built-in Factory

Some factories are built-in Ts.ED. These factories are :

# Inject Http.Server or Https.Server

import {Injectable} from "@tsed/di";
import Http from "http";
import Https from "https";

@Injectable()
export default class OtherService {
  @Inject(Http.Server)
  httpServer: Http.Server | null;

  @Inject(Https.Server)
  httpsServer: Https.Server | null;

  $onInit() {
    if (this.httpServer) {
      console.log("HTTP");
    }
    if (this.httpsServer) {
      console.log("HTTPS");
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Last Updated: 4/25/2024, 6:36:50 AM

Other topics