-
Notifications
You must be signed in to change notification settings - Fork 109
Service Factory and IoC
It is possible to control how Typescript Rest will instantiate your services. It is useful, for example, to integrate it with an IoC Container.
For example, to use typescript-ioc, you can install the IoC container and configure a serviceFactory to use the IoC Container. The module typescript-rest-ioc provides a factory for it.
npm install typescript-rest --save
npm install typescript-ioc --save
npm install typescript-rest-ioc --save
Then, to configure Typescript rest to use your factory, you can add a rest.config file in the root of your project:
{
"serviceFactory": "typescript-rest-ioc"
}
Or call the method Server.registerServiceFactory
directly in your code.
And now you can use Injections, Request scopes and all the features of the IoC Container. It is possible to use it with any other IoC Container, like Inversify.
Example:
class HelloService {
sayHello(name: string) {
return "Hello " + name;
}
}
@Path("/hello")
class HelloRestService {
@Inject
private helloService: HelloService;
@Path(":name")
@GET
sayHello( @PathParam('name') name: string): string {
return this.sayHello(name);
}
}
To create your own factory, just extends the interface ServiceFactory:
export interface ServiceFactory {
/**
* Create a new service object. Called before each request handling.
*/
create: (serviceClass: Function, context: ServiceContext) => any;
/**
* Return the type used to handle requests to the target service.
* By default, returns the serviceClass received, but you can use this
* to implement IoC integrations, once some frameworks like typescript-ioc or
* Inversify can override constructors for injectable types.
*/
getTargetClass: (serviceClass: Function) => FunctionConstructor;
}
- Server
- @Path Decorator
- Http Methods
- Request Parameters
- Types and languages
- @BodyOptions Decorator
- Service Context
- Service Return
- @Security Decorator
- Express Middlewares
- @PreProcessor Decorator
- @PostProcessor Decorator
- Server Errors
- Service Factory and IoC
- Inheritance and Abstract Services
- Swagger Documentation