How to make REST API’s using Node.js, Express.js & Typescript Decorators | Part-1

Rahul Sharma (DevsMitra)
4 min readJan 9, 2020

Decorators Introduction:

A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter.

REST API’s using Node.js, Express.js & Typescript Decorators | 6Questions

We’ll be using Method Decorators to develop routesDecorator.

Method Decorators:

A Method Decorator is declared just before a method declaration. The decorator is applied to the Property Descriptor for the method and can be used to observe, modify, or replace a method definition. A method decorator cannot be used in a declaration file, on overload, or in any other ambient context (such as in a declare class).

Definition referred from typescript official site, Check more details about Method Decorators here

Decorators use the form @expression, where expression must evaluate to a function that will be called at run-time with information about the decorated declaration.

NOTE: Decorators are an experimental feature that may change in future releases.

Prerequisite:

  1. Make sure you have installed the latest Node.js ( Download link )
  2. Basic knowledge of javascript, typescript, node.js, and express.js
  3. Code editor (vs code)

Step 1:

Open the terminal and run the following command

mkdir decorator-routes //create directory
cd decorator-routes

Step 2:

Initialize the Node.js project using the following command from the terminal

npm init

Your package.json will look like this.

package.json:

{
"name": "decorator-routes",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}

Step 3:

Install dependencies using the following command.

npm i express --savenpm i typescript @types/express -D

Note: -D marks things as “used for development” while --save (which is the default, and therefore optional) means “used by the program when it is deployed”.

@types packages provide type information to TypeScript, but they are not used when your code is running/deployed.

Tip: npm i is a shortcut for npm install, and -D is a short for --save-dev.

package.json

{
"name": "decorator-routes",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"@types/express": "^4.17.2",
"typescript": "^3.7.3"

}
}

Step 4:

Put tsc and start scripts in the package.json

package.json

{
"name": "decorator-routes",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"tsc":"tsc",
"start":"node ./dist/server.js"

},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"@types/express": "^4.17.2",
"typescript": "^3.7.3"
}
}

Step 5: Create tsconfing.json and enable experimentalDecorators

Create a text file called tsconfig.json in your root folder, put below code in it:

To enable experimental support for decorators, you must enable the experimentalDecorators in your tsconfig.json

tsconfig.json

{
"compilerOptions": {
"module": "commonjs",
"lib": ["ES2018"],
"target": "es2017",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outDir": "dist",
"experimentalDecorators": true,
"sourceMap": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}

Step: 6

Create a src the directory in your root folder and create subdirectories(controllers, decorators) inside src.

Express.js project structure | 6Questions

Step: 7

Create a text file called routes.decorator.ts inside src/decorators folder, put below code in it:

import { Router } from 'express';export const appRouter = Router();interface IOptions {
path: string;
method: 'get'| 'post'| 'put' | 'delete' ;
middlewares?: any[],
}
function routesDecorator(options: IOptions) {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
(appRouter as any)[options.method](options.path, target[propertyKey]);
};
}
export default routesDecorator;

Create a text file called index.ts inside src/decorators folder, put below code in it:

export * from './routes.decorator';

Create a text file called Users.controller.ts inside src/controllers folder, put below code in it:

import { Request, Response } from 'express';
import routesDecorator from '../decorators/routes.decorator';
export class Users {
@routesDecorator({
path: '/users',
method: 'get'
})
getUsers(req: Request, res: Response) {
res.send('Typescript Decorators are awesome !!!');
}
}

Create a text file called index.ts inside src/controllers folder, put below code in it:

export * from ‘./Users.controller’;

Create a text file called server.ts inside src folder, put below code in it:

import * as express from 'express';const app = express();import './controllers';
import { appRouter } from './decorators/routes.decorator';
app.use(appRouter);app.listen(3000,()=>{
console.log('Server is running on port 3000');
});

Step: 8

Run the following command from the terminal

npm run tsc
npm run start

Step: 9

Open browser or any REST client and go to

http://localhost:3000/users

Got any questions or additional? please leave a comment.

Thank you for reading :)

Live Example:

rest-apis-using-node-js-express-js-typescript-decorators — StackBlitz

Github repository:

--

--

Rahul Sharma (DevsMitra)

I’m a technology enthusiast who does web development. Passionate to contribute to open-source projects and make cool products.