Express Js Application Seed Project With TypeScript

Krishna KV
Technology Specialist
June 11, 2018
Rate this article
[Total: 2    Average: 5/5]
Views    553

Express Js is a Node Js based light-weight web application framework that helps to create quick and robust REST APIs and web applications. Setting up a TypeScript based Express Js application is much harder than creating a plain Javascript based Express Js application. But it’s always advisable to go with TypeScript for larger applications as its much easier to manage and maintain.

In this article, I’ll walk you through an Express Js application which is built with TypeScript. This application contains all basic aspects of a typical Express Js application and can be used as seed project to build your application on top of this.

Express Js TypeScript Seed

Clone or download the source code from this git repository and install all required node packages by running “yarn install” or “npm install” depending on the node package manager that you are using.

Build and packaging

package.json contains configuration and build management details. The below scripts in package.json enables to run the application during development time and package the application for deployment.

  • "start": "nodemon --watch src/**/*.ts --exec ts-node src/main.ts" – nodemon npm will start the express application and continuously monitors the source code for any changes and reloads the application / API while any typescript code is changed.
  • "build:prod": "npm run clean:dist && webpack --mode=production" – This invokes the webpack-cli  to generate a production build. This converts the typescript into javascript and bundles it into one single file named ejs-api.js along with the copy of package.json and yarn.lock (if yarn is used).  Supporting files that are required in addition to application code (TypeScript) can be copied to build folder by making necessary configuration changes in webpack.config.js.

A node package named  “copy-webpack-plugin”  is used to copy files to dist folder while we build the project for production.

express-api.ts -This file consists of the configuration that are required for the middlewares for the project.

Configuring base route

private configureBaseRoute() {
  this.app.use(function (req, res, next) {
    if (req.url === '/') { /* http://localhost:40401/x It will display the version and name */
      return res.json({
        name: '1.0.0',
        version: 'api',
      });
    } else {
      next();
    }
  });
this.app.use('/', this.router); /* The routing can be changed here as /api/v1 */
main.ts – This file contain the run method, which is the entry point for the Express application.

api.routing.ts

This file consists of router details of projects.

import { Router, Request, Response, NextFunction } from 'express';
import { Api } from '../helpers';

export class CustomerController {
    public static route = '/customer';
    public router: Router = Router();
    constructor() {
        this.router.get('/', this.getCustomer);
        this.router.get('/:id', this.getCustomerById);
    }
    public getCustomer(request: Request, response: Response, next: NextFunction) {
        return Api.ok(request, response, 'Customer info');
    }

    public getCustomerById(request: Request, response: Response, next: NextFunction) {
        return Api.ok(request, response, request.params['id']);

    }
}
helpers/api.ts – It is a wrapper for HttpResponse with the status codes and Json information. eg. Api.Ok, Api.ServerError,etc.
helper/logger.ts – It is a wrapper for winston logger, to log application errors, debug info etc.

Controller

It consists of routers such as customer, orders, billing, etc…


import { Router, Request, Response, NextFunction } from 'express';
import { Api } from '../helpers';
export class CustomerController {
  public static route = '/customer';
  public router: Router = Router();
  constructor() {
    this.router.get('/', this.getCustomer);
    this.router.get('/:id', this.getCustomerById);
  }
  public getCustomer(request: Request, response: Response, next: NextFunction) {
    return Api.ok(request, response, 'Customer info');
  }
  public getCustomerById(request: Request, response: Response, next: NextFunction) {
    return Api.ok(request, response, request.params['id']);
  }
}

To run the project.

In browser

http://localhost:40401/
http://localhost:40401/customer
http://localhost:40401/customer/1

Subscribe To Our Newsletter

Leave a comment