├── .env ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── Dockerfile ├── README.md ├── config ├── default.yml └── development.yml ├── docker-compose.yml ├── nest-cli.json ├── package-lock.json ├── package.json ├── src ├── app.module.ts ├── auth │ ├── auth.controller.ts │ ├── auth.module.ts │ ├── decorator │ │ └── get-user.decorator.ts │ ├── dto │ │ ├── signin-credentials.dto.ts │ │ └── signup-credentials.dto.ts │ ├── entity │ │ └── user.entity.ts │ ├── interface │ │ └── jwt-payload.interface.ts │ ├── jwt-strategy.ts │ ├── repository │ │ └── user.repository.ts │ └── service │ │ └── auth.service.ts ├── main.ts ├── migration │ └── .gitkeep ├── todo │ ├── dto │ │ └── todo.dto.ts │ ├── entity │ │ └── todo.entity.ts │ ├── interface │ │ └── todo-payload.interface.ts │ ├── repository │ │ └── todo.repository.ts │ ├── service │ │ └── todo.service.ts │ ├── todo.controller.ts │ └── todo.module.ts ├── typeorm.config.ts ├── user │ ├── dto │ │ └── user-info.dto.ts │ ├── entity │ │ └── user-info.entity.ts │ ├── interface │ │ └── user-info.interface.ts │ ├── repository │ │ └── user-info.repository.ts │ ├── service │ │ └── user.service.ts │ ├── user.controller.ts │ └── user.module.ts └── utils │ └── file-upload.utils.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.env: -------------------------------------------------------------------------------- 1 | DB_TYPE=postgres 2 | POSTGRES_HOST=postgres-db 3 | POSTGRES_PORT=5432 4 | DATABASE_USER=postgres 5 | DATABASE_PASSWORD=postgres 6 | DB_NAME=tododb 7 | POSTGRES_USER=postgres 8 | DB_USERNAME=postgres 9 | DB_PASSWORD=postgres 10 | JWT_SECRET=anyKey 11 | APP_EXPIRES=3600 12 | PGADMIN_DEFAULT_EMAIL=postgres@mail.com 13 | PGADMIN_DEFAULT_PASSWORD=admin12 14 | PGADMIN_LISTEN_PORT=80 15 | APP_PORT=3000 -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | sourceType: 'module', 6 | }, 7 | plugins: ['@typescript-eslint/eslint-plugin'], 8 | extends: [ 9 | 'plugin:@typescript-eslint/recommended', 10 | 'prettier/@typescript-eslint', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | rules: { 19 | '@typescript-eslint/interface-name-prefix': 'off', 20 | '@typescript-eslint/explicit-function-return-type': 'off', 21 | '@typescript-eslint/explicit-module-boundary-types': 'off', 22 | '@typescript-eslint/no-explicit-any': 'off', 23 | }, 24 | }; 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # postgres storage 6 | /pgadmin-data 7 | /pgdata 8 | 9 | # Migration folder 10 | ./src/migration/*.ts 11 | 12 | # Keep migration folder 13 | ./src/migration/.gitkeep 14 | 15 | # Logs 16 | logs 17 | *.log 18 | npm-debug.log* 19 | yarn-debug.log* 20 | yarn-error.log* 21 | lerna-debug.log* 22 | 23 | # OS 24 | .DS_Store 25 | 26 | # Tests 27 | /coverage 28 | /.nyc_output 29 | 30 | # IDEs and editors 31 | /.idea 32 | .project 33 | .classpath 34 | .c9/ 35 | *.launch 36 | .settings/ 37 | *.sublime-workspace 38 | 39 | # IDE - VSCode 40 | .vscode/* 41 | !.vscode/settings.json 42 | !.vscode/tasks.json 43 | !.vscode/launch.json 44 | !.vscode/extensions.json 45 | 46 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Image source 2 | FROM node:10-alpine 3 | 4 | # Docker working directory 5 | WORKDIR /app 6 | 7 | # Copying file into APP directory of docker 8 | COPY ./package.json ./package-lock.json /app/ 9 | 10 | # Then install the NPM module 11 | RUN npm install 12 | 13 | # Copy current directory to APP folder 14 | COPY . /app/ 15 | 16 | EXPOSE 3000 17 | CMD ["npm", "run", "start:dev"] -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Nest Logo 3 |

4 | 5 | ## Description 6 | 7 | A simple TODO application under Docker environment. 8 | * NestJS 9 | * TypeORM 10 | * PostgreSQL 11 | * Swagger 12 | * PGadmin4 13 | * JWT 14 | * Docker 15 | 16 | Go to [Medium](https://tushar-chy.medium.com/a-simple-todo-application-with-nestjs-typeorm-postgresql-swagger-pgadmin4-jwt-and-docker-caa2742a4295) to get the full tutorial. 17 | ## Food App 18 | Another nice repo that is based on a [food-app](https://github.com/TusharRoy23/food-app-nestjs) and for the test, Jest-test has been used. 19 | 20 | # Running the app on docker 21 | ## Docker build & start 22 | 23 | ```bash 24 | # docker env build 25 | $ docker-compose build 26 | 27 | # docker env start 28 | $ docker-compose up 29 | 30 | # remove docker container (services & networks) 31 | $ docker-compose down 32 | ``` 33 | ## Migration 34 | 35 | ```bash 36 | # generate migration 37 | $ docker-compose run nestjs npm run typeorm:generate AnyNameYouLike 38 | 39 | # run migration 40 | $ docker-compose run nestjs npm run typeorm:run 41 | ``` 42 | 43 | # Running the app without docker 44 | ## Installation 45 | 46 | ```bash 47 | $ npm install 48 | ``` 49 | ## Migration 50 | 51 | ```bash 52 | # generate migration 53 | $ npm run typeorm:generate AnyNameYouLike 54 | 55 | # run migration 56 | $ npm run typeorm:run 57 | ``` 58 | 59 | ## Running the app 60 | 61 | ```bash 62 | # development 63 | $ npm run start 64 | 65 | # watch mode 66 | $ npm run start:dev 67 | 68 | # production mode 69 | $ npm run start:prod 70 | ``` 71 | -------------------------------------------------------------------------------- /config/default.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 3000 3 | 4 | db: 5 | type: 'postgres' 6 | port: 5432 7 | database: 'tododb' 8 | 9 | jwt: 10 | expiresIn: 3600 -------------------------------------------------------------------------------- /config/development.yml: -------------------------------------------------------------------------------- 1 | db: 2 | host: 'localhost' 3 | username: 'postgres' 4 | password: 'postgres' 5 | synchronize: false 6 | 7 | jwt: 8 | secret: 'anyKey' -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | db: 4 | image: postgres 5 | restart: always 6 | environment: 7 | - POSTGRES_USER=${DATABASE_USER} 8 | - POSTGRES_PASSWORD=${DATABASE_PASSWORD} 9 | - POSTGRES_DB=${DB_NAME} 10 | container_name: postgres-db 11 | volumes: 12 | - ./pgdata:/var/lib/postgresql/data 13 | nestjs: 14 | build: 15 | context: . 16 | dockerfile: ./Dockerfile 17 | image: tusharchy/nest-and-postgres-application:latest 18 | environment: 19 | - DB_TYPE=${DB_TYPE} 20 | - POSTGRES_HOST=${POSTGRES_HOST} 21 | - POSTGRES_USER=${DATABASE_USER} 22 | - POSTGRES_PASS=${DATABASE_PASSWORD} 23 | - POSTGRES_DB=${DB_NAME} 24 | - POSTGRES_SYNC=false 25 | - JWT_SECRET=${JWT_SECRET} 26 | - POSTGRES_PORT=${POSTGRES_PORT} 27 | - APP_EXPIRES=${APP_EXPIRES} 28 | - APP_PORT=${APP_PORT} 29 | ports: 30 | - "3000:3000" # expose-to-the-world : only-in-the-docker 31 | container_name: nest-todo-app-be 32 | depends_on: 33 | - db 34 | volumes: 35 | - .:/app 36 | - /app/node_modules 37 | pgadmin: 38 | image: dpage/pgadmin4 39 | restart: always 40 | container_name: nest-pgadmin4 41 | environment: 42 | - PGADMIN_DEFAULT_EMAIL=${PGADMIN_DEFAULT_EMAIL} 43 | - PGADMIN_DEFAULT_PASSWORD=${PGADMIN_DEFAULT_PASSWORD} 44 | - PGADMIN_LISTEN_PORT=${PGADMIN_LISTEN_PORT} 45 | ports: 46 | - "8080:80" 47 | volumes: 48 | - ./pgadmin-data:/var/lib/pgadmin 49 | depends_on: 50 | - db 51 | volumes: 52 | pgdata: 53 | pgadmin-data: -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "todoAppOnNestJs", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "prebuild": "rimraf dist", 10 | "build": "nest build", 11 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 12 | "start": "nest start", 13 | "start:dev": "nest start --watch", 14 | "start:debug": "nest start --debug --watch", 15 | "start:prod": "node dist/main", 16 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 17 | "test": "jest", 18 | "test:watch": "jest --watch", 19 | "test:cov": "jest --coverage", 20 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 21 | "test:e2e": "jest --config ./test/jest-e2e.json", 22 | "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/typeorm.config.ts", 23 | "typeorm:create": "npm run typeorm migration:create -- -n", 24 | "typeorm:generate": "npm run typeorm migration:generate -- -n", 25 | "typeorm:run": "npm run typeorm migration:run", 26 | "typeorm:revert": "npm run typeorm migration:revert" 27 | }, 28 | "dependencies": { 29 | "@nestjs/common": "^7.5.1", 30 | "@nestjs/core": "^7.5.1", 31 | "@nestjs/jwt": "^7.2.0", 32 | "@nestjs/passport": "^7.1.5", 33 | "@nestjs/platform-express": "^7.5.1", 34 | "@nestjs/serve-static": "^2.1.4", 35 | "@nestjs/swagger": "^4.7.9", 36 | "@nestjs/typeorm": "^7.1.5", 37 | "bcrypt": "^5.0.0", 38 | "body-parser": "^1.19.0", 39 | "class-transformer": "^0.3.1", 40 | "class-validator": "^0.12.2", 41 | "config": "^3.3.3", 42 | "dotenv": "^8.2.0", 43 | "passport": "^0.4.1", 44 | "passport-jwt": "^4.0.0", 45 | "pg": "^8.5.1", 46 | "reflect-metadata": "^0.1.13", 47 | "rimraf": "^3.0.2", 48 | "rxjs": "^6.6.3", 49 | "swagger-ui-express": "^4.1.6", 50 | "typeorm": "^0.2.29", 51 | "uuid": "^8.3.2" 52 | }, 53 | "devDependencies": { 54 | "@nestjs/cli": "^7.5.1", 55 | "@nestjs/schematics": "^7.1.3", 56 | "@nestjs/testing": "^7.5.1", 57 | "@types/express": "^4.17.8", 58 | "@types/jest": "^26.0.15", 59 | "@types/node": "^14.14.6", 60 | "@types/supertest": "^2.0.10", 61 | "@typescript-eslint/eslint-plugin": "^4.6.1", 62 | "@typescript-eslint/parser": "^4.6.1", 63 | "eslint": "^7.12.1", 64 | "eslint-config-prettier": "7.0.0", 65 | "eslint-plugin-prettier": "^3.1.4", 66 | "jest": "^26.6.3", 67 | "prettier": "^2.1.2", 68 | "supertest": "^6.0.0", 69 | "ts-jest": "^26.4.3", 70 | "ts-loader": "^8.0.8", 71 | "ts-node": "^9.0.0", 72 | "tsconfig-paths": "^3.9.0", 73 | "typescript": "^4.0.5" 74 | }, 75 | "jest": { 76 | "moduleFileExtensions": [ 77 | "js", 78 | "json", 79 | "ts" 80 | ], 81 | "rootDir": "src", 82 | "testRegex": ".*\\.spec\\.ts$", 83 | "transform": { 84 | "^.+\\.(t|j)s$": "ts-jest" 85 | }, 86 | "collectCoverageFrom": [ 87 | "**/*.(t|j)s" 88 | ], 89 | "coverageDirectory": "../coverage", 90 | "testEnvironment": "node" 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | // import { ServeStaticModule } from '@nestjs/serve-static'; 3 | import { TypeOrmModule } from '@nestjs/typeorm'; 4 | // import { join } from 'path'; 5 | import { AuthModule } from './auth/auth.module'; 6 | import { TodoModule } from './todo/todo.module'; 7 | import * as typeOrmConfig from './typeorm.config'; 8 | import { UserModule } from './user/user.module'; 9 | 10 | @Module({ 11 | imports: [ 12 | TypeOrmModule.forRoot(typeOrmConfig), 13 | AuthModule, 14 | TodoModule, 15 | UserModule 16 | ] 17 | }) 18 | export class AppModule {} 19 | -------------------------------------------------------------------------------- /src/auth/auth.controller.ts: -------------------------------------------------------------------------------- 1 | import { Post, Body, ValidationPipe, Controller } from "@nestjs/common" 2 | import { ApiTags } from "@nestjs/swagger" 3 | import { SignInCredentialsDto } from "./dto/signin-credentials.dto" 4 | import { SignupCredentialsDto } from "./dto/signup-credentials.dto" 5 | import { JwtPayload } from "./interface/jwt-payload.interface" 6 | import { AuthService } from "./service/auth.service" 7 | 8 | @ApiTags('Auth') 9 | @Controller('auth') 10 | export class AuthController { 11 | constructor( 12 | private authService: AuthService 13 | ) {} 14 | 15 | @Post('/signup') 16 | signUp( 17 | @Body(ValidationPipe) signupCredentialsDto: SignupCredentialsDto 18 | ): Promise<{ message: string }> { 19 | return this.authService.signUp(signupCredentialsDto) 20 | } 21 | 22 | @Post('/signin') 23 | signIn( 24 | @Body(ValidationPipe) signinCredentialsDto: SignInCredentialsDto 25 | ): Promise<{ accessToken: string, user: JwtPayload }>{ 26 | return this.authService.signIn(signinCredentialsDto) 27 | } 28 | } -------------------------------------------------------------------------------- /src/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { Global, Module } from '@nestjs/common'; 2 | import { JwtModule } from '@nestjs/jwt'; 3 | import { PassportModule } from '@nestjs/passport'; 4 | import { TypeOrmModule } from '@nestjs/typeorm'; 5 | import { AuthController } from './auth.controller'; 6 | import { UserRepository } from './repository/user.repository'; 7 | import { AuthService } from './service/auth.service'; 8 | import { JwtStrategy } from './jwt-strategy'; 9 | 10 | @Global() 11 | @Module({ 12 | imports: [ 13 | PassportModule.register({ defaultStrategy: 'jwt' }), 14 | JwtModule.register({ 15 | secret: process.env.JWT_SECRET, 16 | signOptions: { 17 | expiresIn: +process.env.APP_EXPIRES 18 | } 19 | }), 20 | TypeOrmModule.forFeature([UserRepository]) 21 | ], 22 | controllers: [AuthController], 23 | providers: [ 24 | AuthService, 25 | JwtStrategy 26 | ], 27 | exports: [ 28 | JwtStrategy, 29 | PassportModule 30 | ] 31 | }) 32 | export class AuthModule {} 33 | -------------------------------------------------------------------------------- /src/auth/decorator/get-user.decorator.ts: -------------------------------------------------------------------------------- 1 | import { createParamDecorator, ExecutionContext } from "@nestjs/common"; 2 | import { User } from "../entity/user.entity"; 3 | 4 | export const GetUser = createParamDecorator((data, ctx: ExecutionContext): User => { 5 | const req = ctx.switchToHttp().getRequest() 6 | return req.user 7 | }) -------------------------------------------------------------------------------- /src/auth/dto/signin-credentials.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from "@nestjs/swagger" 2 | import { IsString, Matches, MaxLength, MinLength } from "class-validator" 3 | 4 | export class SignInCredentialsDto { 5 | @ApiProperty({ minimum: 4, maximum: 20 }) 6 | @IsString() 7 | @MinLength(4) 8 | @MaxLength(20) 9 | username: string 10 | 11 | @ApiProperty({ minimum: 6, maximum: 20, description: 'At least 1 capital, 1 small, 1 special character & 1 number' }) 12 | @IsString() 13 | @MinLength(6) 14 | @MaxLength(20) 15 | @Matches( 16 | /((?=.*\d)|(?=.*\w+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/, 17 | { message: 'Password too weak'} 18 | ) 19 | password: string 20 | } -------------------------------------------------------------------------------- /src/auth/dto/signup-credentials.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from "@nestjs/swagger" 2 | import { IsString, MinLength, MaxLength, Matches } from "class-validator" 3 | 4 | export class SignupCredentialsDto { 5 | @ApiProperty({ minimum: 4, maximum: 20 }) 6 | @IsString() 7 | @MinLength(4) 8 | @MaxLength(20) 9 | username: string 10 | 11 | @ApiProperty({ minimum: 6, maximum: 20, description: 'At least 1 capital, 1 small, 1 special character & 1 number' }) 12 | @IsString() 13 | @MinLength(6) 14 | @MaxLength(20) 15 | @Matches( 16 | /((?=.*\d)|(?=.*\w+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/, 17 | { message: 'Password too weak'} 18 | ) 19 | password: string 20 | } -------------------------------------------------------------------------------- /src/auth/entity/user.entity.ts: -------------------------------------------------------------------------------- 1 | import { BaseEntity, Column, Entity, JoinColumn, OneToMany, OneToOne, PrimaryGeneratedColumn, Unique } from "typeorm"; 2 | import * as bcrypt from "bcrypt" 3 | import { Todo } from "../../todo/entity/todo.entity"; 4 | import { UserInfo } from "../../user/entity/user-info.entity"; 5 | 6 | @Entity() 7 | @Unique(['username']) 8 | 9 | export class User extends BaseEntity { 10 | @PrimaryGeneratedColumn() 11 | id: number 12 | 13 | @Column({ type: "varchar" }) 14 | username: string 15 | 16 | @Column({ type: "varchar" }) 17 | password: string 18 | 19 | @Column() 20 | salt: string 21 | 22 | @OneToMany(type => Todo, todo => todo.user, { eager: true }) 23 | todo: Todo[] 24 | 25 | @OneToOne(type => UserInfo, { eager: true }) 26 | @JoinColumn() 27 | user_info: UserInfo 28 | 29 | async validatePassword(password: string): Promise { 30 | const hash = await bcrypt.hash(password, this.salt) 31 | return hash === this.password 32 | } 33 | } -------------------------------------------------------------------------------- /src/auth/interface/jwt-payload.interface.ts: -------------------------------------------------------------------------------- 1 | import { UserInfo } from "../../user/entity/user-info.entity"; 2 | 3 | export interface JwtPayload { 4 | username: string 5 | user_info: UserInfo 6 | } -------------------------------------------------------------------------------- /src/auth/jwt-strategy.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, UnauthorizedException } from "@nestjs/common"; 2 | import { PassportStrategy } from "@nestjs/passport"; 3 | import { InjectRepository } from "@nestjs/typeorm"; 4 | import { Strategy, ExtractJwt } from 'passport-jwt' 5 | import { User } from "./entity/user.entity"; 6 | import { JwtPayload } from "./interface/jwt-payload.interface"; 7 | import { UserRepository } from "./repository/user.repository"; 8 | 9 | @Injectable() 10 | export class JwtStrategy extends PassportStrategy(Strategy) { 11 | constructor( 12 | @InjectRepository(UserRepository) 13 | private userRepository: UserRepository 14 | ) { 15 | super({ 16 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 17 | secretOrKey: process.env.JWT_SECRET 18 | }) 19 | } 20 | 21 | async validate(payload: JwtPayload): Promise { 22 | const { username } = payload 23 | const user = await this.userRepository.findOne({ username }) 24 | 25 | if (!user) { 26 | throw new UnauthorizedException() 27 | } 28 | return user 29 | } 30 | } -------------------------------------------------------------------------------- /src/auth/repository/user.repository.ts: -------------------------------------------------------------------------------- 1 | import { EntityRepository, Repository } from "typeorm"; 2 | import { ConflictException, InternalServerErrorException } from "@nestjs/common"; 3 | import * as bcrypt from 'bcrypt' 4 | 5 | import { SignupCredentialsDto } from "../dto/signup-credentials.dto"; 6 | import { SignInCredentialsDto } from "../dto/signin-credentials.dto"; 7 | import { User } from "../entity/user.entity"; 8 | import { UserInfo } from "../../user/entity/user-info.entity"; 9 | import { JwtPayload } from "../interface/jwt-payload.interface"; 10 | 11 | @EntityRepository(User) 12 | export class UserRepository extends Repository { 13 | async signUp(signupCredentialsDto: SignupCredentialsDto): Promise<{ message: string }> { 14 | const { username, password } = signupCredentialsDto 15 | 16 | const user = new User() 17 | user.username = username 18 | user.salt = await bcrypt.genSalt() 19 | user.password = await this.hashPassword(password, user.salt) 20 | 21 | try { 22 | const userInfo = new UserInfo() 23 | await userInfo.save() 24 | 25 | user.user_info = userInfo 26 | await user.save() 27 | 28 | return { message: 'User successfully created !' } 29 | } catch (error) { 30 | if (error.code === '23505') { 31 | throw new ConflictException('Username already exists') 32 | } else { 33 | throw new InternalServerErrorException() 34 | } 35 | } 36 | } 37 | 38 | async validateUserPassword(signinCredentialDto: SignInCredentialsDto): Promise { 39 | const { username, password } = signinCredentialDto 40 | const auth = await this.findOne({ username }) 41 | 42 | if (auth && await auth.validatePassword(password)) { 43 | return { 44 | username: auth.username, 45 | user_info: auth.user_info 46 | } 47 | } else { 48 | return null 49 | } 50 | } 51 | 52 | 53 | 54 | private async hashPassword(password: string, salt: string): Promise{ 55 | return bcrypt.hash(password, salt) 56 | } 57 | } -------------------------------------------------------------------------------- /src/auth/service/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, UnauthorizedException } from "@nestjs/common"; 2 | import { JwtService } from "@nestjs/jwt"; 3 | import { InjectRepository } from "@nestjs/typeorm"; 4 | import { SignInCredentialsDto } from "../dto/signin-credentials.dto"; 5 | import { SignupCredentialsDto } from "../dto/signup-credentials.dto"; 6 | import { JwtPayload } from "../interface/jwt-payload.interface"; 7 | import { UserRepository } from "../repository/user.repository"; 8 | 9 | @Injectable() 10 | export class AuthService { 11 | constructor( 12 | @InjectRepository(UserRepository) 13 | private userRepository: UserRepository, 14 | private jwtService: JwtService 15 | ) {} 16 | 17 | async signUp(signupCredentialsDto: SignupCredentialsDto): Promise<{ message: string }> { 18 | return this.userRepository.signUp(signupCredentialsDto) 19 | } 20 | 21 | async signIn(signInCredentialsDto: SignInCredentialsDto): Promise<{ accessToken: string, user: JwtPayload }> { 22 | const resp = await this.userRepository.validateUserPassword(signInCredentialsDto) 23 | if (!resp) { 24 | throw new UnauthorizedException('Invalid credentials') 25 | } 26 | 27 | const payload: JwtPayload = resp 28 | const accessToken = await this.jwtService.sign(payload) 29 | 30 | return { 31 | accessToken, 32 | user: resp 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; 3 | import { AppModule } from './app.module'; 4 | import * as bodyParser from 'body-parser' 5 | import { NestExpressApplication } from '@nestjs/platform-express'; 6 | 7 | async function bootstrap() { 8 | // const app = await NestFactory.create(AppModule); 9 | const app = await NestFactory.create(AppModule) 10 | const port = +process.env.APP_PORT || 3000 11 | app.setGlobalPrefix('api') 12 | console.log('Port running on: ', port) 13 | 14 | const options = new DocumentBuilder() 15 | .addBearerAuth() 16 | .setTitle('Todo APP') 17 | .setDescription('Todo API documentation') 18 | .setVersion('1.0') 19 | .addTag('Todo') 20 | .build() 21 | 22 | const document = SwaggerModule.createDocument(app, options) 23 | SwaggerModule.setup('api', app, document) 24 | 25 | app.enableCors() 26 | 27 | app.use(bodyParser.json({limit: '1mb'})) 28 | app.use(bodyParser.urlencoded({ limit:'1mb', extended: true })) 29 | app.use(bodyParser.text({type: 'text/html'})) 30 | 31 | await app.listen(port); 32 | } 33 | bootstrap(); 34 | -------------------------------------------------------------------------------- /src/migration/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TusharRoy23/todoAppOnNestJs/d446f9cd350f954eef1f00d87bec66e70cedca3e/src/migration/.gitkeep -------------------------------------------------------------------------------- /src/todo/dto/todo.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from "@nestjs/swagger" 2 | import { IsString, MaxLength, MinLength } from "class-validator" 3 | 4 | export class TodoDto { 5 | @ApiProperty() 6 | @IsString() 7 | @MinLength(4) 8 | @MaxLength(30) 9 | title: string 10 | 11 | @ApiProperty() 12 | @IsString() 13 | @MinLength(4) 14 | @MaxLength(150) 15 | description: string 16 | } -------------------------------------------------------------------------------- /src/todo/entity/todo.entity.ts: -------------------------------------------------------------------------------- 1 | import { User } from "../../auth/entity/user.entity"; 2 | import { BaseEntity, Column, CreateDateColumn, Entity, ManyToOne, PrimaryGeneratedColumn } from "typeorm"; 3 | 4 | @Entity() 5 | export class Todo extends BaseEntity { 6 | @PrimaryGeneratedColumn() 7 | id: number 8 | 9 | @Column({ type: "varchar"}) 10 | title: string 11 | 12 | @Column() 13 | description: string 14 | 15 | @CreateDateColumn({ type: 'timestamp' }) 16 | createdDate: Date 17 | 18 | @CreateDateColumn({ type: 'timestamp' }) 19 | updatedDate: Date 20 | 21 | @ManyToOne(type => User, user => user.todo, { eager: false }) 22 | user: User 23 | 24 | @Column({ type: 'int' }) 25 | userId: number 26 | } -------------------------------------------------------------------------------- /src/todo/interface/todo-payload.interface.ts: -------------------------------------------------------------------------------- 1 | export interface TodoPayload { 2 | id?: number 3 | title: string 4 | description: string 5 | createdDate: Date 6 | updatedDate: Date 7 | userId?: number 8 | } -------------------------------------------------------------------------------- /src/todo/repository/todo.repository.ts: -------------------------------------------------------------------------------- 1 | import { User } from "../../auth/entity/user.entity"; 2 | import { EntityRepository, Repository } from "typeorm"; 3 | import { TodoDto } from "../dto/todo.dto"; 4 | import { Todo } from "../entity/todo.entity"; 5 | import { TodoPayload } from "../interface/todo-payload.interface"; 6 | 7 | @EntityRepository(Todo) 8 | export class TodoRepository extends Repository { 9 | async createTodo( 10 | todoDto: TodoDto, 11 | user: User 12 | ): Promise { 13 | const { title, description } = todoDto 14 | 15 | const todo = new Todo() 16 | 17 | todo.title = title 18 | todo.description = description 19 | todo.user = user 20 | 21 | await todo.save() 22 | 23 | delete todo.user 24 | return todo 25 | } 26 | 27 | async getAllTodo(user: User): Promise { 28 | const query = this.createQueryBuilder('todo') 29 | 30 | query.where('todo.userId = :userId', { userId: user.id }) 31 | 32 | const todos = await query.getMany() 33 | return todos 34 | } 35 | } -------------------------------------------------------------------------------- /src/todo/service/todo.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, NotFoundException } from "@nestjs/common"; 2 | import { InjectRepository } from "@nestjs/typeorm"; 3 | import { User } from "../../auth/entity/user.entity"; 4 | import { TodoDto } from "../dto/todo.dto"; 5 | import { Todo } from "../entity/todo.entity"; 6 | import { TodoPayload } from "../interface/todo-payload.interface"; 7 | import { TodoRepository } from "../repository/todo.repository"; 8 | 9 | @Injectable() 10 | export class TodoService { 11 | constructor( 12 | @InjectRepository(TodoRepository) 13 | private todoRepository: TodoRepository 14 | ) {} 15 | 16 | async getAllTodo(user: User): Promise{ 17 | return this.todoRepository.getAllTodo(user) 18 | } 19 | 20 | async createTodo( 21 | todoDto: TodoDto, 22 | user: User 23 | ): Promise { 24 | return this.todoRepository.createTodo(todoDto, user) 25 | } 26 | 27 | async getTodoById( 28 | id: number, 29 | user: User 30 | ): Promise { 31 | const todo = await this.todoRepository.findOne({ where: { id, userId: user.id } }) 32 | 33 | if (!todo) { 34 | throw new NotFoundException(`This ${id} is not found`); 35 | } 36 | return todo 37 | } 38 | 39 | async updateTodoById(id: number, todoDto: TodoDto, user: User): Promise { 40 | const todo = await this.getTodoById(id, user) 41 | todo.title = todoDto.title 42 | todo.description = todoDto.description 43 | 44 | await todo.save() 45 | return { 46 | id: todo.id, 47 | title: todo.title, 48 | description: todo.description, 49 | createdDate: todo.createdDate, 50 | updatedDate: todo.updatedDate 51 | } 52 | } 53 | 54 | async deleteTodoById(id: number, user: User): Promise<{ message: string }> { 55 | const todo = await this.todoRepository.delete({ id, userId: user.id }) 56 | 57 | if (todo.affected === 0) { 58 | throw new NotFoundException(`This ${id} is not found`) 59 | } 60 | return { message: 'Deleted successfully !' } 61 | } 62 | } -------------------------------------------------------------------------------- /src/todo/todo.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, Controller, Delete, Get, Param, ParseIntPipe, Patch, Post, UseGuards, UsePipes, ValidationPipe } from "@nestjs/common"; 2 | import { AuthGuard } from "@nestjs/passport"; 3 | import { ApiBearerAuth, ApiTags } from "@nestjs/swagger"; 4 | import { GetUser } from "../auth/decorator/get-user.decorator"; 5 | import { User } from "../auth/entity/user.entity"; 6 | import { TodoDto } from "./dto/todo.dto"; 7 | import { Todo } from "./entity/todo.entity"; 8 | import { TodoPayload } from "./interface/todo-payload.interface"; 9 | import { TodoService } from "./service/todo.service"; 10 | 11 | @ApiTags('Todo') 12 | @ApiBearerAuth() 13 | @Controller('todo') 14 | @UseGuards(AuthGuard()) 15 | 16 | export class TodoController { 17 | constructor( 18 | private todoService: TodoService 19 | ) {} 20 | 21 | @Get() 22 | getAllTodo( 23 | @GetUser() user: User 24 | ): Promise { 25 | return this.todoService.getAllTodo(user) 26 | } 27 | 28 | @Post() 29 | @UsePipes(ValidationPipe) 30 | createTodo( 31 | @Body() todoDto: TodoDto, 32 | @GetUser() user: User 33 | ): Promise { 34 | return this.todoService.createTodo(todoDto, user) 35 | } 36 | 37 | @Get('/:id') 38 | getTodoById( 39 | @Param('id', ParseIntPipe) id: number, 40 | @GetUser() user: User 41 | ): Promise { 42 | return this.todoService.getTodoById(id, user) 43 | } 44 | 45 | @Patch('/:id') 46 | updateTodoById( 47 | @Param('id', ParseIntPipe) id: number, 48 | @Body() todoDto: TodoDto, 49 | @GetUser() user: User 50 | ): Promise{ 51 | return this.todoService.updateTodoById(id, todoDto, user) 52 | } 53 | 54 | @Delete('/:id') 55 | deleteTodoById( 56 | @Param('id', ParseIntPipe) id: number, 57 | @GetUser() user: User 58 | ): Promise<{ message: string }>{ 59 | return this.todoService.deleteTodoById(id, user) 60 | } 61 | } -------------------------------------------------------------------------------- /src/todo/todo.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import { AuthModule } from '../auth/auth.module'; 4 | import { TodoRepository } from './repository/todo.repository'; 5 | import { TodoService } from './service/todo.service'; 6 | import { TodoController } from './todo.controller'; 7 | 8 | @Module({ 9 | imports: [ 10 | TypeOrmModule.forFeature([TodoRepository]) 11 | ], 12 | controllers: [TodoController], 13 | providers: [TodoService] 14 | }) 15 | export class TodoModule {} 16 | -------------------------------------------------------------------------------- /src/typeorm.config.ts: -------------------------------------------------------------------------------- 1 | import { TypeOrmModuleOptions } from "@nestjs/typeorm"; 2 | import * as config from 'config' 3 | 4 | const dbConfig = config.get('db') 5 | 6 | const typeOrmConfig: TypeOrmModuleOptions = { 7 | type: process.env.DB_TYPE || dbConfig.type, 8 | host: process.env.POSTGRES_HOST || dbConfig.host, 9 | port: +process.env.POSTGRES_PORT || 5432, 10 | username: process.env.DB_USERNAME || dbConfig.username, 11 | password: process.env.DB_PASSWORD || dbConfig.password, 12 | database: process.env.POSTGRES_DB || dbConfig.database, 13 | entities: [__dirname + '/**/*.entity.ts', __dirname + '/**/*.entity.js'], 14 | migrationsRun: false, 15 | logging: true, 16 | migrationsTableName: "migration", 17 | migrations: [__dirname + '/migration/**/*.ts', __dirname + '/migration/**/*.js'], 18 | synchronize: false, 19 | cli: { 20 | migrationsDir: 'src/migration' 21 | } 22 | } 23 | 24 | export = typeOrmConfig -------------------------------------------------------------------------------- /src/user/dto/user-info.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from "@nestjs/swagger" 2 | 3 | export class UserInfoDto { 4 | @ApiProperty({ 5 | required: false 6 | }) 7 | petName: string 8 | 9 | @ApiProperty({ 10 | type: 'file', 11 | properties: { 12 | file: { 13 | type: 'string', 14 | format: 'binary' 15 | } 16 | }, 17 | required: false 18 | }) 19 | photo: string 20 | 21 | @ApiProperty({ 22 | required: false 23 | }) 24 | modified_photo: string 25 | 26 | @ApiProperty({ 27 | required: false 28 | }) 29 | address: string 30 | } -------------------------------------------------------------------------------- /src/user/entity/user-info.entity.ts: -------------------------------------------------------------------------------- 1 | import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm"; 2 | 3 | @Entity() 4 | export class UserInfo extends BaseEntity { 5 | @PrimaryGeneratedColumn() 6 | id: number 7 | 8 | @Column({ name: 'pet_name', type: "varchar", nullable: true }) 9 | petName: string 10 | 11 | @Column({ type: "varchar", nullable: true }) 12 | photo: string 13 | 14 | @Column({ type: "varchar", nullable: true }) 15 | modified_photo: string 16 | 17 | @Column({ type: "varchar", nullable: false }) 18 | address: string 19 | } -------------------------------------------------------------------------------- /src/user/interface/user-info.interface.ts: -------------------------------------------------------------------------------- 1 | export interface userInfoData { 2 | id: number, 3 | petName?: string, 4 | photo?: string, 5 | modified_photo?: string, 6 | address: string 7 | } -------------------------------------------------------------------------------- /src/user/repository/user-info.repository.ts: -------------------------------------------------------------------------------- 1 | import { EntityRepository, Repository } from "typeorm"; 2 | import { UserInfo } from "../entity/user-info.entity"; 3 | 4 | @EntityRepository(UserInfo) 5 | export class UserInfoRepository extends Repository { 6 | } -------------------------------------------------------------------------------- /src/user/service/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, NotFoundException } from "@nestjs/common"; 2 | import { InjectRepository } from "@nestjs/typeorm"; 3 | import { User } from "../../auth/entity/user.entity"; 4 | import { UserInfoDto } from "../dto/user-info.dto"; 5 | import { UserInfo } from "../entity/user-info.entity"; 6 | import { userInfoData } from "../interface/user-info.interface"; 7 | import { UserInfoRepository } from "../repository/user-info.repository"; 8 | 9 | @Injectable() 10 | export class UserService { 11 | constructor( 12 | @InjectRepository(UserInfoRepository) 13 | private userInfoRepository: UserInfoRepository 14 | ) {} 15 | 16 | async getUser( 17 | user: User 18 | ): Promise { 19 | const userInfo = await this.userInfoRepository.findOne({ where : { id: user.user_info.id } }) 20 | 21 | if (!userInfo) { 22 | throw new NotFoundException("User not found."); 23 | } 24 | return userInfo 25 | } 26 | 27 | async updateUserProfile( 28 | user: User, 29 | userInfoDto: UserInfoDto 30 | ): Promise { 31 | const userInfo = await this.getUser(user) 32 | 33 | if (userInfoDto.address) userInfo.address = userInfoDto.address 34 | if (userInfoDto.petName) userInfo.petName = userInfoDto.petName 35 | if (userInfoDto.photo) userInfo.photo = userInfoDto.photo 36 | if (userInfoDto.modified_photo) userInfo.modified_photo = userInfoDto.modified_photo 37 | 38 | await userInfo.save() 39 | return userInfo 40 | } 41 | } -------------------------------------------------------------------------------- /src/user/user.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, Controller, Get, Patch, UploadedFile, UseGuards, UseInterceptors } from "@nestjs/common"; 2 | import { AuthGuard } from "@nestjs/passport"; 3 | import { FileInterceptor } from "@nestjs/platform-express"; 4 | import { ApiBearerAuth, ApiConsumes, ApiTags } from "@nestjs/swagger"; 5 | import { GetUser } from "../auth/decorator/get-user.decorator"; 6 | import { User } from "../auth/entity/user.entity"; 7 | 8 | const { editFileName, imageFileFilter } = require('../utils/file-upload.utils') 9 | import { userInfoData } from "./interface/user-info.interface"; 10 | import { UserService } from "./service/user.service"; 11 | import { diskStorage } from "multer"; 12 | import { UserInfoDto } from "./dto/user-info.dto"; 13 | 14 | // < -- Swagger Implementation Start -- > 15 | @ApiTags('User') 16 | @ApiBearerAuth() 17 | // < -- Swagger Implementation End -- > 18 | @Controller('user') 19 | @UseGuards(AuthGuard()) 20 | export class UserController { 21 | constructor( 22 | private userService: UserService 23 | ) {} 24 | 25 | @Get() 26 | getUserInfo( 27 | @GetUser() user: User 28 | ): Promise { 29 | return this.userService.getUser(user) 30 | } 31 | 32 | @Patch() 33 | @ApiConsumes('multipart/form-data') 34 | @UseInterceptors( 35 | FileInterceptor('photo', { 36 | limits: { 37 | fileSize: 2097152 38 | }, 39 | fileFilter: imageFileFilter, 40 | storage: diskStorage({ 41 | destination: function(req, file, cb) { 42 | cb(null, './uploads') 43 | }, 44 | filename: editFileName 45 | }), 46 | }) 47 | ) 48 | updateUserInfo( 49 | @UploadedFile() file, 50 | @Body() userInfoDto: UserInfoDto, 51 | @GetUser() user: User 52 | ):Promise { 53 | if (file) { 54 | userInfoDto.photo = file.originalname 55 | userInfoDto.modified_photo = file.filename 56 | } 57 | 58 | return this.userService.updateUserProfile(user, userInfoDto) 59 | } 60 | } -------------------------------------------------------------------------------- /src/user/user.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { MulterModule } from '@nestjs/platform-express'; 3 | import { TypeOrmModule } from '@nestjs/typeorm'; 4 | import { UserInfoRepository } from './repository/user-info.repository'; 5 | import { UserService } from './service/user.service'; 6 | import { UserController } from './user.controller'; 7 | 8 | @Module({ 9 | imports: [ 10 | MulterModule.register({ 11 | dest: './uploads' 12 | }), 13 | TypeOrmModule.forFeature([UserInfoRepository]) 14 | ], 15 | controllers: [UserController], 16 | providers: [UserService] 17 | }) 18 | export class UserModule {} 19 | -------------------------------------------------------------------------------- /src/utils/file-upload.utils.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, HttpStatus } from "@nestjs/common" 2 | import { extname } from "path" 3 | import { v4 as uuidv4 } from 'uuid'; 4 | 5 | const imageFileFilter = (req, file, callback) => { 6 | if (!extname(file.originalname).match(/\.(jpg|jpeg|png|gif)$/)) { 7 | callback( 8 | new HttpException( 9 | 'Only image files are allowed', 10 | HttpStatus.BAD_REQUEST 11 | ), 12 | false 13 | ) 14 | } else { 15 | callback(null, true) 16 | } 17 | } 18 | 19 | const editFileName = (req, file, callback) => { 20 | const fileExtName = extname(file.originalname) 21 | callback(null, `${uuidv4()}${fileExtName}`); 22 | } 23 | 24 | module.exports = { 25 | imageFileFilter, 26 | editFileName 27 | } -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true 14 | } 15 | } 16 | --------------------------------------------------------------------------------