DEV Community

Cover image for How to solve REST API routing problem with decorators?
Rahul Sharma
Rahul Sharma

Posted on • Edited on

7 1

How to solve REST API routing problem with decorators?

Decorators Introduction:

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

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).

The expression for the method decorator will be called as a function at runtime, with the following three arguments:

  • Either the constructor function of the class for a static member, or the prototype of the class for an instance member.
  • The name of the member.
  • The Property Descriptor for the member.

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

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


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.

Prerequisite:
  • Make sure you have installed the latest Node.js
  • Basic knowledge of javascript, typescript, node.js, and express.js
  • Code editor (vs code)

Step 1:

Open the terminal and run the following command

mkdir decorator-routes //create directory
cd decorator-routes
Enter fullscreen mode Exit fullscreen mode

Step 2:

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

npm init
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

Step 3:

Install dependencies using the following command.

npm i express --save
npm i typescript @types/express -D
Enter fullscreen mode Exit fullscreen mode

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
{
  ...
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "@types/express": "^4.17.13",
    "typescript": "^4.6.2"
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 4:

Add tsc and start scripts in the package.json

package.json
{
  ...
  "scripts": {
    "prestart": "tsc",
    "start": "node ./dist/server.js"
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode

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"
    ]
}
Enter fullscreen mode Exit fullscreen mode

Step: 6

  • Create a src the directory in your root folder
  • Create subdirectories(controllers, decorators) inside src. How to make REST API’s using Node.js, Express.js & Typescript Decorators

Step: 7

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

src/decorators/routes.decorator.ts
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;
Enter fullscreen mode Exit fullscreen mode
Create a index.ts inside src/decorators folder, and add below code in it:
src/decorators/index.ts
export * from './routes.decorator';
Enter fullscreen mode Exit fullscreen mode
Create a Users.controller.ts inside src/controllers folder, and add below code in it:
src/controllers/Users.controller.ts
import { Request, Response } from 'express';
import routes from '../decorators/routes.decorator';
export class Users {
    @routes({
        path: '/users',
        method: 'get'
    })
    getUsers(req: Request, res: Response) {
        res.send('Typescript Decorators are awesome !!!');
    }
}
Enter fullscreen mode Exit fullscreen mode
Create a index.ts inside src/controllers folder, and add below code in it:
src/controllers/index.ts
export * from ./Users.controller;
Enter fullscreen mode Exit fullscreen mode
Create a server.ts inside src folder, and add below code in it:
src/server.ts
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');
});
Enter fullscreen mode Exit fullscreen mode

Step: 8

Run the following command from the terminal

npm run start
Enter fullscreen mode Exit fullscreen mode

Open browser or any REST client and go to

http://localhost:3000/users
Enter fullscreen mode Exit fullscreen mode

Live Example: Demo

Got any questions or additional? please leave a comment.

Thank you for reading 😊


Must Read If you haven't

Catch me on

Youtube Github LinkedIn Medium Stackblitz Hashnode HackerNoon

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (1)

Collapse
 
marytedesco profile image
MaryTedesco
Comment hidden by post author

Some comments have been hidden by the post's author - find out more

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more