├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── .vscode └── settings.json ├── README.md ├── docker-compose.yml ├── nest-cli.json ├── package-lock.json ├── package.json ├── src ├── app.controller.ts ├── app.module.ts ├── app.service.ts ├── auth │ ├── auth.controller.ts │ ├── auth.module.ts │ ├── auth.service.ts │ ├── constant.ts │ ├── decorator.ts │ ├── guards │ │ ├── google.auth.guard.ts │ │ ├── gql.auth.guard.ts │ │ ├── jwt.auth.guard.ts │ │ └── local.auth.guard.ts │ └── strategy │ │ ├── google.strategy.ts │ │ ├── jwt.strategy.ts │ │ └── local.strategy.ts ├── cars │ ├── car.entity.ts │ ├── cars.module.ts │ ├── cars.resolver.ts │ ├── cars.service.ts │ └── dto │ │ ├── car-dto.ts │ │ └── index.ts ├── main.ts ├── schema.gql └── user │ ├── dto │ └── create-user-dto.ts │ ├── entity │ └── user.entity.ts │ ├── user.controller.ts │ ├── user.module.ts │ └── user.service.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | tsconfigRootDir: __dirname, 6 | sourceType: 'module', 7 | }, 8 | plugins: ['@typescript-eslint/eslint-plugin'], 9 | extends: [ 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | ignorePatterns: ['.eslintrc.js'], 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/explicit-module-boundary-types': 'off', 23 | '@typescript-eslint/no-explicit-any': 'off', 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /.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 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "ghasedak", 4 | "nestjs", 5 | "phpmyadmin", 6 | "Sadra", 7 | "signin", 8 | "sjqf", 9 | "typeorm" 10 | ] 11 | } -------------------------------------------------------------------------------- /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 | # nestjs-graphql 75 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | db: 5 | image: mysql 6 | command: --default-authentication-plugin=mysql_native_password 7 | environment: 8 | MYSQL_ROOT_PASSWORD: '!Sadra35289546' 9 | MYSQL_DATABASE: 'cars' 10 | MYSQL_USER: 'phpmyadmin' 11 | MYSQL_PASSWORD: '!Sadra35289546' 12 | ports: 13 | - 30306:30306 14 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src", 5 | "compilerOptions": { 6 | "deleteOutDir": true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "graphql", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "build": "nest build", 10 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 11 | "start": "nest start", 12 | "start:dev": "nest start --watch", 13 | "start:debug": "nest start --debug --watch", 14 | "start:prod": "node dist/main", 15 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 16 | "test": "jest", 17 | "test:watch": "jest --watch", 18 | "test:cov": "jest --coverage", 19 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 20 | "test:e2e": "jest --config ./test/jest-e2e.json" 21 | }, 22 | "dependencies": { 23 | "@nestjs/apollo": "^12.0.9", 24 | "@nestjs/common": "^10.0.0", 25 | "@nestjs/config": "^3.1.1", 26 | "@nestjs/core": "^10.0.0", 27 | "@nestjs/graphql": "^12.0.9", 28 | "@nestjs/jwt": "^10.2.0", 29 | "@nestjs/mapped-types": "*", 30 | "@nestjs/passport": "^10.0.2", 31 | "@nestjs/platform-express": "^10.0.0", 32 | "@nestjs/typeorm": "^10.0.0", 33 | "@types/passport-google-oauth20": "^2.0.14", 34 | "@types/passport-jwt": "^3.0.9", 35 | "apollo-server-express": "^3.12.1", 36 | "argon2": "^0.31.2", 37 | "class-transformer": "^0.5.1", 38 | "class-validator": "^0.14.0", 39 | "graphql": "^16.8.0", 40 | "graphql-tools": "^9.0.0", 41 | "jsonwebtoken": "^9.0.2", 42 | "mysql2": "^2.3.3", 43 | "passport-jwt": "^4.0.1", 44 | "passport-local": "^1.0.0", 45 | "reflect-metadata": "^0.1.13", 46 | "rxjs": "^7.8.1", 47 | "sqlite3": "^5.1.6", 48 | "typeorm": "^0.3.17" 49 | }, 50 | "devDependencies": { 51 | "@nestjs/cli": "^10.0.0", 52 | "@nestjs/schematics": "^10.0.0", 53 | "@nestjs/testing": "^10.0.0", 54 | "@types/bcrypt": "^5.0.2", 55 | "@types/express": "^4.17.17", 56 | "@types/jest": "^29.5.2", 57 | "@types/node": "^20.3.1", 58 | "@types/passport-google-oauth2": "^0.1.8", 59 | "@types/supertest": "^2.0.12", 60 | "@typescript-eslint/eslint-plugin": "^6.0.0", 61 | "@typescript-eslint/parser": "^6.0.0", 62 | "base64url": "^3.0.1", 63 | "bcrypt": "^5.1.1", 64 | "eslint": "^8.42.0", 65 | "eslint-config-prettier": "^9.0.0", 66 | "eslint-plugin-prettier": "^5.0.0", 67 | "ghasedak": "^0.2.1", 68 | "jest": "^29.5.0", 69 | "passport-google-oauth2": "^0.2.0", 70 | "prettier": "^3.0.0", 71 | "source-map-support": "^0.5.21", 72 | "supertest": "^6.3.3", 73 | "ts-jest": "^29.1.0", 74 | "ts-loader": "^9.4.3", 75 | "ts-node": "^10.9.1", 76 | "tsconfig-paths": "^4.2.0", 77 | "typescript": "^5.1.3" 78 | }, 79 | "jest": { 80 | "moduleFileExtensions": [ 81 | "js", 82 | "json", 83 | "ts" 84 | ], 85 | "rootDir": "src", 86 | "testRegex": ".*\\.spec\\.ts$", 87 | "transform": { 88 | "^.+\\.(t|j)s$": "ts-jest" 89 | }, 90 | "collectCoverageFrom": [ 91 | "**/*.(t|j)s" 92 | ], 93 | "coverageDirectory": "../coverage", 94 | "testEnvironment": "node" 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get } from '@nestjs/common'; 2 | import { AppService } from './app.service'; 3 | 4 | @Controller() 5 | export class AppController { 6 | constructor(private readonly appService: AppService) {} 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | import { CarsModule } from './cars/cars.module'; 5 | import { GraphQLModule } from '@nestjs/graphql'; 6 | import { join } from 'path'; 7 | import { ApolloDriver } from '@nestjs/apollo'; 8 | import { TypeOrmModule } from '@nestjs/typeorm'; 9 | import { CarEntity } from './cars/car.entity'; 10 | import { AuthModule } from './auth/auth.module'; 11 | import { UserModule } from './user/user.module'; 12 | import { UserEntity } from './user/entity/user.entity'; 13 | 14 | @Module({ 15 | imports: [ 16 | CarsModule, 17 | //PassportModule.register({ defaultStrategy: 'jwt' }), 18 | GraphQLModule.forRoot({ 19 | driver: ApolloDriver, 20 | autoSchemaFile: join(process.cwd(), "src/schema.gql") 21 | }), 22 | TypeOrmModule.forRoot({ 23 | type: "mysql", 24 | database: "cars", 25 | host: "localhost", 26 | username: "phpmyadmin", 27 | password: "!Sadra35289546", 28 | entities: [ 29 | CarEntity, 30 | UserEntity 31 | ], 32 | port: 3306, 33 | synchronize: true, 34 | }), 35 | AuthModule, 36 | UserModule, 37 | // JwtModule.register({ 38 | // global: true, 39 | // secret: "secret", 40 | // signOptions: { 41 | // expiresIn: '1d' 42 | // }, 43 | //}), 44 | ], 45 | controllers: [AppController], 46 | providers: [AppService], 47 | }) 48 | export class AppModule { 49 | 50 | } 51 | 52 | 53 | -------------------------------------------------------------------------------- /src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class AppService { 5 | 6 | } 7 | -------------------------------------------------------------------------------- /src/auth/auth.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Post, Redirect, Req, Res, UseGuards } from '@nestjs/common'; 2 | import { AuthService } from './auth.service'; 3 | import { Request, Response } from 'express'; 4 | import { UserService } from 'src/user/user.service'; 5 | import { LocalAuthGuard } from './guards/local.auth.guard'; 6 | import { GoogleAuthGuard } from './guards/google.auth.guard'; 7 | 8 | @Controller('auth') 9 | export class AuthController { 10 | constructor( 11 | private authService: AuthService, 12 | private userService: UserService 13 | ) { } 14 | 15 | @Get('google') 16 | @UseGuards(GoogleAuthGuard) 17 | auth() { 18 | return 19 | } 20 | 21 | @Get('google/callback') 22 | @UseGuards(GoogleAuthGuard) 23 | async googleCallback(@Req() req: Request) { 24 | return this.authService.handleGoogleAuth(req.user); 25 | } 26 | 27 | 28 | @Post('login') 29 | @UseGuards(LocalAuthGuard) 30 | login(@Req() req: Request) { 31 | console.log(req); 32 | return this.authService.login(req.user) 33 | } 34 | 35 | @Get("sms") 36 | otp() { 37 | return this.authService.authByOtp(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AuthService } from './auth.service'; 3 | import { JwtStrategy } from './strategy/jwt.strategy'; 4 | import { LocalStrategy } from './strategy/local.strategy'; 5 | import { PassportModule } from '@nestjs/passport'; 6 | import { JwtModule } from '@nestjs/jwt'; 7 | import { JWT_SECRET } from './constant'; 8 | import { AuthController } from './auth.controller'; 9 | import { UserModule } from 'src/user/user.module'; 10 | import { GoogleStrategy } from './strategy/google.strategy'; 11 | 12 | 13 | @Module({ 14 | imports: [ 15 | UserModule, 16 | PassportModule.register({ defaultStrategy: ['jwt', 'google'] }), 17 | JwtModule.register({ 18 | secret: JWT_SECRET, 19 | signOptions: { expiresIn: 3600 } 20 | }) 21 | ], 22 | providers: [AuthService, JwtStrategy, LocalStrategy, GoogleStrategy], 23 | controllers: [AuthController] 24 | }) 25 | export class AuthModule { } 26 | -------------------------------------------------------------------------------- /src/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, UnauthorizedException } from '@nestjs/common'; 2 | import { UserService } from 'src/user/user.service'; 3 | import { JWT_SECRET, SMS_API_KEY, User } from './constant'; 4 | import { JwtService } from "@nestjs/jwt" 5 | import * as bcrypt from "bcrypt" 6 | import * as Ghasedak from 'ghasedak'; 7 | @Injectable() 8 | export class AuthService { 9 | constructor( 10 | private userService: UserService, 11 | private jwtService: JwtService 12 | ) { } 13 | async validate( 14 | email: string, password: string 15 | ): Promise { 16 | const user = await this.userService.findUser(email); 17 | if (!user) throw new UnauthorizedException(); 18 | const isPasswordValid = await bcrypt.compare(password, user.password) 19 | return isPasswordValid ? user : null; 20 | } 21 | login( 22 | user: any 23 | ): { accessToken: string } { 24 | const payload = { 25 | email: user.email, 26 | sub: user.id 27 | } 28 | const jwtToken = this.jwtService.sign(payload); 29 | return { 30 | accessToken: jwtToken 31 | } 32 | } 33 | async verify( 34 | jwtToken: string 35 | ): Promise { 36 | const decode = this.jwtService.verify<{ email: string, sub: string }>( 37 | jwtToken, 38 | { secret: JWT_SECRET } 39 | ); 40 | const user = await this.userService.findUser(decode.email); 41 | if (!user) throw new UnauthorizedException(); 42 | return user; 43 | } 44 | async handleGoogleAuth(user: any) { 45 | const { accessToken } = this.login(user); 46 | return { 47 | accessToken, 48 | msg: "authenticate success " 49 | } 50 | } 51 | async authByOtp() { 52 | const otpSender = new Ghasedak(SMS_API_KEY) 53 | const smsOption = { 54 | message: "123456", 55 | receptor: "09162844007" 56 | } 57 | otpSender.send(smsOption); 58 | return; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/auth/constant.ts: -------------------------------------------------------------------------------- 1 | export class User { 2 | 3 | id: string 4 | email: string 5 | password?: string 6 | phone?: string 7 | cars?: string[] 8 | otp?:string 9 | 10 | } 11 | 12 | export const JWT_SECRET = "k2cy4NSbBpWQhuEwjkIG6lS"; 13 | 14 | export const GOOGLE_CLIENT_ID = "435383785262-hb1fn4tbtkck0sjqf8ar2e124bsq6tas.apps.googleusercontent.com" 15 | export const GOOGLE_CLIENT_SECRET = "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"; 16 | export const GOOGLE_CALLBACK_URL = "http://localhost:3000/auth/google/callback"; 17 | 18 | export const SMS_API_KEY = "2f3238e0cc31c1f0c0a1c7e9c96fd695a1f1091e2ae7c6d844b81ac9083a725e" ; -------------------------------------------------------------------------------- /src/auth/decorator.ts: -------------------------------------------------------------------------------- 1 | import { ExecutionContext, createParamDecorator } from "@nestjs/common"; 2 | import { GqlExecutionContext } from "@nestjs/graphql"; 3 | 4 | export const CurrentUser = createParamDecorator( 5 | (data: any, context: ExecutionContext) => { 6 | if (context.getType() == 'http') { 7 | return context.switchToHttp().getRequest().user; 8 | } 9 | const ctx = GqlExecutionContext.create(context); 10 | return ctx.getContext().req.user; 11 | }) -------------------------------------------------------------------------------- /src/auth/guards/google.auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from "@nestjs/common"; 2 | import { AuthGuard } from "@nestjs/passport"; 3 | 4 | @Injectable() 5 | export class GoogleAuthGuard extends AuthGuard('google') { } -------------------------------------------------------------------------------- /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): any { 7 | const ctx = GqlExecutionContext.create(context); 8 | return ctx.getContext().req; 9 | } 10 | } -------------------------------------------------------------------------------- /src/auth/guards/jwt.auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { AuthGuard } from "@nestjs/passport"; 2 | 3 | export class JwtAuthGuard extends AuthGuard("jwt") { } -------------------------------------------------------------------------------- /src/auth/guards/local.auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { AuthGuard } from "@nestjs/passport" 2 | 3 | export class LocalAuthGuard extends AuthGuard("local") { } -------------------------------------------------------------------------------- /src/auth/strategy/google.strategy.ts: -------------------------------------------------------------------------------- 1 | import { PassportStrategy } from "@nestjs/passport"; 2 | import { Strategy, VerifyCallback } from "passport-google-oauth2"; 3 | import { UserService } from "src/user/user.service"; 4 | import { GOOGLE_CALLBACK_URL, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET } from "../constant"; 5 | import { BadRequestException, Injectable } from "@nestjs/common"; 6 | import { JwtService } from "@nestjs/jwt"; 7 | import { AuthService } from "../auth.service"; 8 | 9 | @Injectable() 10 | export class GoogleStrategy extends PassportStrategy(Strategy, 'google') { 11 | constructor( 12 | private readonly userService: UserService, 13 | private readonly authService: AuthService, 14 | private jwtService: JwtService 15 | ) { 16 | super({ 17 | clientID: GOOGLE_CLIENT_ID, 18 | clientSecret: GOOGLE_CLIENT_SECRET, 19 | callbackURL: GOOGLE_CALLBACK_URL, 20 | scope: ['profile', 'email'] 21 | }) 22 | } 23 | async validate( 24 | accessToken: string, 25 | refreshToken: string, 26 | profile: any, 27 | done: VerifyCallback 28 | ) { 29 | const user = await this.userService.createUserByEmail(profile.email); 30 | if (!user) throw new BadRequestException(); 31 | done(null, user); 32 | } 33 | } 34 | 35 | 36 | -------------------------------------------------------------------------------- /src/auth/strategy/jwt.strategy.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from "@nestjs/common"; 2 | import { PassportStrategy } from "@nestjs/passport"; 3 | import { ExtractJwt } from "passport-jwt"; 4 | import { Strategy } from "passport-local" 5 | import { UserService } from '../../user/user.service'; 6 | import { JWT_SECRET, User } from "../constant"; 7 | 8 | @Injectable() 9 | export class JwtStrategy extends PassportStrategy(Strategy) { 10 | constructor( 11 | private userService: UserService 12 | ) { 13 | super({ 14 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 15 | ignoreExpires: false, 16 | secretOrKey: JWT_SECRET 17 | }) 18 | } 19 | async validate( 20 | validationPayload: { email: string, sub: string } 21 | ): Promise { 22 | return await this.userService.findUser(validationPayload.email); 23 | } 24 | } -------------------------------------------------------------------------------- /src/auth/strategy/local.strategy.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from "@nestjs/common"; 2 | import { PassportStrategy } from "@nestjs/passport" 3 | import { Strategy } from "passport-local"; 4 | import { AuthService } from "../auth.service"; 5 | import { User } from "../constant"; 6 | 7 | @Injectable() 8 | export class LocalStrategy extends PassportStrategy(Strategy) { 9 | constructor( 10 | private authService: AuthService 11 | ) { 12 | super({ usernameField: 'email' }) 13 | } 14 | async validate(email: string, password: string): Promise { 15 | const user = await this.authService.validate(email, password); 16 | return user; 17 | } 18 | } -------------------------------------------------------------------------------- /src/cars/car.entity.ts: -------------------------------------------------------------------------------- 1 | import { Field, ObjectType } from "@nestjs/graphql"; 2 | import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm"; 3 | 4 | @Entity({ name: "CarEntity" }) 5 | @ObjectType() 6 | export class CarEntity extends BaseEntity { 7 | @PrimaryGeneratedColumn() 8 | @Field(type => String) 9 | id: string; 10 | 11 | @Column({ type: String }) 12 | @Field(type => String, 13 | { description: "the name of company" }) 14 | maker: string; 15 | 16 | @Column({ type: String }) 17 | @Field( 18 | type => String, 19 | { description: "the name of car model" } 20 | ) 21 | model: string; 22 | 23 | @Column({ type: Number }) 24 | @Field( 25 | type => Number, 26 | { description: "the price of car" } 27 | ) 28 | price: number; 29 | 30 | @Column( 31 | { type: String, nullable: true } 32 | ) 33 | @Field( 34 | type => String, 35 | { 36 | nullable: true, 37 | description: "type of car like 'SUV','coupe','sedan',''etc " 38 | } 39 | ) 40 | type?: "SUV" | "coupe" | "sedan" | "etc"; 41 | 42 | @Column({ type: String, nullable: true }) 43 | @Field( 44 | type => String, 45 | { nullable: true } 46 | ) 47 | description?: string; 48 | 49 | // @Column({ type: String}) 50 | // @Field(type => String) 51 | // owner: string; 52 | } -------------------------------------------------------------------------------- /src/cars/cars.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { CarsService } from './cars.service'; 3 | import { CarsResolver } from './cars.resolver'; 4 | import { TypeOrmModule } from '@nestjs/typeorm'; 5 | import { CarEntity } from './car.entity'; 6 | 7 | @Module({ 8 | imports: [ 9 | TypeOrmModule.forFeature([CarEntity]), 10 | ], 11 | providers: [ 12 | CarsService, 13 | CarsResolver, 14 | ] 15 | }) 16 | export class CarsModule { } 17 | -------------------------------------------------------------------------------- /src/cars/cars.resolver.ts: -------------------------------------------------------------------------------- 1 | import { Args, Context, Mutation, Query, Resolver } from '@nestjs/graphql'; 2 | import { CarsService } from './cars.service'; 3 | import { CarEntity } from './car.entity'; 4 | import { CreateCarDto, FindCarDto, GetCarByModelDto, UpdateCarDto } from './dto/car-dto'; 5 | import { Req, UseGuards } from '@nestjs/common'; 6 | 7 | @Resolver(of => CarEntity) 8 | export class CarsResolver { 9 | constructor(private carsService: CarsService) { } 10 | 11 | @Mutation(returns => CarEntity) 12 | createCar( 13 | @Context() ctx: any, 14 | @Args("createCarDto") 15 | createdCarDto: CreateCarDto): Promise { 16 | return this.carsService.create(createdCarDto, ctx); 17 | } 18 | @Query(returns => [CarEntity]) 19 | getCars(): Promise { 20 | return this.carsService.findAll(); 21 | } 22 | 23 | @Mutation(returns => CarEntity) 24 | getCarById(@Args("findCarDto") findCarDto: FindCarDto): Promise { 25 | return this.carsService.findById(findCarDto); 26 | } 27 | 28 | @Mutation(returns => CarEntity) 29 | removeCar(@Args("removeCarDto") removeCarDto: FindCarDto): Promise { 30 | return this.carsService.removeById(removeCarDto); 31 | } 32 | 33 | @Mutation(returns => CarEntity) 34 | updateCar(@Args("updateCarDto") updateCarDto: UpdateCarDto): Promise { 35 | return this.carsService.editCar(updateCarDto); 36 | } 37 | 38 | @Query(returns => [CarEntity]) 39 | getCarByModel(@Args("getCarByModel") getCarByModelDto: GetCarByModelDto): Promise { 40 | return this.carsService.getCarByModel(getCarByModelDto); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/cars/cars.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, InternalServerErrorException, NotFoundException, UseGuards } from '@nestjs/common'; 2 | import { CarEntity } from './car.entity'; 3 | import { InjectRepository } from '@nestjs/typeorm'; 4 | import { Repository } from 'typeorm'; 5 | import { CreateCarDto, FindCarDto, GetCarByModelDto, UpdateCarDto } from './dto'; 6 | @Injectable() 7 | export class CarsService { 8 | constructor( 9 | @InjectRepository(CarEntity) 10 | private readonly carRepository: Repository, 11 | ) { } 12 | async create(createCarDto: CreateCarDto, ctx: any): Promise { 13 | // const ownerId = ctx.req.user.id 14 | // createCarDto.owner = ownerId; 15 | console.log(createCarDto); 16 | const car = this.carRepository.create(createCarDto); 17 | await this.carRepository.save(car); 18 | if (!car) throw new InternalServerErrorException("can not create car "); 19 | return car; 20 | } 21 | async findAll(): Promise { 22 | const cars = await this.carRepository.find(); 23 | return cars 24 | } 25 | 26 | async findById(findCarDto: FindCarDto): Promise { 27 | const car = await this.carRepository.findOne({ where: { id: String(findCarDto.id) } }); 28 | if (!car) throw new NotFoundException("car not found with this id "); 29 | return car; 30 | } 31 | async removeById(removeCarDto: FindCarDto): Promise { 32 | const car = await this.carRepository.findOne({ where: { id: String(removeCarDto.id) } }) 33 | await this.carRepository.delete({ id: String(removeCarDto.id) }) 34 | return car; 35 | } 36 | async editCar(updateCarDto: UpdateCarDto): Promise { 37 | const carProperty = await this.carRepository.findOne({ where: { id: updateCarDto.id } }); 38 | delete updateCarDto.id; 39 | const car = await this.carRepository.save({ 40 | id: updateCarDto.id, 41 | ...carProperty, 42 | ...updateCarDto 43 | }) 44 | return car 45 | } 46 | async getCarByModel(getCarByModelDto: GetCarByModelDto) { 47 | return await this.carRepository.find(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/cars/dto/car-dto.ts: -------------------------------------------------------------------------------- 1 | import { Field, InputType, Int, ObjectType } from "@nestjs/graphql"; 2 | import { IsEmpty, IsNotEmpty, IsNumber, IsString, ValidateIf } from "class-validator" 3 | import { Entity } from "typeorm"; 4 | 5 | @InputType() 6 | export class CreateCarDto { 7 | 8 | @Field(type => String) 9 | @IsString() 10 | @IsNotEmpty() 11 | maker: string; 12 | 13 | @Field(type => String) 14 | @IsString() 15 | @IsNotEmpty() 16 | model: string; 17 | 18 | @Field(type => Int) 19 | @IsNumber() 20 | @IsNotEmpty() 21 | price: number; 22 | 23 | @Field(type => String, { nullable: true }) 24 | @ValidateIf((object, value) => value !== null) 25 | type?: "SUV" | "coupe" | "sedan" | "etc"; 26 | 27 | @Field(type => String, { nullable: true }) 28 | @ValidateIf((object, value) => value !== null) 29 | description?: string; 30 | 31 | // @Field(type => String, { nullable: true }) 32 | // owner: string; 33 | } 34 | @InputType() 35 | export class UpdateCarDto { 36 | @Field(type => String) 37 | id?: string; 38 | 39 | @Field(type => String, { nullable: true }) 40 | @IsString() 41 | maker?: string; 42 | 43 | @Field(type => String, { nullable: true }) 44 | @IsString() 45 | model?: string; 46 | 47 | @Field(type => Int, { nullable: true }) 48 | price?: number; 49 | 50 | @Field(type => String, { nullable: true }) 51 | @ValidateIf((object, value) => value !== null) 52 | type?: "SUV" | "coupe" | "sedan" | "etc"; 53 | 54 | @Field(type => String, { nullable: true }) 55 | @ValidateIf((object, value) => value !== null) 56 | description?: string; 57 | 58 | @Field(type => String, { nullable: true }) 59 | owner: string; 60 | } 61 | 62 | @InputType() 63 | export class FindCarDto { 64 | @Field(type => Number) 65 | @IsNumber() 66 | @IsNotEmpty() 67 | id: number; 68 | } 69 | 70 | @InputType() 71 | export class GetCarByModelDto { 72 | 73 | @Field(type => String, { nullable: true }) 74 | @IsString() 75 | model?: string; 76 | } 77 | 78 | @Entity({ name: "message" }) 79 | @ObjectType() 80 | export class message { 81 | @Field(type => Object) 82 | msg: string 83 | } 84 | -------------------------------------------------------------------------------- /src/cars/dto/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./car-dto" -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | import { BadRequestException, ValidationPipe } from '@nestjs/common'; 4 | import { ValidationError } from 'class-validator'; 5 | 6 | async function bootstrap() { 7 | const app = await NestFactory.create(AppModule); 8 | app.useGlobalPipes(new ValidationPipe({ 9 | exceptionFactory: (validationErrors: ValidationError[] = []) => { 10 | console.error(JSON.stringify(validationErrors)); 11 | return new BadRequestException(validationErrors); 12 | }, 13 | transform: true, 14 | }) 15 | ); 16 | await app.listen(3000); 17 | } 18 | bootstrap(); 19 | -------------------------------------------------------------------------------- /src/schema.gql: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------ 2 | # THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY) 3 | # ------------------------------------------------------ 4 | 5 | type CarEntity { 6 | id: String! 7 | 8 | """the name of company""" 9 | maker: String! 10 | 11 | """the name of car model""" 12 | model: String! 13 | 14 | """the price of car""" 15 | price: Float! 16 | 17 | """type of car like 'SUV','coupe','sedan',''etc """ 18 | type: String 19 | description: String 20 | } 21 | 22 | type Query { 23 | getCars: [CarEntity!]! 24 | getCarByModel(getCarByModel: GetCarByModelDto!): [CarEntity!]! 25 | } 26 | 27 | input GetCarByModelDto { 28 | model: String 29 | } 30 | 31 | type Mutation { 32 | createCar(createCarDto: CreateCarDto!): CarEntity! 33 | getCarById(findCarDto: FindCarDto!): CarEntity! 34 | removeCar(removeCarDto: FindCarDto!): CarEntity! 35 | updateCar(updateCarDto: UpdateCarDto!): CarEntity! 36 | } 37 | 38 | input CreateCarDto { 39 | maker: String! 40 | model: String! 41 | price: Int! 42 | type: String 43 | description: String 44 | } 45 | 46 | input FindCarDto { 47 | id: Float! 48 | } 49 | 50 | input UpdateCarDto { 51 | id: String! 52 | maker: String 53 | model: String 54 | price: Int 55 | type: String 56 | description: String 57 | owner: String 58 | } -------------------------------------------------------------------------------- /src/user/dto/create-user-dto.ts: -------------------------------------------------------------------------------- 1 | import { IsEmpty, IsString } from "class-validator" 2 | 3 | export class CreateUserDto { 4 | 5 | email: string 6 | phone?: string 7 | password?: string 8 | otp?:string 9 | 10 | } -------------------------------------------------------------------------------- /src/user/entity/user.entity.ts: -------------------------------------------------------------------------------- 1 | import { Field, ObjectType } from "@nestjs/graphql"; 2 | import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm"; 3 | 4 | @Entity({ name: "user" }) 5 | @ObjectType() 6 | export class UserEntity extends BaseEntity { 7 | @PrimaryGeneratedColumn() 8 | id: string 9 | 10 | @Column() 11 | email: string 12 | 13 | @Column({ nullable: true }) 14 | phone?: string 15 | 16 | @Column({ nullable: true }) 17 | password?: string 18 | 19 | @Column('simple-array', { nullable: true }) 20 | cars?: string[] 21 | 22 | @Column({nullable:true}) 23 | otp?:string 24 | } -------------------------------------------------------------------------------- /src/user/user.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common'; 2 | import { CreateUserDto } from './dto/create-user-dto'; 3 | import { UserService } from './user.service'; 4 | import { GoogleAuthGuard } from 'src/auth/guards/google.auth.guard'; 5 | import { LocalAuthGuard } from 'src/auth/guards/local.auth.guard'; 6 | import { CurrentUser } from 'src/auth/decorator'; 7 | import { User } from 'src/auth/constant'; 8 | 9 | @Controller('user') 10 | export class UserController { 11 | 12 | constructor(private userService: UserService) { } 13 | @Post('signin') 14 | async createUser(@Body() createUser: CreateUserDto) { 15 | return await this.userService.createUser(createUser); 16 | } 17 | 18 | @Get('list') 19 | @UseGuards(LocalAuthGuard) 20 | async getUsers(@CurrentUser() user: User) { 21 | return await this.userService.getUser(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/user/user.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { UserService } from './user.service'; 3 | import { UserController } from './user.controller'; 4 | import { TypeOrmModule } from '@nestjs/typeorm'; 5 | import { UserEntity } from './entity/user.entity'; 6 | 7 | @Module({ 8 | imports: [ 9 | TypeOrmModule.forFeature([UserEntity]) 10 | ], 11 | exports: [UserService], 12 | providers: [UserService], 13 | controllers: [UserController] 14 | }) 15 | export class UserModule { } 16 | -------------------------------------------------------------------------------- /src/user/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { CreateUserDto } from './dto/create-user-dto'; 3 | import { Repository } from 'typeorm'; 4 | import { UserEntity } from './entity/user.entity'; 5 | import { User } from 'src/auth/constant'; 6 | import * as bcrypt from 'bcrypt'; 7 | import { InjectRepository } from '@nestjs/typeorm'; 8 | 9 | @Injectable() 10 | export class UserService { 11 | constructor( 12 | @InjectRepository(UserEntity) 13 | private readonly userRepository: Repository 14 | ) { } 15 | async createUser(createUserDto: CreateUserDto) { 16 | const hashPassword = bcrypt.hashSync(createUserDto.password, 2); 17 | delete createUserDto.password; 18 | const user = this.userRepository.create( 19 | { ...createUserDto, password: hashPassword } 20 | ); 21 | return await this.userRepository.save(user); 22 | } 23 | async createUserByEmail(email: string) { 24 | return this.userRepository.create({ email }) 25 | } 26 | async updateUser(userId: string, updateUserDto) { 27 | return await this.userRepository.update(userId, updateUserDto); 28 | } 29 | async removeUser(userId: string) { 30 | return await this.userRepository.delete({ id: userId }) 31 | } 32 | async getUser() { 33 | return await this.userRepository.find() 34 | } 35 | async findUser(email: string): Promise { 36 | return await this.userRepository.findOne({ where: { email } }) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /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": "ES2021", 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 | --------------------------------------------------------------------------------