Skip to content

Node + Typescript + Express + Sequelize + Mongoose + Validations + Socket + CronJobs + Docker + Swagger + Service Based Template

License

Notifications You must be signed in to change notification settings

Thre4dripper/NodeTs-Express-Service-Based-Template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

96 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NodeTs-Express-Service-Based-Template

Node TypeScript Express Sequelize MySQL PostgresSQL Sqlite MariaDB MSSql DB2 Snowflake Oracle Mongoose MongoDB Validations Socket Docker Swagger CronJobs

A fully configurable Node.js, Express, and TypeScript server template with a service-based architecture that can interact with MySQL, PostgresSQL, Sqlite, MariaDB, MSSql, DB2, Snowflake, Oracle, MongoDB. Out-of-the-box validation, documentation generation, and more.

Features

  • Node.js, Express, TypeScript: Robust server setup using Node.js, Express, and TypeScript.
  • Sequelize: Integration with Sequelize for SQL database operations.
  • Mongoose: Integration with Mongoose for MongoDB database operations.
  • Database Compatibility: Interact with MySQL, PostgreSQL, MariaDB, Sqlite, MSSql, MongoDB.
  • Validation Mechanism: Pre-built validations for request payloads.
  • Automated Swagger Documentation: Automatically generated documentation available at /api-docs.
  • Service-Based Architecture: Modular approach for better organization and scalability.
  • Socket Events: Socket event handling using Socket.io.
  • Docker: Dockerized for easy deployment.
  • Cron Jobs: Schedule tasks using cron jobs.

Modules

Automated Swagger Docs

  • Swagger documentation auto-generated for all routes.
  • Accessible at /api-docs.
  • Generated using the doc method in the MasterController class and Joi validation schemas.

MasterController (Heart of the application)

The MasterController is the backbone, providing functionalities for managing HTTP requests, socket events, payload validation, and more.

Features

  • Controller Logic Handling: restController method manages HTTP requests.
  • Socket Event Handling: socketController method manages socket events.
  • Cron Job Scheduling: cronController method schedules cron jobs.
  • Payload Validation: joiValidator method validates incoming request payloads.
  • Swagger Documentation Generation: doc method generates Swagger documentation.
  • Route Handling: get, post, put, and delete methods register routes within the Express router.

Usage

Extend the MasterController to create controller classes for specific routes or socket events. Use the provided methods for efficient request handling, validation, and documentation generation.

Installation

Automated (CLI Tool)

Easily initialize a Node.js server project with custom configurations using our CLI tool:

npx node-server-init <folder-name>

If you want to use the current directory as the project folder, run the following command:

npx node-server-init .

For more information, visit the CLI Tool page or the GitHub repository.

Manual

Clone this repo to your local machine using `

$ git clone https://github.com/Thre4dripper/NodeTs-Express-Service-Based-Template

Install dependencies

$ npm install or yarn

Start the server

$ npm run dev or yarn dev

Build the project

$ npm run build or yarn build

Run the project

$ npm run start or yarn start

Database Setup

Additional dependencies are required for database operations. Install the appropriate dependencies for your database dialect.

MySQL

$ npm install mysql2

PostgreSQL

$ npm install pg pg-hstore

Sqlite

$ npm install sqlite

MariaDB

$ npm install mariadb

MSSql

$ npm install tedious or mssql

DB2

$ npm install ibm_db

Snowflake

$ npm install snowflake-sdk

Oracle

$ npm install oracledb

MongoDB

$ npm install mongoose

Creating APIs

Controller

class Controller extends MasterController<IParams, IQuery, IBody> {
    // swagger documetation for the api
    static doc() {
        return {
            tags: ['User'],
            summary: 'Register User',
            description: 'Register User',
        };
    }

    // add your validations here,
    // rest of the swagger documentation will be generated automatically from the validation
    public static validate(): RequestBuilder {
        const payload = new RequestBuilder();

        // request body validation
        payload.addToBody(
            Joi.object().keys({
                name: Joi.string().required(),
                lastName: Joi.string().required(),
                email: Joi.string().email().required(),
                password: Joi.string().min(8).max(20).required(),
            }),
        );

        // request query validation
        payload.addToQuery(
            Joi.object().keys({
                limit: Joi.number().required(),
                offset: Joi.number().required(),
            }),
        );

        // request params validation
        payload.addToParams(
            Joi.object().keys({
                id: Joi.number().required(),
            }),
        );
        return payload;
    }

    // controller function
    async restController(
        params: IParams,
        query: IQuery,
        body: IBody,
        headers: any,
        allData: any): Promise<ResponseBuilder> {
        // your code here
        return new ResponseBuilder(200, Response, 'Success Message');
    }

    // socket controller function
    socketController(io: Server, socket: Socket, payload: any): void {
        // your code here
        // Socket data will be available in payload, recieved from the client on socket event, which is setup in the route file
        // You can emit data back to the client using io.emit or socket.emit
    }

    // cron controller function
    cronController(): void {
        // your scheduled code here (if any)
    }
}

export default Controller;

Controller Generics

  • IParams: Request params interface/type
  • IQuery: Request query interface/type
  • IBody: Request body interface/type

restController Parameters

  • params: Request params (eg. /user/:id)
  • query: Request query (eg. /user?limit=10&offset=0)
  • body: Request body
  • headers: Request headers
  • allData: All request data (all the above-combined + custom data from middlewares)

socketController Parameters

  • io: Socket.io instance
  • socket: Socket instance
  • payload: Data sent from the client

Router File

import express from 'express'
import Controller from '../Controller'

export default (app: express.Application) => {
    // REST Routes
    Controller.get(app, '/user/:id', [
        /* Comma separated middlewares */
    ])
    Controller.post(app, '/user/:id', [
        /* Comma separated middlewares */
    ])
    Controller.put(app, '/user/:id', [
        /* Comma separated middlewares */
    ])
    Controller.delete(app, '/user/:id', [
        /* Comma separated middlewares */
    ])
    Controller.patch(app, '/user/:id', [
        /* Comma separated middlewares */
    ])

    // Socket Events
    // Any payload you send from the client to this event will be available in the socketController function
    Controller.socketIO('Event Name')
}

Important: Make sure to name your router file as *.routes.ts or *.routes.js

Note: You don't need to import your router file to anywhere, put it in the routes directory, and it will be automatically taken care by the package.

Cron File

class DemoCron extends MasterController<null, null, null> {
    cronController() {
        console.log('Cron job is running');
    }
}

// Unix Crontab format
DemoCron.cronJob('*/5 * * * * *');

// Using CronBuilder
DemoCron.cronJob(
    new CronBuilder()
    .every()
    .second()
    .every()
    .specificMinute([10, 20, 30])
    .every()
    .dayOfMonth(CronMonth.January)
    .every()
    .dayOfWeek(CronWeekday.Friday)
    .build(),
);

Important: Make sure to name your cron file as *.cron.ts or *.cron.js

Note: You don't need to import your cron file to anywhere, put it in cron directory, and it will be automatically taken care by the package.

Docker

Docker Environment variables

  • PORT - Port number for the server to run on.
  • DB_DIALECT - Database dialect to use. (Options: mysql, postgres, mariadb, sqlite, mssql, mongodb)
  • DB_HOST - Database host.
  • DB_PORT - Database port.
  • DB_USER - Database username.
  • DB_PASS - Database password.
  • DB_NAME - Database name.
  • MONGO_URI - MongoDB URI (Only for MongoDB Dialect).
  • JWT_SECRET - Secret key for JWT.

Build the image

$ docker build -t <image-name> .

Run the container

$ docker run -e <env-variable>=<value> -p <port>:<port> <image-name>

Run the container in the background

$ docker run -d -e <env-variable>=<value> -p <port>:<port> <image-name>

Stop the container

$ docker stop <container-id>

Remove the container

$ docker rm <container-id>

Remove the image

$ docker rmi <image-name>

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

Node + Typescript + Express + Sequelize + Mongoose + Validations + Socket + CronJobs + Docker + Swagger + Service Based Template

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published