Configuration

@@ServerSettings@@ let you to configure quickly your server via decorator. This decorator take your configuration and merge it with the default server configuration.

The default configuration is as follow:

{
  "rootDir": "path/to/root/project",
  "env": "development",
  "port": 8080,
  "debug": false,
  "httpsPort": 8000,
  "uploadDir": "${rootDir}/uploads",
  "mount": {
    "/rest": "${rootDir}/controllers/**/*.ts" // support ts with ts-node then fallback to js
  },
  "componentsScan": [
    "${rootDir}/middlewares/**/*.ts",
    "${rootDir}/services/**/*.ts",
    "${rootDir}/converters/**/*.ts"
  ],
  "routers": {
    "mergeParams": false,
    "strict": false,
    "caseSensitive": false
  }
}
1
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 follow:

// server.ts
import {ServerLoader, ServerSettings} from "@tsed/common";
import Path = require("path");

@ServerSettings({
   rootDir: Path.resolve(__dirname), //optional. By default it's equal to process.cwd()
   mount: {
     "/rest": "${rootDir}/controllers/current/**/*.js",
     "/rest/v1": [
        "${rootDir}/controllers/v1/users/*.js", 
        "${rootDir}/controllers/v1/groups/**/*.ts", // support ts entry
        "!${rootDir}/controllers/v1/groups/old/*.ts", // support ts entry
        MyController // support manual import
     ]
   }
})
export class Server extends ServerLoader {}

// app.ts
import * as Server from "./server";
new Server.start();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Ts.ED support ts-node. Ts extension will be replaced by a Js extension if ts-node isn't the runtime.

Options

HTTP & HTTPs server

Change address

It's possible to change the HTTP and HTTPS server address as follows:

import {ServerLoader, ServerSettings} from "@tsed/common";

@ServerSettings({
   httpPort: "127.0.0.1:8081",
   httpsPort: "127.0.0.2:8082",
})
export class Server extends ServerLoader {}
1
2
3
4
5
6
7

Random port

Random port assignment can be enable with the value 0. The port assignment will be delegate to the OS.

import {ServerLoader, ServerSettings} from "@tsed/common";

@ServerSettings({
   httpPort: "127.0.0.1:0",
   httpsPort: "127.0.0.2:0",
})
export class Server extends ServerLoader {}
1
2
3
4
5
6
7

Or:

import {ServerLoader, ServerSettings} from "@tsed/common";

@ServerSettings({
   httpPort: 0,
   httpsPort: 0,
})
export class Server extends ServerLoader {}
1
2
3
4
5
6
7

Disable HTTP

import {ServerLoader, ServerSettings} from "@tsed/common";

@ServerSettings({
   httpPort: false
})
export class Server extends ServerLoader {}
1
2
3
4
5
6

Disable HTTPS

import {ServerLoader, ServerSettings} from "@tsed/common";

@ServerSettings({
   httpsPort: false,
})
export class Server extends ServerLoader {}
1
2
3
4
5
6

HTTPs configuration

You see the example projet HTTPs

Logger

Default logger

Default logger use by Ts.ED is ts-log-debug.

Configuration

Some options is provided:

It's recommended to disable logRequest in production. Logger have a cost on the performance.

Request logger

For each Express.Request, a logger will be attached and can be used like here:

request.log.info({customData: "test"}) // parameter is optional
request.log.debug({customData: "test"})
request.log.warn({customData: "test"})
request.log.error({customData: "test"})
request.log.trace({customData: "test"})
1
2
3
4
5

A call with once of this method 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"
}
1
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 {ServerLoader, ServerSettings} from "@tsed/common";

@ServerSettings({
   logger: {
       requestFields: ["reqId", "method", "url", "headers", "body", "query","params", "duration"]
   }
})
export class Server extends ServerLoader {

}
1
2
3
4
5
6
7
8
9
10

or you can override the middleware with @@OverrideMiddleware@@.

Example:

import {ServerLoader, ServerSettings, OverrideMiddleware, LogIncomingRequestMiddleware, Res, Req} from "@tsed/common";

@OverrideMiddleware(LogIncomingRequestMiddleware)
export class CustomLogIncomingRequestMiddleware extends LogIncomingRequestMiddleware {
 
    public use(@Req() request: any, @Res() response: any) {
    
        // you can set a custom ID with another lib
        request.id = require('uuid').v4()
        
        return super.use(request, response); // required 
    }
    
    protected requestToObject(request) {
        return {
           reqId: request.id,
           method: request.method,
           url: request.originalUrl || request.url,
           duration: new Date().getTime() - request.tsedReqStart.getTime(),
           headers: request.headers,
           body: request.body,
           query: request.query,
           params: request.params
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

Shutdown logger

Shutdown return a Promise that will be resolved when ts-log-debug 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 "ts-log-debug";

$log
  .shutdown()
  .then(() => {
     console.log("Complete")
  }); 
1
2
3
4
5
6
7

Get configuration

The configuration can be reused throughout your application in different ways.

From service (DI)

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

@Service() // or Controller or Middleware
export class MyService {
  constructor(serverSettingsService: ServerSettingsService) {}
}
1
2
3
4
5
6

From decorators

Decorators @@Constant@@ and @@Value@@ can be used in all classes including:

@@Constant@@ and @@Value@@ accept 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);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

::: warning @@Constant@@ return an Object.freeze() value. :::

::: tip NOTE The values for the decorated properties aren't available on constructor. Use $onInit() hook to use the value. :::