using assert with ts-node in mocha test

I created a mocha test in a test.ts

I created a mocha test in a test.ts

import * as assert from "assert";

describe('it', () => {
it('should ', done => {
assert.strictEqual(true, false);
done();
});
});

My package.jsons devDependencies:

"devDependencies": {
"@types/mocha": "^5.2.5",
"@types/node": "^10.12.18",
"mocha": "^5.2.0",
"ts-node": "^8.0.1",
"typescript": "^3.2.4"
}

tsconfig.json:

{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"sourceMap": true,
"declaration": true,
"outDir": "./dist",
"strict": true,
"types": ["mocha"]
}
}

When running ts-node, I get this error:

error TS2307: Cannot find module 'assert'.

My commandline call is this:

./node_modules/mocha/bin/mocha -r ts-node/register test/test.ts

Regular tsc throws no errors.

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

Building a Node.js App with TypeScript Tutorial

Building a Node.js App with TypeScript Tutorial

Learn to build a simple blog server using Node.js and TypeScript.Set up your development environment. To build applications using TypeScript, make sure you have Node.js installed on your system. Create the project structure. Configuring TypeScript. Add ESLint

As dynamically typed languages became prominent during the last decade, typeless (or should I say lawless?) programming became the norm for the backend as well as the frontend.

Many people believe the simplicity of “just writing” code is efficient for providing a proof of concept or prototyping applications.

However, as those applications grow, the typeless code used to build them often becomes incredibly convoluted and more difficult (some would say impossible) to manage.

In the worst cases, developers end up resorting to testing and prayer in the hopes that simple operations like renaming a function won’t break the whole complex system. However, developers can build their code from day one to make their codebase readable at scale.

TypeScript to the rescue

The key to making a large (or even small!) codebase readable is to keep track of all the data types flowing through the app.

To help developers with this, TypeScript provided a typed superset of plain old JavaScript. This means that a regular JavaScript developer’s existing knowledge applies to TypeScript.

There are other efficient ways developers can use their knowledge and code in new ways. Developers who use NodeJS can now recycle their frontend code for the backend, and vice versa.

Additionally, the introduction of static typing to JavaScript allows developers to reuse some of that old Java/C# knowledge to help maintain their NodeJS codebases.

Today’s Project: A Simple Blogging Engine

In this tutorial, we need a new backend for a blogging engine. This app will contain a list of blog posts, each with a title, content, and author.

The authors will be able to register and log in using the session-in-cookies approach. Okta will manage the users, and all blog posts will be saved in memory.

Documentation for the backend will be exposed as a Swagger specification generated from TypeScript typings for classes and methods.

Dependencies for the NodeJS Typescript Sample App
  • NestJS to bootstrap the server
  • Swagger to define the server docs
  • Okta for user management and authentication
  • NodeJS
  • validate-class npm library for input validation
  • nodemon to auto-restart the server on every change
Initialize

Create an empty directory bloggeurcd into it, and type npm init there. After pressing the ENTER key a few times, a NodeJS project will initiate.

TypeScript config JSON

As TypeScript is very configurable, most TypeScript projects contain a configuration to select the language features it should use.

Create a tsconfig.json in the root of your project:

{
  "compilerOptions": {
    "target": "es2015",
    "lib": ["es2015"],
    "types": ["reflect-metadata", "node"],
    "module": "commonjs",
    "moduleResolution": "node",
    "experimentalDecorators":true,
    "emitDecoratorMetadata": true,
    "sourceMap": true,
    "declaration": false,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  },
  "exclude": [
    "node_modules"
  ]
}

Add all the dependencies
npm install @nestjs/[email protected] @nestjs/[email protected] @nestjs/[email protected] @nestjs/[email protected] @okta/[email protected] @okta/[email protected] @types/[email protected] @types/[email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] @types/[email protected]

Most of these dependencies should be straightforward, but a few of them require a bit of explaining:

  • NestJS to bootstrap the server
  • Swagger to define the server docs
  • Okta for user management and authentication
  • NodeJS
  • validate-class npm library for input validation
  • nodemon to auto-restart the server on every change
Create the server startup

Create a point of entry (server.js) to set up the TypeScript context and run the project using a regular node command:

require('reflect-metadata'); // used to extract static data types at runtime, needed for automatic API docs generation
require('ts-node/register'); // used to transpile typescript code dynamically at runtime
require('dotenv/config'); // if it exists, loads .env file into process.env
require('./src/server.ts'); // entry into the TypeScript realm

Also, create a src directory, for the source code.

Create a NestJS module

Both Node.js and .NET heavily inspired NestJS. So it’s not surprising that every NestJS app is just a bunch of modules.

Create an (almost) empty NestJS module src/application.module.ts. It only contains a cookie-parser middleware, and will contain all of the application’s (currently non-existent) controllers:

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import cookieParser from 'cookie-parser';
import glob from 'glob';

const controllers =
  glob.sync('*.module/*-controller.ts', { cwd: __dirname, absolute: true }) // go through all the modules containing controllers
    .map(require) // require every one of them
    .map(imported => imported.default);
    // and return each one's default export (which is expected to be a NestJS controller class)

@Module({
  controllers
})
export class ApplicationModule implements NestModule {
  configure(consumer: MiddlewareConsumer): MiddlewareConsumer | void {
    consumer.apply(cookieParser()).forRoutes('/');
  }
}

Bootstrap the NestJS server

Create src/server.ts to spin up the server:

import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ApplicationModule } from './application.module';

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule); // Application module created in the step before
  app.useGlobalPipes(new ValidationPipe()); // Makes use of class-validate to sanitize data entering the API

  // Creates Swagger documentation and OpenAPI console on the root path (http://localhost:3000)
  const swaggerOptions = new DocumentBuilder().build();
  const document = SwaggerModule.createDocument(app, swaggerOptions);
  SwaggerModule.setup('/', app, document);

  await app.listen(3000);
}

bootstrap().catch(console.error);

Test Run your Application

By running npm start or node server.js, your server should be started on port 3000.

But be sure to run it using nodemon to allow for automatic restarts:

npx nodemon server.js --ext ts

After running the server, direct your browser to [http://localhost:3000](http://localhost:3000 "http://localhost:3000"). An API console should open with the message “No operations defined in spec”.

Now let’s create a few operations!

Create the [BlogPost](https://developer.okta.com/blog/2019/09/19/nodejs-typescript#create-the-blogpost-module "BlogPost") module

Create a directory src/blog-post.module. In it, create src/blog-post.module/blog-post-controller.ts to contain all the posts:

import { Controller, Get } from '@nestjs/common';
import { ApiModelProperty, ApiResponse } from '@nestjs/swagger';

export class BlogPost {
  @ApiModelProperty() // used to generate Swagger documentation that `BlogPost` model contains id of type number
  id: number;

  @ApiModelProperty()
  authorId: string;

  @ApiModelProperty()
  title: string;

  @ApiModelProperty()
  content: string;
}

export const blogPosts = [{
  id: 1,
  authorId: 'xxx',
  title: 'Build a NodeJS App with Typescript',
  content: 'Whats wrong with Javascript?'
}, {
  id: 2,
  authorId: 'yyy',
  title: 'Don\'t build a NodeJS App with Typescript',
  content: 'Whats wrong with Typescript?'
}];

@Controller('blog-posts')
export default class BlogPostController {
  @Get() // registers a `blog-posts` GET method on the API
  @ApiResponse({ type: BlogPost, status: 200, isArray: true }) // for Swagger documentation: API returns an array of BlogPost models
  findAll(): Array<BlogPost> {
    return blogPosts;
  }
}

Refresh browser page [http://localhost:3000](http://localhost:3000 "http://localhost:3000"), and execute GET blog-posts in the API console.

Create the Authentication module

Create a directory for authentication module: src/auth.module.

To help offload the burden of authentication, you will use Okta for authentication, authorization, and user account management.

Create a forever-free Okta account and application

Click here to create an account.

Once you’re logged into your Okta dashboard, click Applications in the menu and click Add Application. From the wizard, choose Service and click Next.

On the Application Settings screen, name the application (I’ve named mine “the-blog-backend”).

After an application has been successfully created, copy the client ID and client secret into the .env file in the root of the project.

The dotenv (.env) file stores your development environment variables. They switch your application’s code from development to production or reference accounts on 3rd-party providers.

This file is consumed by the require('dotenv/config') statement in your server.js file. It copies the values from .env file into the process.env global variable. Create an empty .env file in the root directory of the project.

The application needs an API token to communicate with Okta. In the Okta dashboard, click on API, then Tokens, and on the new page click Create Token. Copy its value to the .env file as well.

You’ll also put your Okta account’s domain in the .env file. It’s the hostname of the Okta dashboard you’re currently using, but without the -admin part. It should look something like dev-xxxxxx.okta.com.

After writing all those values, your .env file should look something like this:

OKTA_CLIENT_ID={yourClientId}
OKTA_CLIENT_SECRET={yourClientSecret}
OKTA_APP_TOKEN={yourAppToken}
OKTA_DOMAIN=https://{yourOktaDomain}

All these values are needed for the next section.

Integrate Authentication with Okta APIs

The Okta APIs you need for this project are the authentication API and the user management API.

Both are nicely exposed through npm packages @okta/okta-auth-js and @okta/okta-sdk-nodejs.

Create src/auth-module/okta-client.ts file to integrate with those services:

import { Client as OktaClient } from '@okta/okta-sdk-nodejs';
import OktaAuth from '@okta/okta-auth-js';

const { OKTA_DOMAIN, OKTA_APP_TOKEN } = process.env; // provided by .env file

const oktaClient = new OktaClient({
  orgUrl: OKTA_DOMAIN,
  token: OKTA_APP_TOKEN,
});

const oktaAuthClient = new OktaAuth({
  issuer: `${OKTA_DOMAIN}/oauth2/default`,
});

export interface IRegisterData {
  firstName: string;
  lastName: string;
  email: string;
  password: string;
}

export interface IRegistrationResponse {
  id: string;
}

export async function register(registerData: IRegisterData): Promise<IRegistrationResponse> {
  const { email, firstName, lastName, password } = registerData;
  const createdUser = await oktaClient.createUser({
    profile: { email, login: email, firstName, lastName },
    credentials: { password : { value: password } }
  });

  return createdUser;
}

export interface ILoginData {
  email: string;
  password: string;
}

export interface ISession {
  sessionId: string;
  userId: string;
  userEmail: string;
}

export async function sessionLogin(loginData: ILoginData): Promise<ISession> {
  const { email: username, password } = loginData;
  const { sessionToken } = await oktaAuthClient.signIn({ username, password });

  const session = await oktaClient.createSession({ sessionToken });
  const { login, id, userId } = session;

  return { sessionId: id, userEmail: login, userId };
}

export async function getSessionBySessionId(sessionId: string): Promise<ISession> {
  const session = await oktaClient.getSession(sessionId);
  const { login, id, userId } = session;

  return { sessionId: id, userEmail: login, userId };
}

export async function getUserById(id: string) {
  const { profile: { firstName, lastName, email } } = await oktaClient.getUser(id);
  return { id, firstName, lastName, email };
}

You have now exposed the functions to register a user with Okta, generate a session ID using email and password, and fetch a user by their ID.

That’s all you need for user management and authentication for this project.

Create a Login Endpoint

To allow for authentication, you need a login endpoint. Create a src/auth.module/auth-controller.ts file:

import { Body, Controller, Post, Req, UnauthorizedException } from '@nestjs/common';
import { ApiModelProperty, ApiResponse } from '@nestjs/swagger';
import { sessionLogin } from './okta-client';
import { Request } from 'express';

/*
 DTO is short for Data Transfer Object
 DTO is an object that carries data between processes
 In the context of web apps, it's used to document type of data to be transferred between backend and frontend
 */
export class LoginDto {
  @ApiModelProperty()
  email: string;

  @ApiModelProperty()
  password: string;
}

export class LoginResponseDto {
  @ApiModelProperty()
  sessionId: string;

  @ApiModelProperty()
  userEmail: string;

  @ApiModelProperty()
  userId: string
}

@Controller('login')
export default class AuthController {
  @Post()
  @ApiResponse({ type: LoginResponseDto, status: 201 })
  async login(@Body() data: LoginDto, @Req() request: Request): Promise<LoginResponseDto> {
    const { email, password } = data;
    try {
      const session = await sessionLogin({ email, password });
      request.res.cookie('sessionId', session.sessionId);
      return session;
    } catch (e) {
      console.log('login error', e);
      throw new UnauthorizedException('Invalid email or password');
    }
  }
}

You can now refresh the Swagger page at [http://localhost:3000](http://localhost:3000 "http://localhost:3000") to try out the new login endpoint.

We currently have no way to register a user through the server, so you can use Okta’s dashboard to create one and then execute a login endpoint with the corresponding email and password.

Create endpoints to create and fetch users

Having said that, let’s create endpoints for user creation and fetching.

Create src/user.module file and in it, create a src/user.module/user-controller.ts file:

import { Body, Controller, Get, NotFoundException, Param, Post, Req } from '@nestjs/common';
import { ApiModelProperty, ApiResponse } from '@nestjs/swagger';

import { getUserById, register, sessionLogin } from '../auth.module/okta-client';
import { IsEmail, IsNotEmpty } from 'class-validator';
import { Request } from 'express';

export class User {
  @ApiModelProperty()
  id: string;

  @ApiModelProperty()
  email: string;

  @ApiModelProperty()
  firstName: string;

  @ApiModelProperty()
  lastName: string;
}

export class UserRegisterDto {
  @ApiModelProperty()
  @IsEmail()
  email: string;

  @ApiModelProperty()
  @IsNotEmpty()
  password: string;

  @ApiModelProperty()
  @IsNotEmpty()
  firstName: string;

  @ApiModelProperty()
  @IsNotEmpty()
  lastName: string;
}

@Controller('users')
export default class UserController {
  @ApiResponse({ type: User, status: 201 })
  @Post()
  async create(@Body() userData: UserRegisterDto, @Req() request: Request): Promise<User> {
    const { email, password, firstName, lastName } = userData;
    const { id } = await register({ email, password, firstName, lastName });
    const { sessionId } = await sessionLogin({ email, password });
    request.res.cookie('sessionId', sessionId);

    return { id, email, firstName, lastName };
  }

  @ApiResponse({ type: User, status: 200 })
  @Get(':id')
  async find(@Param('id') id: string): Promise<User> {
    try {
      const user = await getUserById(id);
      return user;
    } catch (e) {
      console.error('could not find user', id, e);
      throw new NotFoundException('No such user');
    }
  }
}

Everything is pretty much the same here except for the @IsEmail() and @IsNotEmpty() validators.

Those prevent a request from being executed if data sent to the server does not contain a valid email and non-empty first and last name and password.

You can try out those validators by refreshing [http://localhost:3000](http://localhost:3000 "http://localhost:3000") page and executing register endpoint with some faulty data.

Secure the API

We need two more things for a secure API: authentication middleware to identify a logged-in user and an is-authenticated guard to protect non-public endpoints from anonymous access.

Create a src/auth.module/auth-middleware.ts file:

import { NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
import { getSessionBySessionId } from './okta-client';

export class AuthMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: Function) {
    const { sessionId } = req.cookies;
    if (!sessionId) {
      return next();
    }

    try {
      req['auth'] = await getSessionBySessionId(sessionId);
    } catch (e) {
      console.log('session fetching failed', e);
    }
    next();
  }
}

This middleware extracts sessionId from cookies and attaches session info to the auth key of the request object.

To use the created middleware, apply it to the Application module. src/application.module.ts should look like this after the change:

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import cookieParser from 'cookie-parser';
import glob from 'glob';

import { AuthMiddleware } from './auth.module/auth-middleware';

const controllers =
  glob.sync('*.module/*-controller.ts', { cwd: __dirname, absolute: true })
    .map(require)
    .map(imported => imported.default);

@Module({
  controllers
})
export class ApplicationModule implements NestModule {
  configure(consumer: MiddlewareConsumer): MiddlewareConsumer | void {
    consumer.apply(cookieParser(), AuthMiddleware).forRoutes('/');
  }
}

Next is the authentication guard. Create a src/auth.module/is-authenticated-guard.ts file:

import { CanActivate, ExecutionContext } from '@nestjs/common';

export class IsAuthenticatedGuard implements CanActivate {
  canActivate(context: ExecutionContext) {
    const request = context.switchToHttp().getRequest();
    const { auth } = request;
    return !!auth;
  }
}

Now we’re finally ready to create a blog post!

Create a blog post

To allow blog post creation, let’s expand our BlogPost controller to add a create() method. The method should be secured against unauthenticated usage and also modified to use userId extracted from the user’s session.

This is what the src/blog-post.module/blog-post-controller.ts file looks like after adding the create() method:

import { Body, Controller, Get, NotFoundException, Param, Post, Req, UseGuards } from '@nestjs/common';
import { ApiModelProperty, ApiResponse } from '@nestjs/swagger';
import { IsAuthenticatedGuard } from '../auth.module/is-authenticated-guard';
import { IsNotEmpty } from 'class-validator';
import { getUserById } from '../auth.module/okta-client';
import { User } from '../user.module/user-controller';

export class BlogPost {
  @ApiModelProperty()
  id: number;

  @ApiModelProperty()
  authorId: string;

  @ApiModelProperty()
  title: string;

  @ApiModelProperty()
  content: string;
}

export class BlogPostDto {
  @ApiModelProperty()
  @IsNotEmpty()
  title: string;

  @ApiModelProperty()
  @IsNotEmpty()
  content: string;
}

// you also don't need those dummy blog posts because they can be created through API now
export const blogPosts = new Array<BlogPost>();

@Controller('blog-posts')
export default class BlogPostController {
  @Get()
  @ApiResponse({ type: BlogPost, status: 200, isArray: true })
  findAll(): Array<BlogPost> {
    return blogPosts;
  }

  @Post()
  @ApiResponse({ type: BlogPost, status: 201 })
  @UseGuards(IsAuthenticatedGuard)
  create(@Body() blogPostDto: BlogPostDto, @Req() req): BlogPost {
    const { content, title } = blogPostDto;
    const id = blogPosts.length + 1;
    const { userId } = req['auth'];

    const newBlogPost: BlogPost = { id, title, content, authorId: userId };
    blogPosts.push(newBlogPost);

    return newBlogPost;
  }

  @Get(':id/author')
  async findAuthor(@Param('id') blogPostId: string): Promise<User> {
    const blogPost = blogPosts.filter(post => post.id.toString() === blogPostId)[0];
    if (!blogPost) {
      throw new NotFoundException('No such blog post');
    }
    return await getUserById(blogPost.authorId);
  }
}

After refreshing that [http://localhost:3000](http://localhost:3000 "http://localhost:3000") page again, you should finally be able to create blog posts (but only after a successful login).

Good job!

Congratulations. You have finished a small blogging engine using NodeJS and TypeScript.

You leveraged TypeScript’s typing system to both implement and document a simple REST API.

Notice how API documentation and implementation are held together rather than being written apart? That helps keep the docs and implementation in sync as the API evolves.

Recommended Reading

How to Role-Based Access Control in a Node.js application

How to Build Node.js Modules with Rust

Node.js Tutorial for Beginners in 2020

How To Build a Node.js Application with TypeScript and Docker

How To Build a Node.js Application with TypeScript and Docker

How To Build a Node.js Application with TypeScript and Docker - In this article, we will see how to build a Node.js, TypeScript Application and deploy it to server with Docker.

If you are new to typescript, watch this tutorial which covers the basics of TypeScript.

Application Setup

Firstly, you need to install typescript in your machine. Run the following command, this will install typescript globally in your machine.

npm install -g typescript 

Create a directory and initialize the node.js application with the command.

npm init --yes

After that, you need to create a configuration file for typescript which compiles the typescript into javascript.

tsc --init

it will create a configuration file called tsconfig.json which contains the TypeScript configuration for the application.


You may also like:Docker for Node.js Projects From a Docker Captain


Configuring TypeScript

Further, the configuration file contains the compiler options which can be configured. important options are,

  • target – it can be either ES6 or ES5, based on the options, TypeScript compiles the code either to ES6 or ES5.
  • outDir – it specifies the directory where the compiled code will be stored.
  • rootDir – it specifies directory on which the typescript code will be.
  • moduleResolution – specifies the module resolution strategy

Once, it is configured. we need to install few dependencies to setup and run the typescript on express application.

Install the following dependencies using the command

npm i -D typescript ts-node @types/node @types/express

  • ts-node – it is a package for using TypeScript with Node.js. we can run the application using ts-node app.ts
  • @types/node – it defines the custom types for Node.js in typescript
  • @types/express – it defines the custom types for express application in typescript

After that, create a scripts in package.json to compile and run the application.

"scripts": {
    "dev": "ts-node src/app.ts",
    "start": "ts-node dist/app.js",
    "build": "tsc -p ."
  }

Building Express Application with TypeScript
Once TypeScript configuration is done, we can build the Express application using TypeScript.

Create a directory called src which contains the TypeScript files and add the app.ts file in that.

import express,{ Application,Request,Response,NextFunction } from 'express';
import bodyParser from 'body-parser';

const app : Application = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


app.get('/',(req:Request,res : Response ) => {

    res.send('TS App is Running')
})

const PORT = process.env.PORT;


app.listen(PORT,() => {
    console.log(`server is running on PORT ${PORT}`)
})

one of the advantages of using TypeScript is defining the Type for the variable(Static Checking).

Here Express instance will be of type Application, Therefore, variable must be of type Application. same goes for Request,Response and Next Function(Middleware).

After that, we need to write a logic to connect the database. create a file called connect.ts and add the following code,

import mongoose from 'mongoose';

type DBInput = {
    db : string;
}

export default({db} : DBInput) => {
    
    const connect = () => {
        mongoose
            .connect(db,{ useNewUrlParser : true })
            .then(() => {
                return console.info(`Successfully connected to ${db}`);
            })
            .catch((err) => {
                console.error(`Error connecting to database :`,err);

                return process.exit(1);
            })
    };

    connect();

    mongoose.connection.on('disconnected',connect);
}

DBInput is a type which takes variable db as a string. we use it connect with mongodb.

After that, create directories Controllers,Models ,Routes and types in the root directory.

  • Controllers – contains all the business logic for the application
  • Models – contains all the Database Schema of Mongoose.
  • Routes – will have all the API Routes for the application
  • Types – will contains Custom types used in the Application
    create a file User.mode.ts in Models Directory and add the following code,
import mongoose, { Schema,Document } from 'mongoose';

 export interface IUser extends Document {
     email : String;
     firstName : String;
     lastName : String;
 }

 const UserSchema : Schema = new Schema({
     email : {
         type : String,
         required : true,
         unique : true
     },
     firstName : {
         type : String,
         required : true
     },
     lastName : {
         type : String,
         required : true
     }
 });

 export default mongoose.model<IUser>('User',UserSchema);

Firstly, we define mongoose schema for user model and User Interface

In Controllers Directory, Create User.controller.ts file and add the following code

import User,{ IUser } from '../Models/User.model';

interface ICreateUserInput {
    email: IUser['email'];
    firstName: IUser['firstName'];
    lastName: IUser['lastName'];
}

async function CreateUser({
    email,
    firstName,
    lastName
  }: ICreateUserInput): Promise<IUser> {
    return User.create({
      email,
      firstName,
      lastName
    })
      .then((data: IUser) => {
        return data;
      })
      .catch((error: Error) => {
        throw error;
      });
  }
  
  export default {
    CreateUser
  };

After that, create a file index.ts in Routes directory and add the following code,

import { RoutesInput } from '../types/route';
import UserController from '../Controllers/User.controller';

export default ({ app } : RoutesInput) => {

    app.post('api/user',async(req,res) => {
        const user = await UserController.CreateUser({
            firstName: req.body.firstName,
            lastName: req.body.lastName,
            email: req.body.email
          });
      
          return res.send({ user });
    })
}

RoutesInput is a custom type which defines the Express Application Type.

create a file types.ts in types directory and add the code,

import { Application } from 'express';
export type RoutesInput = {
  app: Application;
};

update the** app.ts** with mongodb connection and routes of the application.

import express,{ Application,Request,Response,NextFunction } from 'express';
import "dotenv/config";
import bodyParser from 'body-parser';
import Routes from './Routes';
import Connect from './connect';

const app : Application = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


app.get('/',(req:Request,res : Response ) => {

    res.send('TS App is Running')
})

const PORT = process.env.PORT;
const db = 'mongodb://localhost:27017/test';


Connect({ db });
Routes({ app })

app.listen(PORT,() => {
    console.log(`server is running on PORT ${PORT}`)
})

To test the application, run the script npm run dev and visit the url http://localhost:4000

Docker Configuration

If you are new to docker, read about docker for node.js and docker configuration.

create a file Dockerfile in the root directory and add the following code.

FROM node:10

WORKDIR /usr/src/app

COPY package.json ./

RUN npm install

RUN npm install pm2 -g

RUN npm run build

COPY ./dist .

EXPOSE 4000

CMD ["pm2-runtime","app.js"]

Basically, we take the node base image and install all our dependency in the docker image container

After that, we install process manager called pm2 which is used mostly in all production applications. then we copy the compiled code from local to docker image.

Further, create a file docker-compose.yml in the root directory and add the following code.

version: "3"

services:
  app:
    container_name: app
    restart: always
    build: .
    environment: 
      - PORT=4000 
    ports: 
      - "4000:4000" 
    links: 
      - mongo
  mongo:
    container_name: mongo
    image: mongo
    ports:
      - "27017:27017" 

Docker compose combine multiple docker services and run it in a single container. Here, we combine MongoDB and Application images and run it container.

Docker Deployment and Running

Once, Dockerfile is added. run the following command,

docker-compose up

it will deploy the compiled code in docker image and run it in the container.

Complete Source code contains Building a Production – Ready Node.js App with TypeScript and Docker.

Originally published by ganeshmani009 at cloudnweb.dev

Learm More