Code Monkey home page Code Monkey logo

nestjs-microservice-boilerplate's Introduction

Changelog

v2.1.0

  • sample .env file to indicate required environment variables
  • switch to truly private variables, instead of TypeScript modifiers
  • CustomResponse interface includes the namespace now

v2.0.0

Core

  • upgrade to latest NestJS version(v7)
  • folder structure update
  • use cross-env to set the NODE_ENV for cross OS support

Modules

  • refactor utils to simply custom-response
  • CustomResponse interface is a generic now
  • new custom-response status WARNING = 'warning'
  • config.service will use now process.cwd() istead of a relative path
  • config.service will return the values from .env files or from process.env
  • database.module will receive each entity inside the entities instead of 'dist/**/*.entity{.ts,.js}'

Explanation

For a better understanding, check out this article.

Preparation

Write your .env variables

Now is time to write your configuration for this project. Create two files: .env.development and .env.test.

! Both will be ignored with .gitignore

! In production instead of these two, create a new file on your server named .env.production

This is an example for .env.development ! Replace with your config

DB_SERVER_PORT=3306
DB_SERVER_HOST=localhost
DB_SERVER_USERNAME=root
DB_SERVER_PASSWORD=root
DATABASE=users

ERROR_CODE_NAMESPACE=users-microservice

Microservice Port

:8875

Response Format

{
  "status":ResponseStatus
  "data":any -> '' when no data is found
  "error":CustomError
}

ResponseStatus - "success" or "fail"

CustomError - consist of 3 parts: an error code, a message and a namespace. Codes are universal, but messages can vary. Here is the error JSON payload:

{
  "code":number,
  "msg":string || string[]
  "namespace":string
}

Error codes

10xx - General Server or Network issues

1000 UNKNOWN

  • An unknown error occured while processing the request.

1001 DATABASE_ERROR

  • An unknown error occured on database.

11xx - Request issues

1100 BAD_PARAMETERS

  • Bad parameters send to endpoint
  • The validation pipe will return the error as message

nestjs-microservice-boilerplate's People

Contributors

georgianstan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

nestjs-microservice-boilerplate's Issues

QueryFailedError: relation "auth_user_entity" does not exist

I am using typeORM and i have an AuthUserEnity `import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm";

@entity()
export class AuthUserEntity {
@PrimaryGeneratedColumn()
public id: number;

@column()
public email :string;

@column()
public password :string;

@Column()
public salt : string

}`

and in AppModule : `import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";

import { TypeOrmModule } from "@nestjs/typeorm";
import { AuthUserEntity } from "./auth/auth.user.entity";
import { AuthModule } from "./auth/auth.module";

@module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get('POSTGRES_HOST'),
port: configService.get('POSTGRES_PORT'),
username: configService.get('POSTGRES_USER'),
password: configService.get('POSTGRES_PASSWORD'),
database: configService.get('POSTGRES_DB'),
entities: [AuthUserEntity],
synchronized: true
})
}),
AuthModule
],
controllers: [],
providers: []
})

export class AppModule {

}`

and in AuthModule : `import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { AuthUserEntity } from "./auth.user.entity";
import { JwtStategy } from "./auth.stategy";
import { AuthService } from "./auth.service";
import { AuthController } from "./auth.controller";
import { JwtModule } from "@nestjs/jwt";

@module({
imports: [JwtModule.register({
secret : 'iloveyou',
signOptions : {expiresIn : "1h"}
}),
TypeOrmModule.forFeature([AuthUserEntity])],
providers: [AuthService, JwtStategy],
controllers : [AuthController],
exports: [AuthService]
})

export class AuthModule{

}`

I'm try to you postman to post data and I'm getting an error " relation "auth_user_entity" does not exist" Does anyone know how to fix this? Thanks very much !

QueryFailedError: relation "users" does not exist

I am following your article on creating integration tests but I keep getting this error

QueryFailedError: relation "users" does not exist

I manually went into postgres locally and created the database for testing specified below. I verified that the db is there but when I run the test it doesn't seem to create the tables in the db. Any idea why? Did u get similar errors?

describe('UserService (e2e)', () => {
  let repository: Repository<User>
  let service: UserService

  beforeAll(async () => {
    const module = await Test.createTestingModule({
      imports: [
        UserModule,
        TypeOrmModule.forRoot({
          type: 'postgres',
          host: 'localhost',
          port: 5432,
          username: 'rm',
          password: 'root',
          database: 'ea_games_blog_test',
          entities: ['./**/*.entity.ts'],
          synchronize: false,
        }),
        TypeOrmModule.forFeature([User]),
      ],
      providers: [
        UserService,
        {
          provide: getRepositoryToken(User),
          useClass: Repository,
        },
      ],
      controllers: [UserController],
    }).compile()

    service = module.get<UserService>(UserService)
  })

  describe('Create User', () => {
    const user: Partial<UserCreateDTO> = {
      name: 'Mike Test User',
      email: '[email protected]',
    }
    it('should create a user is the DB', async () => {
      const res = await service.add(user)
      console.log('res', res)
    })
  })
})

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.