# Configuration
lets you quickly configure your server via decorator. This decorator takes your configuration and merges it with the default server configuration.
The default configuration is as follows:
{
"rootDir": "path/to/root/project",
"env": "development",
"port": 8080,
"debug": false,
"httpsPort": 8000,
"uploadDir": "${rootDir}/uploads",
"mount": {
"/rest": "${rootDir}/controllers/**/*.ts"
},
"componentsScan": [
"${rootDir}/middlewares/**/*.ts",
"${rootDir}/services/**/*.ts",
"${rootDir}/converters/**/*.ts"
],
"routers": {
"mergeParams": false,
"strict": false,
"caseSensitive": false
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
You can customize your configuration as follows on Server.ts
level:
or when you bootstrap your Server (e.g. index.ts
):
import {$log} from "@tsed/common";
import {PlatformExpress} from "@tsed/platform-express";
import {Server} from "./Server";
async function bootstrap() {
try {
$log.debug("Start server...");
const platform = await PlatformExpress.bootstrap(Server, {
// extra settings
});
await platform.listen();
$log.debug("Server initialized");
} catch (er) {
$log.error(er);
}
}
bootstrap();
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Note
Ts.ED supports ts-node. Ts extension will be replaced by a Js extension if ts-node isn't the runtime.
# Load configuration from file
It is also possible to use node-config or dotenv to load your configuration from file:
# Options
# rootDir
- type:
string
The root directory where you build run project. By default, it is equal to process.cwd()
.
import {Configuration} from "@tsed/di";
import {resolve} from "path";
const rootDir = resolve(__dirname);
@Configuration({
rootDir
})
export class Server {}
2
3
4
5
6
7
8
9
# env
- type:
The environment profiles. By default the environment profile is equal to NODE_ENV
.
import {Env} from "@tsed/core";
import {Configuration, Constant} from "@tsed/di";
@Configuration({
env: Env.PROD
})
export class Server {
@Constant('env')
env: Env;
$beforeRoutesInit() {
if (this.env === Env.PROD) {
// do something
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# httpPort
- type:
string
|number
|false
Port number for the HTTP.Server.
Set false
to disable the http port.
# httpsPort
- type:
string
|number
|false
Port number for the HTTPs.Server.
# httpsOptions
- type: Https.ServerOptions)
key
<string> | <string[]> | <Buffer> | <Object[]>: The private key of the server in PEM format. To support multiple keys using different algorithms, an array can be provided either as a plain array of key strings or an array of objects in the format{pem: key, passphrase: passphrase}
. This option is required for ciphers making use of private keys.passphrase
<string> A string containing the passphrase for the private key or pfx.cert
<string> | <string[]> | <Buffer> | <Buffer[]>: A string, Buffer, array of strings, or array of Buffers containing the certificate key of the server in PEM format. (Required)ca
<string> | <string[]> | <Buffer> | <Buffer[]>: A string, Buffer, array of strings, or array of Buffers of trusted certificates in PEM format. If this is omitted, several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections.
See the HTTPs project example
# mount
- type:
Mount all given controllers and map controllers to the corresponding endpoints.
Ts.ED provides the possibility to mount multiple Rest paths instead of the default path /rest
.
This option will allow you to define a version for an endpoint and select which controllers you want to associate with the given path.
import {Configuration} from "@tsed/di";
import {resolve} from "path";
const rootDir = resolve(__dirname);
@Configuration({
rootDir,
mount: {
"/rest/v1": [
`${rootDir}/controllers/v1/**/*.ts`
],
"/rest/v0": [
`${rootDir}/controllers/v0/users/*.ts`,
`${rootDir}/controllers/v0/groups/*.ts`
]
}
})
export class Server {
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
It is also possible to split the configuration by using the :
# componentsScan
- type:
string[]
List of glob pattern to scan directories which contains Services, Middlewares or Converters.
# imports
- type:
Type<any>[]
Add providers or modules here. These modules or providers will be built before the server itself.
# exclude
- type:
string[]
List of glob patterns. Exclude all files that match with this list when the Server scans all components with the mount
or scanComponents
options.
# scopes
- type:
{[key: string]: ProviderScope}
Change the default scope for a given provider. See injection scopes for more details.
import {Configuration, ProviderScope, ProviderType} from "@tsed/di";
@Configuration({
scopes: {
[ProviderType.CONTROLLER]: ProviderScope.REQUEST
}
})
export class Server {
}
2
3
4
5
6
7
8
9
# logger
- type:
Logger configuration.
# resolvers - External DI v5.39.0+
- type:
Ts.ED has its own DI container, but sometimes you have to work with other DI like Inversify or TypeDI. The version 5.39.0+
now allows you to configure multiple external DI by using the resolvers
options.
The resolvers options can be configured as following:
import {Configuration} from "@tsed/common";
import {resolve} from "path";
import {myContainer} from "./inversify.config";
const rootDir = resolve(__dirname);
@Configuration({
rootDir,
resolvers: [
{
get(token: any) {
return myContainer.get(token);
}
}
]
})
export class Server {
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
It's also possible to register resolvers with the decorator:
import {Module} from "@tsed/di";
import {myContainer} from "./inversify.config";
@Module({
resolvers: [
{
get(token: any) {
return myContainer.get(token);
}
}
]
})
export class MyModule {
}
2
3
4
5
6
7
8
9
10
11
12
13
14
# acceptMimes
Configure the mimes accepted by default for each request by the server. Require adding to work.
# Express options
Some configuration options are related to PlatformExpress itself.
# express.router
The global configuration for the Express.Router. See express documentation.
# statics
- type:
Object to mount all directories under an endpoint. See more on Serve Static.
# HTTP & HTTPs server
# Change address
It's possible to change the HTTP and HTTPS server address as follows:
import {Configuration} from "@tsed/common";
@Configuration({
httpPort: "127.0.0.1:8081",
httpsPort: "127.0.0.2:8082",
})
export class Server {}
2
3
4
5
6
7
# Random port
Random port assignment can be enable with the value 0
. The port assignment will be delegated to the OS.
import {Configuration} from "@tsed/common";
@Configuration({
httpPort: "127.0.0.1:0",
httpsPort: "127.0.0.2:0",
})
export class Server {}
2
3
4
5
6
7
Or:
import {Configuration} from "@tsed/common";
@Configuration({
httpPort: 0,
httpsPort: 0,
})
export class Server {}
2
3
4
5
6
7
# Disable HTTP
import {Configuration} from "@tsed/common";
@Configuration({
httpPort: false
})
export class Server {}
2
3
4
5
6
# Disable HTTPS
import {Configuration} from "@tsed/common";
@Configuration({
httpsPort: false,
})
export class Server {}
2
3
4
5
6
# Logger
# Default logger
Default logger used by Ts.ED is @tsed/logger.
# Configuration
Some options are provided:
logger.level
: Change the default log level displayed in the terminal. Values:debug
,info
,warn
orerror
. By default:info
.logger.logRequest
: Log all incoming requests. By default, it's true and prints the configuredlogger.requestFields
.logger.requestFields
: Fields displayed when a request is logged. Possible values:reqId
,method
,url
,headers
,body
,query
,params
,duration
.logger.reqIdBuilder
: A function called for each incoming request to create a request id.logger.jsonIndentation
: The number of space characters to use as white space in JSON output. Default is 2 (0 in production).logger.disableRoutesSummary
: Disable routes table displayed in the logger. By default debug isfalse
.logger.format
: Specify log format. Example:%[%d{[yyyy-MM-dd hh:mm:ss,SSS}] %p%] %m
. See @tsed/logger configuration.logger.ignoreUrlPatterns
(String
orRegExp
): List of patterns to ignore logged request according to therequest.url
.
WARNING
It is recommended to disable logRequest in production. Logger has a cost on the performance.
# Request logger
For each Express.Request, a logger will be attached and can be used like here:
import {Controller, Context, Get, RequestLogger} from "@tsed/common";
@Controller("/")
class MyController {
@Get('/')
get(@Context("logger") logger: RequestLogger) {
logger.info({customData: "test"}); // parameter is optional
logger.debug({customData: "test"})
logger.warn({customData: "test"})
logger.error({customData: "test"})
logger.trace({customData: "test"})
}
}
2
3
4
5
6
7
8
9
10
11
12
13
A call with one of these methods will generate a log according to the logger.requestFields
configuration:
[2017-09-01 11:12:46.994] [INFO ] [TSED] - {
"status": 200,
"reqId": 1,
"method": "GET",
"url": "/api-doc/swagger.json",
"duration": 92,
"headers": {
"host": "0.0.0.0:8001",
"connection": "keep-alive",
"upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"accept-encoding": "gzip, deflate",
"accept-language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4"
},
"body": {},
"query": {},
"customData": "test"
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
You can configure this output from configuration:
import {Configuration} from "@tsed/common";
@Configuration({
logger: {
requestFields: ["reqId", "method", "url", "headers", "body", "query","params", "duration"]
}
})
export class Server {
}
2
3
4
5
6
7
8
9
10
or you can override the middleware with .
Example:
import {Context, OverrideProvider, PlatformLogMiddleware} from "@tsed/common";
@OverrideProvider(PlatformLogMiddleware)
export class CustomPlatformLogMiddleware extends PlatformLogMiddleware {
public use(@Context() ctx: Context) {
// do something
return super.use(ctx); // required
}
protected requestToObject(ctx: Context) {
const {request} = ctx;
// NOTE: request => PlatformRequest. To get Express.Request use ctx.getRequest<Express.Request>();
return {
method: request.method,
url: request.url,
headers: request.headers,
body: request.body,
query: request.query,
params: request.params
};
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Shutdown logger
Shutdown returns a Promise that will be resolved when @tsed/logger has closed all appenders and finished writing log events. Use this when your program exits to make sure all your logs are written to files, sockets are closed, etc.
import {$log} from "@tsed/logger";
$log
.shutdown()
.then(() => {
console.log("Complete")
});
2
3
4
5
6
7
# Get configuration
The configuration can be reused throughout your application in different ways.
- With dependency injection in Service, Controller, Middleware, Filter or Converter.
- With the decorators and .
# From service (DI)
import {Configuration, Injectable} from "@tsed/di";
@Injectable() // or Controller or Middleware
export class MyService {
constructor(@Configuration() configuration: Configuration) {}
}
2
3
4
5
6
# From decorators
Decorators and can be used in all classes including:
and accepts an expression as parameters to inspect the configuration object and return the value.
import {Constant, Value} from "@tsed/di";
import {Env} from "@tsed/core";
export class MyClass {
@Constant("env")
env: Env;
@Value("swagger.path")
swaggerPath: string;
$onInit() {
console.log(this.env);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
WARNING
returns an Object.freeze() value.
NOTE
The values for the decorated properties aren't available on constructor. Use $onInit() hook to use the value.
- Session & cookies
- Passport.js
- TypeORM
- Mongoose
- GraphQL
- Socket.io
- Swagger
- AJV
- Multer
- Serve static files
- Templating
- Throw HTTP Exceptions
- Customize 404
- AWS
- Jest
- Seq
- Controllers
- Providers
- Model
- Converters
- Middlewares
- Pipes
- Interceptors
- Authentication
- Hooks
- Injection scopes
- Custom providers
- Custom endpoint decorator
- Testing