Factory

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

Declare a factory from an instance

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

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

export interface IMyFooFactory {
   getFoo(): string;
}

export type MyFooFactory = IMyFooFactory;
export const MyFooFactory = Symbol("MyFooFactory");

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

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

// otherservice.ts
import {MyFooFactory} from "./FooFactory.ts";

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

Note: TypeScript transform and store MyFooFactory as Function type in the metadata. So to inject a factory, you must use the @Inject(type) decorator.

Built-in Factory

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

Inject ExpressApplication

import {ExpressApplication, Service, Inject} from "@tsed/common";

@Service()
export default class OtherService {
     constructor(@Inject(ExpressApplication) expressApplication: ExpressApplication){
           expressApplication.use("/", (request, response, next) => {
               
           });
     }
}
1
2
3
4
5
6
7
8
9
10

Note: TypeScript transform and store ExpressApplication as Function type in the metadata. So to inject a factory, you must use the @Inject(type) decorator.

Inject HttpServer or HttpsServer

import {HttpServer, Service, Inject} from "@tsed/common";

@Service()
export default class OtherService {
     constructor(@Inject(HttpServer) httpServer: HttpServer){
           const server = HttpServer.get(); // return the Http.Server instance
     }
}
1
2
3
4
5
6
7
8