Rest API In Node.js Using TypeScript And Fortjs

This article explains how to create a REST API using TypeScript and Fortjs.

Introduction

 
TypeScript is a modern scripting language that adds static typing to JavaScript, provides better IntelliSense and Debugging support, makes JS a structured language that results in faster development and much more. The popular JavaScript framework, Angular is an example of how TypeScript can be used to create a large project in less time. 
 
Now you must be wondering, can we use the power of TypeScript to create a nodejs server? 
 
The answer is yes.
 
In this article, we will use fortjs - a nodejs MVC framework that is fully compatible with TypeScript and next gen JavaScript - es6, es7.
 

Code

 
SetUp
 
Clone or download the TypeScript starter project of fortjs here.
 
After you have downloaded the project. Open the Console and move to project directory and do the following steps,
  1. run the command - npm install
  2. run the command - npm run start 
Open the URL - localhost:4000 in browser. You will see something like below.
 
Rest API In Node.js Using TypeScript And Fort.js
 
REST 
 
We are going to create a REST endpoint for entity user - which will perform the CRUD operations for user such as adding user, deleting user, getting user, and updating user.
 
According to to REST,
  1. Adding user - should be done using http method "POST"
  2. Deleting user - should be done using  http method "REMOVE"
  3. Getting user - should be done using http method  "GET"
  4. Updating user - should be done using http method "PUT"
For creating an endpoint, we need to create a Controller. You can read about controller here.
 
Create a file user_controller.ts inside the contollers folder and Copy the below code inside the file.
  1. import { Controller, textResult, DefaultWorker} from 'fortjs'    
  2. export class UserController extends Controller {    
  3.       @DefaultWorker()    
  4.       async default() {    
  5.           return textResult('you have successfully created a user controller');    
  6.       }    
  7. }    
In the above code,
  • We have created a class "UserController" which is extending another class Controller from fortjs.
  • We have created a method default which is returning some result by using the method textResult from fortjs. textResult return http response with content-type 'text/plain'.
  • We have used a decorator DefaultWorker from fortjs. A worker makes the method visible so that it can be called using http request (no worker means it just a function which is only available for this class). A default worker is a worker which add the route "/" for target method. Please take a look at worker doc - http://fortjs.info/tutorial/worker/
We have created a controller but it's still unknown by fortjs. In order to use this controller, we need to add this to routes. Open routes.ts inside root folder and add UserController to routes.
  1. import {DefaultController } from "./controllers/default_controller";  
  2. import { UserController } from "./controllers/user_controller";  
  3.   
  4. export const routes = [{  
  5.     path: "/default",  
  6.     controller: DefaultController  
  7. },{  
  8.     path: "/user",   
  9.     controller: UserController  
  10. }]  
You can see, we have added the path "/user" for UserController. It means when the url contains path "/user", UserController will be called. 
 
Now open the URL — localhost:4000/user. You can see the output which is returned from default method inside “UserController”. 
 
Rest API In Node.js Using TypeScript And Fort.js
 
Note: One thing to notice here is that the code looks very simple and nice. This is possible due to TypeScript and fortjs. And another fun is that you will get IntelliSense support and this all make life easy for a developer :).
 
Service
 
Before moving further, let’s write service code, which will help us to do CRUD operations.
 
Create a folder “models” and then a file “user.ts” inside the folder. Paste the below code inside the file.
  1. import { Length, Contains, IsIn, IsEmail } from "class-validator";  
  2.   
  3. export class User {  
  4.     id?: number;  
  5.   
  6.     @Length(5)  
  7.     password?: string;  
  8.   
  9.     @Length(5)  
  10.     name: string;  
  11.   
  12.     @IsIn(["male""female"])  
  13.     gender: string;  
  14.   
  15.     @Length(10, 100)  
  16.     address: string;  
  17.   
  18.     @IsEmail()  
  19.     emailId: string;  
  20.   
  21.     constructor(user: any) {  
  22.        this.id = Number(user.id);  
  23.        this.name = user.name;  
  24.        this.gender = user.gender;  
  25.        this.address = user.address;  
  26.        this.emailId = user.emailId;  
  27.        this.password = user.password;  
  28.     }  
  29. }  

I am using a npm plugin - "class-validator" to validate the model. This model “user” will be used by service and controller for transfer of data.

Create a folder “services” and then a file “ user_service.ts” inside the folder. Paste the below code inside the file.
  1. import { User } from "../models/user";  
  2.   
  3. interface IStore {  
  4.     users: User[];  
  5. }  
  6.   
  7. const store: IStore = {  
  8.     users: [{  
  9.         id: 1,  
  10.         name: "durgesh",  
  11.         address: "Bengaluru india",  
  12.         emailId: "durgesh@imail.com",  
  13.         gender: "male",  
  14.         password: "admin"  
  15.     }]  
  16. }  
  17.   
  18. export class UserService {
  19.   
  20.     getUsers() {  
  21.         return store.users;  
  22.     }
  23.   
  24.     addUser(user: User) {  
  25.         const lastUser = store.users[store.users.length - 1];  
  26.         user.id = lastUser == null ? 1 : lastUser.id + 1;  
  27.         store.users.push(user);  
  28.         return user;  
  29.     } 
  30.  
  31.     updateUser(user: User) {  
  32.         const existingUser = store.users.find(qry => qry.id === user.id);  
  33.         if (existingUser != null) {  
  34.             existingUser.name = user.name;  
  35.             existingUser.address = user.address;  
  36.             existingUser.gender = user.gender;  
  37.             existingUser.emailId = user.emailId;  
  38.             return true;  
  39.         }  
  40.         return false;  
  41.     }  

  42.     getUser(id: number) {  
  43.         return store.users.find(user => user.id === id);  
  44.     }  

  45.     removeUser(id: number) {  
  46.         const index = store.users.findIndex(user => user.id === id);  
  47.         store.users.splice(index, 1);  
  48.     }  
  49. }  
Above code contains a variable store, which contains collection of users and the method inside the service do operation like — add, update, delete, get on that store. Basically i have made a fake db and doing some crud operation.
 
GET
 
We are going to create an endpoint for getting user.
 
Let’s rename the default methods to “getUsers” which will return all users. Replace the code inside user_controller.ts by below code.
  1. import { Controller, jsonResult, DefaultWorker} from 'fortjs'  
  2.   
  3. export class UserController extends Controller {  
  4.     @DefaultWorker()  
  5.     async getUsers() {  
  6.        const service = new UserService();  
  7.        return jsonResult(service.getUsers());  
  8.     }  
  9. }  
As you can see, we are using DefaultWorker since it makes the method visible for http request and adds route "/" with http method "GET". So all these things using one decorator.
 
Now open the URL -  localhost:4000/user or you can use any http client such as postman.
 
Rest API In Node.js Using TypeScript And Fort.js
 
This method is only for http method — “GET” (since we are using DefaultWorker). If you will call this same endpoint for methods other than “GET”, you will get the status code 405.
 
POST
 
We need to create a method, which will add the users and only works for http method "POST". So now “UserController” looks like this:
  1. import { Controller, jsonResult, DefaultWorker, HTTP_METHOD, HTTP_STATUS_CODE, Worker, Route } from 'fortjs'  
  2.     
  3. export class UserController extends Controller {  
  4.     
  5.       @DefaultWorker()  
  6.       async getUsers() {  
  7.           const service = new UserService();  
  8.           return jsonResult(service.getUsers());  
  9.       }  
  10.          
  11.       @Worker([HTTP_METHOD.Post])  
  12.       @Route("/")  
  13.       async addUser() {  
  14.           const user = {  
  15.               name: this.body.name,  
  16.               gender: this.body.gender,  
  17.               address: this.body.address,  
  18.               emailId: this.body.emailId,  
  19.               password: this.body.password  
  20.           };  
  21.           const service = new UserService();  
  22.           const newUser = service.addUser(user);  
  23.           return jsonResult(newUser, HTTP_STATUS_CODE.Created);  
  24.       }  
  25. }  
In the above code,
  • We have created a method  "addUser" and added a decorator “Route” with parameter “/” which will add the route to method "addUser". This means that, method “addUser” will be called when url will be - localhost:4000/user/.
  • In order to make this method visible - we are using decorator “Worker”. The parameter “HTTP_METHOD.Post” makes the method only work when the request method will be POST.
  • The method addUser - takes data from body (post data) and add the user to store by calling service. After the successful addition, it returns the added user with http code - 201 (Resource Created).
In summary, we have created a method "addUser" that is used to add users. It only works for http method post & route "/".
 
You can test this by sending a post request to URL - "localhost:4000/user/" with user model value as body of the request. 
 
Rest API In Node.js Using TypeScript And Fort.js 
 
So we have successfully created the POST endpoint. But one thing to note here is that we are not doing any validations for the user. It might be that invalid data is supplied in post request.
 
We can write code inside “addUser” method to validate input data or write a separate method inside a controller (like validateUser) for validation.
 
Let's add the validation code.
  1. import { Controller, jsonResult, DefaultWorker, HTTP_METHOD, HTTP_STATUS_CODE, Worker, Route } from 'fortjs'  
  2. import { User } from '../models/user';  
  3. import { validate } from "class-validator";   
  4.   
  5. export class UserController extends Controller {  
  6.   
  7.     @DefaultWorker()  
  8.     async getUsers() {  
  9.         const service = new UserService();  
  10.         return jsonResult(service.getUsers());  
  11.     }  
  12.   
  13.     @Worker([HTTP_METHOD.Post])  
  14.     @Route("/")  
  15.     async addUser() {  
  16.         const user = {  
  17.             name: this.body.name,  
  18.             gender: this.body.gender,  
  19.             address: this.body.address,  
  20.             emailId: this.body.emailId,  
  21.             password: this.body.password  
  22.         }  
  23.         as User;  
  24.         const errorMsg = await this.validateUser(user);  
  25.         if (errorMsg == null) {  
  26.             const service = new UserService();  
  27.             const newUser = service.addUser(user);  
  28.             return jsonResult(newUser, HTTP_STATUS_CODE.Created);  
  29.         } else {  
  30.             return textResult(errMessage, HTTP_STATUS_CODE.BadRequest);  
  31.         }  
  32.     }  
  33.   
  34.   
  35.     async validateUser(user: User) {  
  36.         const errors = await validate('User', user);  
  37.         if (errors.length === 0) {  
  38.             return null;  
  39.         } else {  
  40.             const error = errors[0];  
  41.             const constraint = Object.keys(error.constraints)[0];  
  42.             const errMessage = error.constraints[constraint];  
  43.             return errMessage;  
  44.         }  
  45.     }  
  46. }  
Ok, so we have added the code for data validation. It will work as expected but dont you think the code looks little bit messy? 
 
FortJs provides components for validation and any extra work, so that your code looks much cleaner and easy to manage. 
 
FortJs says -  "A worker should only have code related to its main purpose and extra code should be written into components."
 
Let's implement the above validation using components. Since we are doing operations on worker, we need to use Guard component.
 
Guard 
 
Create a folder “guards” and a file “ model_user_guard.ts” inside the folder. Write the below code inside the file.
  1. import { Guard, HttpResult, MIME_TYPE, HTTP_STATUS_CODE, textResult } from "fortjs";  
  2. import { User } from "../models/user";  
  3. import { validate } from "class-validator";  
  4.   
  5. export class ModelUserGuard extends Guard {  
  6.     async check() {  
  7.         const user: User = new User(this.body);  
  8.         // here i am using a plugin to validate but you can write your own code too.   
  9.         const errors = await validate('User', user);  
  10.         if (errors.length === 0) {  // allow the request to pass through guard
  11.             // pass this to method, so that they dont need to parse again  
  12.             this.data.user = user;  
  13.             return null;  
  14.         }  
  15.         else {  // block the request
  16.             const error = errors[0];  
  17.             const constraint = Object.keys(error.constraints)[0];  
  18.             const errMessage = error.constraints[constraint];  
  19.             return textResult(errMessage, HTTP_STATUS_CODE.BadRequest);  
  20.         }  
  21.     }  
  22. }  
In the above code,
  • We are writing code inside the check method, which is part of guard lifecycle. We are validating the user inside it.
  • If user is valid then we are passing the user by using "data" property and returning null. Returning null means guard has allowed this request and the worker should be called.
  • If user is  not valid, we are returning an error message as text response with http code- "badrequest". We are returning textResult, which means the fortjs will consider this as response and worker won't be called.
Now we need to add this guard to method “addUser”.
  1. @Guards([ModelUserGuard])  
  2. @Worker([HTTP_METHOD.Post])  
  3. @Route("/")  
  4. async addUser() {  
  5.     const user: User = this.data.user;  
  6.     const service = new UserService();  
  7.     return jsonResult(service.addUser(user), HTTP_STATUS_CODE.Created);  
  8. }  
In the above code,
  • I have added the guard, “ModelUserGuard” using the decorator Guards .
  • With the guard in process, we don't need to parse the data from body anymore inside worker, we are reading it from this.data which we are passing from "ModelUserGuard".
  • The method “addUser” will be only called when Guard allow means if all data is valid.
You can see that our worker method looks very light after using component.
 
PUT
 
Now we need to create a method, which will update the user and will only work for http method — “PUT”.
 
Let’s add another method - “updateUser” with route “/” , guard — “ModelUserGuard” (for validation of user) and most important - worker with http method — “PUT” 
  1. @Worker([HTTP_METHOD.Put])  
  2. @Guards([ModelUserGuard])  
  3. @Route("/")  
  4. async updateUser() {  
  5.       const user: User = this.data.user;  
  6.       const service = new UserService();  
  7.       const userUpdated = service.updateUser(user);  
  8.       if (userUpdated === true) {  
  9.           return textResult("user updated");  
  10.       }  
  11.       else {  
  12.           return textResult("invalid user");  
  13.       }  
  14. }  
The above code is very simple. It is just calling the service code to update the user. But one important thing to notice is that we have reutilized the guard - “ModelUserGuard” and it makes our code very clean.
 
So we are done with,
  • GET - Returns all users
  • POST - add users
  • PUT - update user
Currently, the GET request returns all the users but what if we want to get only one user.
 
Let’s see, how to do it.
 
We have created a method “getUsers” for returning all users. Now let’s create another method “getUser”, which will return only one user. 
  1. @Worker([HTTP_METHOD.Get])  
  2. @Route("/{id}")  
  3. async getUser() {  
  4.       const userId = Number(this.param.id);  
  5.       const service = new UserService();  
  6.       const user = service.getUser(userId);  
  7.       if (user == null) {  
  8.           return textResult("invalid id");  
  9.       }  
  10.       return jsonResult(user);  
  11. }  
In the above code, we are using a placeholder in route. Now “getUser” will be called when url will be something like localhost:4000/user/1 The placeholder value is being consumed by using "this.param" .
 
REMOVE
 
We will use the same concept as get.
  1. @Worker([HTTP_METHOD.Delete])  
  2. @Route("/{id}")  
  3. async removeUser() {  
  4.       const userId = Number(this.param.id);  
  5.       const service = new UserService();  
  6.       const user = service.getUser(userId);  
  7.       if (user != null) {  
  8.           service.removeUser(userId);  
  9.           return textResult("user deleted");  
  10.       }  
  11.       else {  
  12.           return textResult("invalid user");  
  13.       }  
  14. }  
In the above code, we are just calling the service to remove the user after getting the id from route.
 
Finally, we have successfully created a REST endpoint for user.
 

Summary

 
TypeScript makes JavaScript development very faster with static typing & IntelliSense support. On the other hand, fortjs helps write clean and modular server side code. 
 
Reference 
  • http://fortjs.info/