Giter VIP home page Giter VIP logo

nestjs-boilerplate's Introduction

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads CircleCI Coverage Discord Backers on Open Collective Sponsors on Open Collective Support us

Description

Nest framework TypeScript starter repository with configurations of the following -

  • Postgres DB
  • TypeORM (structured migrations & entities see usage)
  • Queue (Custom queue implementation see usage)
  • Caching
  • Swagger for documentation
  • Custom environment variables handling with multiple files & validation using Zod ( ie. simplified Testing )
  • Helmet to set security-related HTTP headers appropriately
  • Logger using winston (console logs are nest like see usage)
  • Auth Guard (Expects a Bearar token): By default the following token will work if you want to test the protected routes eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjkzMTdmN2ZjLWVjYjQtNGEwOS04ZGFkLTZiMGZlMGZjM2VhMyIsImZpcnN0X25hbWUiOiJqb2huIiwibGFzdF9uYW1lIjoiZG9lIiwiZW1haWwiOiJqb2huQGRvZS5jb20iLCJpYXQiOjE3MDc0MTkwNzV9.PfUoWAPjFyA93GNaqAtys4x2wJgLd1sm89JvM3xlnt8

Installation

$ npm install

Usage

TypeORM

Define a new entity with the .entity.ts extension preferably in here src/models/your-model/entities/name.entity.ts or wherever you want, then generate a migration file with the following command -

npm run migration:generate --name=your_migration_file_name

It will generate a migration file in src/providers/typeorm/migrations

You can deploy the migrations using -

npm run migration:deploy

OR undo the latest migration using -

npm run migration:undo

QUEUE

Add the type definition for the payload of the new job in src/providers/queue/payload-types

// new-job.type.ts

export type NewJobPayload = {
  message: string;
};

Add the new job to src/providers/queue/queue.jobs.ts

export class QueueJobs {
  /** Other Code */

  async newJob(payload: NewJobPayload): Promise<boolean> {
    /** code related to processing of the job */
    return true;
  }

  /** Other Code */
}

Map the payload in src/providers/queue/job-payload-type-mapper.ts in the following format -

the_added_job_name_in_QueueJobs: payload_type

export type JobPayloadTypeMapper = {
  /** [job-name-from QueueJobs]: payload-type*/
  newJob: NewJobPayload;
};

Now, using QueueService, just add the job & processing will be handled automatically.

Class AnyService{
  constructor(
    private readonly queueService: QueueService
  ){}

  someMethod(){
    this.queueService.addJob({
      task: "newJob",
      payload: {
        message: "my-message"
      }
    })
  }
}

LOGGER

Crate new logger from the WinstonLogger class from src/utils/winston-logger/winston-logger.ts.

Logs are saved in the logs folder in the root directory, by default it will keep logs upto 30 days.

class MyService{
  private logger = new WinstonLogger(MyService.name) // sets up the context

  foo(){
    // use like this to pass additional data
    this.logger.error({
      message: "Unauthorized",
      data: {
        user: {
          id: 1,
          first_name: "Jyotirmay",
          last_name: "Barman"
        }
      }
    });
    // OR just to pass the message
    this.logger.error("Unauthorized");
  }

}

We have the following methods available in the WinstonLogger class -

type LogPayload = string | {
  message: string,
  data?: any,
  context?:string,
  stack?: string,
}

fatal(payload: LogPayload, context?: string, stack?: string);
error(payload: LogPayload, context?: string, stack?: string);
log(payload: LogPayload, context?: string, stack?: string);
warn(payload: LogPayload, context?: string, stack?: string);
debug(payload: LogPayload, context?: string, stack?: string);
verbose(payload: LogPayload, context?: string, stack?: string);
setContext(ctx:string);
getContext(): string;

NOTE : We avoid using dependency injection for the logger because it disrupts the context when implemented

Running the app

# development
$ npm run start

# watch mode
$ npm run start:dev

# production mode
$ npm run start:prod

Test

# unit tests
$ npm run test

# e2e tests
$ npm run test:e2e

# test coverage
$ npm run test:cov

Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.

Stay in touch

License

Nest is MIT licensed.

nestjs-boilerplate's People

Contributors

jyotirmaybarman avatar

Stargazers

 avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.