# 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
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
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 :
- HttpServer. This is an instance
of Http.Server (opens new window) from
http
module. - HttpsServer. This is an instance
of Https.Server (opens new window) from
https
module.
# 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
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
- Session & cookies
- Passport.js
- Keycloak
- Prisma
- TypeORM
- MikroORM
- Mongoose
- GraphQL
- GraphQL WS
- Apollo
- TypeGraphQL
- GraphQL Nexus
- Socket.io
- Swagger
- AJV
- Multer
- Serve static files
- Templating
- Serverless HTTP
- Seq
- OIDC
- Stripe
- Agenda
- Terminus
- Serverless
- IORedis
- Vike
- Jest
- Vitest
- Controllers
- Providers
- Model
- JsonMapper
- Middlewares
- Pipes
- Interceptors
- Authentication
- Hooks
- Exceptions
- Throw HTTP Exceptions
- Cache
- Command
- Response Filter
- Injection scopes
- Custom providers
- Lazy-loading provider
- Custom endpoint decorator
- Testing
- Customize 404