├── .env ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── README.md ├── nest-cli.json ├── package.json ├── src ├── app.module.ts ├── auth │ ├── auth.controller.ts │ ├── auth.module.ts │ ├── auth.service.spec.ts │ ├── auth.service.ts │ ├── current-user.decorator.ts │ ├── guards │ │ ├── gql-auth.guard.ts │ │ ├── jwt-auth.guard.ts │ │ └── local-auth.guard.ts │ ├── strategies │ │ ├── jwt.strategy.ts │ │ └── local.strategy.ts │ └── users │ │ ├── dto │ │ └── create-user.input.ts │ │ ├── models │ │ ├── user.model.ts │ │ └── user.schema.ts │ │ ├── users.module.ts │ │ ├── users.repository.ts │ │ ├── users.resolver.ts │ │ └── users.service.ts ├── database │ ├── abstract.repository.ts │ ├── abstract.schema.ts │ └── database.module.ts └── main.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json ├── tsconfig.json └── yarn.lock /.env: -------------------------------------------------------------------------------- 1 | MONGODB_URI=mongodb://localhost/nextjs-auth 2 | JWT_SECRET=X3LVaw860XJ0VgzbPd9Nd6cbBSBHnr28ArodUrkPMfR8Qii9ovIwaGikzmLbfRJGDDDxFBaDc9Scmrypmshkj5kf6iqCyy721Vy 3 | JWT_EXPIRATION=3600 4 | PORT=3001 -------------------------------------------------------------------------------- /.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 | 'plugin:prettier/recommended', 11 | ], 12 | root: true, 13 | env: { 14 | node: true, 15 | jest: true, 16 | }, 17 | ignorePatterns: ['.eslintrc.js'], 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 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Nest Logo 3 |

4 | 5 | [circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 6 | [circleci-url]: https://circleci.com/gh/nestjs/nest 7 | 8 |

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

9 |

10 | NPM Version 11 | Package License 12 | NPM Downloads 13 | CircleCI 14 | Coverage 15 | Discord 16 | Backers on Open Collective 17 | Sponsors on Open Collective 18 | 19 | Support us 20 | 21 |

22 | 24 | 25 | ## Description 26 | 27 | [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository. 28 | 29 | ## Installation 30 | 31 | ```bash 32 | $ npm install 33 | ``` 34 | 35 | ## Running the app 36 | 37 | ```bash 38 | # development 39 | $ npm run start 40 | 41 | # watch mode 42 | $ npm run start:dev 43 | 44 | # production mode 45 | $ npm run start:prod 46 | ``` 47 | 48 | ## Test 49 | 50 | ```bash 51 | # unit tests 52 | $ npm run test 53 | 54 | # e2e tests 55 | $ npm run test:e2e 56 | 57 | # test coverage 58 | $ npm run test:cov 59 | ``` 60 | 61 | ## Support 62 | 63 | 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](https://docs.nestjs.com/support). 64 | 65 | ## Stay in touch 66 | 67 | - Author - [Kamil Myśliwiec](https://kamilmysliwiec.com) 68 | - Website - [https://nestjs.com](https://nestjs.com/) 69 | - Twitter - [@nestframework](https://twitter.com/nestframework) 70 | 71 | ## License 72 | 73 | Nest is [MIT licensed](LICENSE). 74 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nextjs-auth-backend", 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 | }, 23 | "dependencies": { 24 | "@nestjs/apollo": "^10.0.19", 25 | "@nestjs/common": "^8.0.0", 26 | "@nestjs/config": "^2.2.0", 27 | "@nestjs/core": "^8.0.0", 28 | "@nestjs/graphql": "^10.0.21", 29 | "@nestjs/jwt": "^9.0.0", 30 | "@nestjs/mongoose": "^9.2.0", 31 | "@nestjs/passport": "^9.0.0", 32 | "@nestjs/platform-express": "^8.0.0", 33 | "apollo-server-express": "^3.10.0", 34 | "bcrypt": "^5.0.1", 35 | "class-transformer": "^0.5.1", 36 | "class-validator": "^0.13.2", 37 | "cookie-parser": "^1.4.6", 38 | "graphql": "^16.5.0", 39 | "joi": "^17.6.0", 40 | "mongoose": "^6.5.0", 41 | "passport": "^0.6.0", 42 | "passport-jwt": "^4.0.0", 43 | "passport-local": "^1.0.0", 44 | "reflect-metadata": "^0.1.13", 45 | "rimraf": "^3.0.2", 46 | "rxjs": "^7.2.0" 47 | }, 48 | "devDependencies": { 49 | "@nestjs/cli": "^8.0.0", 50 | "@nestjs/schematics": "^8.0.0", 51 | "@nestjs/testing": "^8.0.0", 52 | "@types/bcrypt": "^5.0.0", 53 | "@types/cookie-parser": "^1.4.3", 54 | "@types/express": "^4.17.13", 55 | "@types/jest": "27.0.2", 56 | "@types/node": "^16.0.0", 57 | "@types/passport-jwt": "^3.0.6", 58 | "@types/passport-local": "^1.0.34", 59 | "@types/supertest": "^2.0.11", 60 | "@typescript-eslint/eslint-plugin": "^5.0.0", 61 | "@typescript-eslint/parser": "^5.0.0", 62 | "eslint": "^8.0.1", 63 | "eslint-config-prettier": "^8.3.0", 64 | "eslint-plugin-prettier": "^4.0.0", 65 | "jest": "^27.2.5", 66 | "prettier": "^2.3.2", 67 | "source-map-support": "^0.5.20", 68 | "supertest": "^6.1.3", 69 | "ts-jest": "^27.0.3", 70 | "ts-loader": "^9.2.3", 71 | "ts-node": "^10.0.0", 72 | "tsconfig-paths": "^3.10.1", 73 | "typescript": "^4.3.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 { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo'; 2 | import { Module } from '@nestjs/common'; 3 | import { ConfigModule } from '@nestjs/config'; 4 | import { GraphQLModule } from '@nestjs/graphql'; 5 | import * as Joi from 'joi'; 6 | import { AuthModule } from './auth/auth.module'; 7 | 8 | @Module({ 9 | imports: [ 10 | AuthModule, 11 | ConfigModule.forRoot({ 12 | isGlobal: true, 13 | validationSchema: Joi.object({ 14 | JWT_SECRET: Joi.string().required(), 15 | JWT_EXPIRATION: Joi.string().required(), 16 | MONGODB_URI: Joi.string().required(), 17 | PORT: Joi.number().required(), 18 | }), 19 | }), 20 | GraphQLModule.forRoot({ 21 | driver: ApolloDriver, 22 | autoSchemaFile: true, 23 | }), 24 | ], 25 | controllers: [], 26 | providers: [], 27 | }) 28 | export class AppModule {} 29 | -------------------------------------------------------------------------------- /src/auth/auth.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Post, Res, UseGuards } from '@nestjs/common'; 2 | import { Response } from 'express'; 3 | import { AuthService } from './auth.service'; 4 | import { CurrentUser } from './current-user.decorator'; 5 | import { LocalAuthGuard } from './guards/local-auth.guard'; 6 | import { User } from './users/models/user.model'; 7 | 8 | @Controller('auth') 9 | export class AuthController { 10 | constructor(private readonly authService: AuthService) {} 11 | 12 | @UseGuards(LocalAuthGuard) 13 | @Post('login') 14 | async login( 15 | @CurrentUser() user: User, 16 | @Res({ passthrough: true }) response: Response, 17 | ) { 18 | await this.authService.login(user, response); 19 | response.send(user); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { ConfigService } from '@nestjs/config'; 3 | import { JwtModule } from '@nestjs/jwt'; 4 | import { DatabaseModule } from '../database/database.module'; 5 | import { AuthController } from './auth.controller'; 6 | import { AuthService } from './auth.service'; 7 | import { JwtStrategy } from './strategies/jwt.strategy'; 8 | import { LocalStrategy } from './strategies/local.strategy'; 9 | import { UsersModule } from './users/users.module'; 10 | 11 | @Module({ 12 | imports: [ 13 | DatabaseModule, 14 | UsersModule, 15 | JwtModule.registerAsync({ 16 | useFactory: (configService: ConfigService) => ({ 17 | secret: configService.get('JWT_SECRET'), 18 | signOptions: { 19 | expiresIn: `${configService.get('JWT_EXPIRATION')}s`, 20 | }, 21 | }), 22 | inject: [ConfigService], 23 | }), 24 | ], 25 | controllers: [AuthController], 26 | providers: [AuthService, LocalStrategy, JwtStrategy], 27 | }) 28 | export class AuthModule {} 29 | -------------------------------------------------------------------------------- /src/auth/auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AuthService } from './auth.service'; 3 | 4 | describe('AuthService', () => { 5 | let service: AuthService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [AuthService], 10 | }).compile(); 11 | 12 | service = module.get(AuthService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { ConfigService } from '@nestjs/config'; 3 | import { JwtService } from '@nestjs/jwt'; 4 | import { Response } from 'express'; 5 | import { User } from './users/models/user.model'; 6 | 7 | export interface TokenPayload { 8 | userId: string; 9 | } 10 | 11 | @Injectable() 12 | export class AuthService { 13 | constructor( 14 | private readonly configService: ConfigService, 15 | private readonly jwtService: JwtService, 16 | ) {} 17 | 18 | async login(user: User, response: Response) { 19 | const tokenPayload: TokenPayload = { 20 | userId: user._id, 21 | }; 22 | 23 | const expires = new Date(); 24 | expires.setSeconds( 25 | expires.getSeconds() + this.configService.get('JWT_EXPIRATION'), 26 | ); 27 | 28 | const token = this.jwtService.sign(tokenPayload); 29 | 30 | response.cookie('Authentication', token, { 31 | httpOnly: true, 32 | expires, 33 | }); 34 | } 35 | 36 | logout(response: Response) { 37 | response.cookie('Authentication', '', { 38 | httpOnly: true, 39 | expires: new Date(), 40 | }); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/auth/current-user.decorator.ts: -------------------------------------------------------------------------------- 1 | import { createParamDecorator, ExecutionContext } from '@nestjs/common'; 2 | import { GqlExecutionContext } from '@nestjs/graphql'; 3 | import { User } from './users/models/user.model'; 4 | 5 | export const getCurrentUserByContext = (context: ExecutionContext): User => { 6 | if (context.getType() === 'http') { 7 | return context.switchToHttp().getRequest().user; 8 | } 9 | if ((context.getType() as any) === 'graphql') { 10 | const ctx = GqlExecutionContext.create(context); 11 | return ctx.getContext().req.user; 12 | } 13 | }; 14 | 15 | export const CurrentUser = createParamDecorator( 16 | (_data: unknown, context: ExecutionContext) => 17 | getCurrentUserByContext(context), 18 | ); 19 | -------------------------------------------------------------------------------- /src/auth/guards/gql-auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { ExecutionContext } from '@nestjs/common'; 2 | import { GqlExecutionContext } from '@nestjs/graphql'; 3 | import { AuthGuard } from '@nestjs/passport'; 4 | 5 | export class GqlAuthGuard extends AuthGuard('jwt') { 6 | getRequest(context: ExecutionContext) { 7 | const ctx = GqlExecutionContext.create(context); 8 | return ctx.getContext().req; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/auth/guards/jwt-auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { AuthGuard } from '@nestjs/passport'; 2 | 3 | export default class JwtAuthGuard extends AuthGuard('jwt') {} 4 | -------------------------------------------------------------------------------- /src/auth/guards/local-auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { AuthGuard } from '@nestjs/passport'; 2 | 3 | export class LocalAuthGuard extends AuthGuard('local') {} 4 | -------------------------------------------------------------------------------- /src/auth/strategies/jwt.strategy.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, UnauthorizedException } from '@nestjs/common'; 2 | import { ConfigService } from '@nestjs/config'; 3 | import { PassportStrategy } from '@nestjs/passport'; 4 | import { ExtractJwt, Strategy } from 'passport-jwt'; 5 | import { TokenPayload } from '../auth.service'; 6 | import { UsersService } from '../users/users.service'; 7 | 8 | @Injectable() 9 | export class JwtStrategy extends PassportStrategy(Strategy) { 10 | constructor( 11 | configService: ConfigService, 12 | private readonly usersService: UsersService, 13 | ) { 14 | super({ 15 | jwtFromRequest: ExtractJwt.fromExtractors([ 16 | (request: any) => { 17 | return request?.cookies?.Authentication; 18 | }, 19 | ]), 20 | secretOrKey: configService.get('JWT_SECRET'), 21 | }); 22 | } 23 | 24 | async validate({ userId }: TokenPayload) { 25 | try { 26 | return await this.usersService.getUser({ 27 | _id: userId, 28 | }); 29 | } catch (err) { 30 | throw new UnauthorizedException(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/auth/strategies/local.strategy.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { PassportStrategy } from '@nestjs/passport'; 3 | import { Strategy } from 'passport-local'; 4 | import { UsersService } from '../users/users.service'; 5 | 6 | @Injectable() 7 | export class LocalStrategy extends PassportStrategy(Strategy) { 8 | constructor(private readonly usersService: UsersService) { 9 | super({ usernameField: 'email' }); 10 | } 11 | 12 | async validate(email: string, password: string) { 13 | return this.usersService.validateUser(email, password); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/auth/users/dto/create-user.input.ts: -------------------------------------------------------------------------------- 1 | import { Field, InputType } from '@nestjs/graphql'; 2 | import { IsEmail, IsNotEmpty, IsString } from 'class-validator'; 3 | 4 | @InputType() 5 | export class CreateUserInput { 6 | @Field() 7 | @IsEmail() 8 | email: string; 9 | 10 | @Field() 11 | @IsString() 12 | @IsNotEmpty() 13 | password: string; 14 | } 15 | -------------------------------------------------------------------------------- /src/auth/users/models/user.model.ts: -------------------------------------------------------------------------------- 1 | import { Field, ID, ObjectType } from '@nestjs/graphql'; 2 | 3 | @ObjectType() 4 | export class User { 5 | @Field(() => ID) 6 | _id: string; 7 | 8 | @Field() 9 | email: string; 10 | } 11 | -------------------------------------------------------------------------------- /src/auth/users/models/user.schema.ts: -------------------------------------------------------------------------------- 1 | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; 2 | import { AbstractDocument } from '../../../database/abstract.schema'; 3 | 4 | @Schema({ versionKey: false }) 5 | export class UserDocument extends AbstractDocument { 6 | @Prop() 7 | email: string; 8 | 9 | @Prop() 10 | password: string; 11 | } 12 | 13 | export const UserSchema = SchemaFactory.createForClass(UserDocument); 14 | -------------------------------------------------------------------------------- /src/auth/users/users.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { UsersRepository } from './users.repository'; 3 | import { UsersService } from './users.service'; 4 | import { MongooseModule } from '@nestjs/mongoose'; 5 | import { User } from './models/user.model'; 6 | import { UserSchema } from './models/user.schema'; 7 | import { UsersResolver } from './users.resolver'; 8 | 9 | @Module({ 10 | imports: [ 11 | MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]), 12 | ], 13 | providers: [UsersService, UsersRepository, UsersResolver], 14 | exports: [UsersService], 15 | }) 16 | export class UsersModule {} 17 | -------------------------------------------------------------------------------- /src/auth/users/users.repository.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Logger } from '@nestjs/common'; 2 | import { InjectConnection, InjectModel } from '@nestjs/mongoose'; 3 | import { Model, Connection } from 'mongoose'; 4 | import { AbstractRepository } from '../../database/abstract.repository'; 5 | import { User } from './models/user.model'; 6 | import { UserDocument } from './models/user.schema'; 7 | 8 | @Injectable() 9 | export class UsersRepository extends AbstractRepository { 10 | protected readonly logger = new Logger(UsersRepository.name); 11 | 12 | constructor( 13 | @InjectModel(User.name) userModel: Model, 14 | @InjectConnection() connection: Connection, 15 | ) { 16 | super(userModel, connection); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/auth/users/users.resolver.ts: -------------------------------------------------------------------------------- 1 | import { UseGuards } from '@nestjs/common'; 2 | import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; 3 | import { CurrentUser } from '../current-user.decorator'; 4 | import { GqlAuthGuard } from '../guards/gql-auth.guard'; 5 | import { CreateUserInput } from './dto/create-user.input'; 6 | import { User } from './models/user.model'; 7 | import { UsersService } from './users.service'; 8 | 9 | @Resolver(() => User) 10 | export class UsersResolver { 11 | constructor(private readonly usersService: UsersService) {} 12 | 13 | @Mutation(() => User) 14 | async createUser(@Args('createUserData') createUserData: CreateUserInput) { 15 | return this.usersService.createUser(createUserData); 16 | } 17 | 18 | @UseGuards(GqlAuthGuard) 19 | @Query(() => User, { name: 'me' }) 20 | getMe(@CurrentUser() user: User) { 21 | return user; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/auth/users/users.service.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Injectable, 3 | UnauthorizedException, 4 | UnprocessableEntityException, 5 | } from '@nestjs/common'; 6 | import * as bcrypt from 'bcrypt'; 7 | import { UsersRepository } from './users.repository'; 8 | import { CreateUserInput } from './dto/create-user.input'; 9 | import { UserDocument } from './models/user.schema'; 10 | import { User } from './models/user.model'; 11 | 12 | @Injectable() 13 | export class UsersService { 14 | constructor(private readonly usersRepository: UsersRepository) {} 15 | 16 | async createUser(data: CreateUserInput) { 17 | await this.validateCreateUserData(data); 18 | const userDocument = await this.usersRepository.create({ 19 | ...data, 20 | password: await bcrypt.hash(data.password, 10), 21 | }); 22 | return this.getUserFromDocument(userDocument); 23 | } 24 | 25 | private async validateCreateUserData(data: CreateUserInput) { 26 | let userDocument: UserDocument; 27 | try { 28 | userDocument = await this.usersRepository.findOne({ 29 | email: data.email, 30 | }); 31 | } catch (err) {} 32 | 33 | if (userDocument) { 34 | throw new UnprocessableEntityException('Email already exists.'); 35 | } 36 | } 37 | 38 | async validateUser(email: string, password: string) { 39 | const user = await this.usersRepository.findOne({ email }); 40 | const passwordIsValid = await bcrypt.compare(password, user.password); 41 | if (!passwordIsValid) { 42 | throw new UnauthorizedException('Credentials are not valid.'); 43 | } 44 | return user; 45 | } 46 | 47 | async getUser(args: Partial) { 48 | const userDocument = await this.usersRepository.findOne(args); 49 | return this.getUserFromDocument(userDocument); 50 | } 51 | 52 | private getUserFromDocument(userDocument: UserDocument): User { 53 | return { 54 | _id: userDocument._id.toHexString(), 55 | email: userDocument.email, 56 | }; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/database/abstract.repository.ts: -------------------------------------------------------------------------------- 1 | import { Logger, NotFoundException } from '@nestjs/common'; 2 | import { 3 | FilterQuery, 4 | Model, 5 | Types, 6 | UpdateQuery, 7 | SaveOptions, 8 | Connection, 9 | } from 'mongoose'; 10 | import { AbstractDocument } from './abstract.schema'; 11 | 12 | export abstract class AbstractRepository { 13 | protected abstract readonly logger: Logger; 14 | 15 | constructor( 16 | protected readonly model: Model, 17 | private readonly connection: Connection, 18 | ) {} 19 | 20 | async create( 21 | document: Omit, 22 | options?: SaveOptions, 23 | ): Promise { 24 | const createdDocument = new this.model({ 25 | ...document, 26 | _id: new Types.ObjectId(), 27 | }); 28 | return ( 29 | await createdDocument.save(options) 30 | ).toJSON() as unknown as TDocument; 31 | } 32 | 33 | async findOne(filterQuery: FilterQuery): Promise { 34 | const document = await this.model.findOne(filterQuery, {}, { lean: true }); 35 | 36 | if (!document) { 37 | this.logger.warn('Document not found with filterQuery', filterQuery); 38 | throw new NotFoundException('Document not found.'); 39 | } 40 | 41 | return document; 42 | } 43 | 44 | async findOneAndUpdate( 45 | filterQuery: FilterQuery, 46 | update: UpdateQuery, 47 | ) { 48 | const document = await this.model.findOneAndUpdate(filterQuery, update, { 49 | lean: true, 50 | new: true, 51 | }); 52 | 53 | if (!document) { 54 | this.logger.warn(`Document not found with filterQuery:`, filterQuery); 55 | throw new NotFoundException('Document not found.'); 56 | } 57 | 58 | return document; 59 | } 60 | 61 | async upsert( 62 | filterQuery: FilterQuery, 63 | document: Partial, 64 | ) { 65 | return this.model.findOneAndUpdate(filterQuery, document, { 66 | lean: true, 67 | upsert: true, 68 | new: true, 69 | }); 70 | } 71 | 72 | async find(filterQuery: FilterQuery) { 73 | return this.model.find(filterQuery, {}, { lean: true }); 74 | } 75 | 76 | async startTransaction() { 77 | const session = await this.connection.startSession(); 78 | session.startTransaction(); 79 | return session; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/database/abstract.schema.ts: -------------------------------------------------------------------------------- 1 | import { Prop, Schema } from '@nestjs/mongoose'; 2 | import { SchemaTypes, Types } from 'mongoose'; 3 | 4 | @Schema() 5 | export class AbstractDocument { 6 | @Prop({ type: SchemaTypes.ObjectId }) 7 | _id: Types.ObjectId; 8 | } 9 | -------------------------------------------------------------------------------- /src/database/database.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { ConfigService } from '@nestjs/config'; 3 | import { MongooseModule } from '@nestjs/mongoose'; 4 | 5 | @Module({ 6 | imports: [ 7 | MongooseModule.forRootAsync({ 8 | useFactory: (configService: ConfigService) => ({ 9 | uri: configService.get('MONGODB_URI'), 10 | }), 11 | inject: [ConfigService], 12 | }), 13 | ], 14 | }) 15 | export class DatabaseModule {} 16 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { ValidationPipe } from '@nestjs/common'; 2 | import { ConfigService } from '@nestjs/config'; 3 | import { NestFactory } from '@nestjs/core'; 4 | import * as cookieParser from 'cookie-parser'; 5 | import { AppModule } from './app.module'; 6 | 7 | async function bootstrap() { 8 | const app = await NestFactory.create(AppModule); 9 | 10 | app.use(cookieParser()); 11 | app.useGlobalPipes(new ValidationPipe()); 12 | 13 | const configService = app.get(ConfigService); 14 | const port = configService.get('PORT'); 15 | 16 | await app.listen(port); 17 | } 18 | bootstrap(); 19 | -------------------------------------------------------------------------------- /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 | "skipLibCheck": true, 15 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false 20 | } 21 | } 22 | --------------------------------------------------------------------------------