Getting started

You can start your project from the getting started project boilerplate.

Installation from scratch

You can get the latest version of Ts.ED using the following npm command:

$ npm install --save-dev typescript @types/express
$ npm install --save express@4 @tsed/core @tsed/di @tsed/common
1
2

TIP

The following modules are also recommended:

$ npm install --save body-parser compression cookie-parser method-override
$ npm install --save-dev ts-node nodemon
1
2

WARNING

It's really import to keep the same version for all @tsed/* packages. To prevent errors, fix the version for each Ts.ED packages:

{
  "dependencies": {
    "@tsed/common": "5.0.7",
    "@tsed/di": "5.0.7",
    "@tsed/core": "5.0.7",
    "@tsed/swagger": "5.0.7",
    "@tsed/testing": "5.0.7"
  }
} 
1
2
3
4
5
6
7
8
9

WARNING

Ts.ED requires Node >= 8, Express >= 4, TypeScript >= 2.0 and the experimentalDecorators, emitDecoratorMetadata, types and lib compilation options in your tsconfig.json file.

{
  "compilerOptions": {
    "target": "es2016",
    "lib": ["es2016"],
    "typeRoots": [
      "./node_modules/@types"
    ],
    "module": "commonjs",
    "moduleResolution": "node",
    "experimentalDecorators":true,
    "emitDecoratorMetadata": true,
    "allowSyntheticDefaultImports": true
  },
  "exclude": [
    "node_modules"
  ]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Optional

You can copy this example of package.json to develop your application:

{
  "name": "test-ts-express-decorator",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "npm run tsc",
    "coverage": "npm run test-cov && npm run test-remap",
    "postinstall": "npm run build",
    "tslint": "tslint ./*.ts ./lib/*.ts",
    "test": "mocha --reporter spec --check-leaks --bail test/",
    "tsc": "tsc --project tsconfig.json",
    "tsc:w": "tsc -w",
    "start": "nodemon --watch '**/*.ts' --ignore 'node_modules/**/*' --exec ts-node src/index.ts"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@tsed/core": "4.0.0",
    "@tsed/common": "4.0.0",
    "body-parser": "^1.15.2",
    "compression": "^1.6.2",
    "cookie-parser": "^1.4.3",
    "express": "^4.14.0",
    "method-override": "^2.3.6"
  },
  "devDependencies": {
    "@types/express": "^4.0.37",
    "ts-node": "^3.3.0",
    "nodemon": "^1.11.0",
    "typescript": "^2.4.3"
  }
}
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
27
28
29
30
31
32
33

Then use the command npm install && npm start to start your server.

Quick start

Create your express server

Ts.ED provide a class to configure your Express application quickly. Just create a server.ts in your root project, declare a new Server class that extends ServerLoader.

import {ServerLoader, ServerSettings, GlobalAcceptMimesMiddleware} from "@tsed/common";
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const compress = require('compression');
const methodOverride = require('method-override');
const rootDir = __dirname;

@ServerSettings({
  rootDir,
  acceptMimes: ["application/json"]
})
export class Server extends ServerLoader {
  /**
   * This method let you configure the express middleware required by your application to works.
   * @returns {Server}
   */
  public $onMountingMiddlewares(): void|Promise<any> {
      this
        .use(GlobalAcceptMimesMiddleware)
        .use(cookieParser())
        .use(compress({}))
        .use(methodOverride())
        .use(bodyParser.json())
        .use(bodyParser.urlencoded({
          extended: true
        }));

      return null;
  }
}
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
27
28
29
30

By default ServerLoader load controllers in ${rootDir}/controllers and mount it to /rest endpoint.

To customize the server settings see Configuration page.

Finally create an index.ts file to bootstrap your server, on the same level of the Server.ts:

import {Server} from "./Server.ts"

new Server().start()
  .then(() => {
    console.log('Server started...');
  })
  .catch((err) => {
    console.error(err);
  })
1
2
3
4
5
6
7
8
9

You should have this tree directories:

.
├── src
│   ├── controllers
│   ├── services
│   ├── middlewares
│   ├── index.ts
│   └── Server.ts
└── package.json
1
2
3
4
5
6
7
8

TIP

By default ServerLoader load automatically Services, Controllers and Middlewares in a specific directories. This behavior can be change by editing the componentScan configuration.

Create your first controller

Create a new CalendarCtrl.ts in your controllers directory (by default root/controllers). All controllers declared with decorators is considered as an Express router. An Express router require a path (here, the path is /calendars) to expose an url on your server. More precisely, it's a part of path, and entire exposed url depend on the Server configuration (see Configuration) and the children controllers.

In this case, we haven't a dependencies and the root endpoint is set to /rest. So the controller's url will be http://host/rest/calendars.

import {Controller, Get} from "@tsed/common";

@Controller("/calendars")
export class CalendarCtrl {
  @Get()
  findAll(): string {
    return "This action returns all calendars";
  }
}
1
2
3
4
5
6
7
8
9

TIP

Decorators , , , , etc..., supports dynamic pathParams (eg: /:id) and RegExp like Express API.

See Controllers section for more details

WARNING

You have to configure engine rendering if you want to use the decorator .

To test your method, just run your server.ts and send a HTTP request on /rest/calendars/1.

Ready for More?

We’ve briefly introduced the most basic features of Ts.ED - the rest of this guide will cover them and other advanced features with much finer details, so make sure to read through it all!