├── .env.example ├── .eslintrc.js ├── .gitignore ├── .husky ├── .gitignore └── pre-commit ├── .prettierrc ├── README.md ├── docker-compose.yml ├── nest-cli.json ├── package.json ├── schema.gql ├── src ├── app.controller.spec.ts ├── app.controller.ts ├── app.module.ts ├── app.service.ts ├── main.ts └── users │ ├── dto │ ├── create-user.input.ts │ └── update-user.input.ts │ ├── entities │ └── user.entity.ts │ ├── users.module.ts │ ├── users.resolver.spec.ts │ ├── users.resolver.ts │ ├── users.service.spec.ts │ └── users.service.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json ├── tsconfig.json └── yarn.lock /.env.example: -------------------------------------------------------------------------------- 1 | DB_HOST=localhost 2 | DB_PORT=5432 3 | DB_USERNAME=postgres 4 | DB_PASSWORD=SuperSecret!23 5 | DB_DATABASE=postgres -------------------------------------------------------------------------------- /.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 36 | 37 | .env 38 | .docker-data/ -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npx pretty-quick --staged && yarn lint 5 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Nestjs with Graphql 2 | 3 | Welcome to this project! 4 | 5 | I developed this project as a scaffold for my artciles in the medium platform 6 | 7 | If you want to start reading please start with this [article](https://javascript.plainenglish.io/graphql-nodejs-mongodb-made-easy-with-nestjs-and-mongoose-29f9c0ea7e1d) 8 | 9 | Please note that the main branch is outdated and each branch reflects some speccific article I published on medium. 10 | 11 | Feel free to fork this project and to give a star if it was anyhow useful for your learnings 12 | 13 | Cheers 14 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | db: 4 | image: postgres 5 | restart: unless-stopped 6 | ports: 7 | - '5432:5432' 8 | environment: 9 | POSTGRES_PASSWORD: SuperSecret!23 10 | volumes: 11 | - .docker-data/postgres:/var/lib/postgresql/data 12 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nestjs-with-graphql", 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 | "prepare": "husky install" 23 | }, 24 | "dependencies": { 25 | "@nestjs/common": "^8.0.0", 26 | "@nestjs/core": "^8.0.0", 27 | "@nestjs/graphql": "^8.0.2", 28 | "@nestjs/platform-express": "^8.0.0", 29 | "@nestjs/typeorm": "^8.0.2", 30 | "apollo-server-express": "2.x.x", 31 | "dotenv": "^10.0.0", 32 | "graphql": "^15.5.1", 33 | "pg": "^8.7.1", 34 | "reflect-metadata": "^0.1.13", 35 | "rimraf": "^3.0.2", 36 | "rxjs": "^7.2.0", 37 | "typeorm": "^0.2.36" 38 | }, 39 | "devDependencies": { 40 | "@nestjs/cli": "^8.0.0", 41 | "@nestjs/schematics": "^8.0.0", 42 | "@nestjs/testing": "^8.0.0", 43 | "@types/express": "^4.17.13", 44 | "@types/jest": "^26.0.24", 45 | "@types/node": "^16.0.0", 46 | "@types/supertest": "^2.0.11", 47 | "@typescript-eslint/eslint-plugin": "^4.28.2", 48 | "@typescript-eslint/parser": "^4.28.2", 49 | "eslint": "^7.30.0", 50 | "eslint-config-prettier": "^8.3.0", 51 | "eslint-plugin-prettier": "^3.4.0", 52 | "husky": "^6.0.0", 53 | "jest": "27.0.6", 54 | "prettier": "^2.3.2", 55 | "pretty-quick": "^3.1.1", 56 | "supertest": "^6.1.3", 57 | "ts-jest": "^27.0.3", 58 | "ts-loader": "^9.2.3", 59 | "ts-node": "^10.0.0", 60 | "tsconfig-paths": "^3.10.1", 61 | "typescript": "^4.3.5" 62 | }, 63 | "jest": { 64 | "moduleFileExtensions": [ 65 | "js", 66 | "json", 67 | "ts" 68 | ], 69 | "rootDir": "src", 70 | "testRegex": ".*\\.spec\\.ts$", 71 | "transform": { 72 | "^.+\\.(t|j)s$": "ts-jest" 73 | }, 74 | "collectCoverageFrom": [ 75 | "**/*.(t|j)s" 76 | ], 77 | "coverageDirectory": "../coverage", 78 | "testEnvironment": "node" 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /schema.gql: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------ 2 | # THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY) 3 | # ------------------------------------------------------ 4 | 5 | type User { 6 | """ 7 | id of the user 8 | """ 9 | userId: String! 10 | 11 | """ 12 | Example field (placeholder) 13 | """ 14 | exampleField: Int! 15 | 16 | """ 17 | first name of the user 18 | """ 19 | firstName: String! 20 | 21 | """ 22 | last name of the user 23 | """ 24 | lastName: String! 25 | 26 | """ 27 | email of the user 28 | """ 29 | email: String! 30 | 31 | """ 32 | role of the user 33 | """ 34 | role: String! 35 | } 36 | 37 | type Query { 38 | users: [User!]! 39 | user(userId: String!): User! 40 | } 41 | 42 | type Mutation { 43 | createUser(createUserInput: CreateUserInput!): User! 44 | updateUser(updateUserInput: UpdateUserInput!): User! 45 | removeUser(userId: String!): User! 46 | } 47 | 48 | input CreateUserInput { 49 | """ 50 | Example field (placeholder) 51 | """ 52 | exampleField: Int! 53 | 54 | """ 55 | first name of the user 56 | """ 57 | firstName: String! 58 | 59 | """ 60 | last name of the user 61 | """ 62 | lastName: String! 63 | 64 | """ 65 | email of the user 66 | """ 67 | email: String! 68 | 69 | """ 70 | role of the user 71 | """ 72 | role: String! 73 | } 74 | 75 | input UpdateUserInput { 76 | """ 77 | Example field (placeholder) 78 | """ 79 | exampleField: Int 80 | 81 | """ 82 | first name of the user 83 | """ 84 | firstName: String 85 | 86 | """ 87 | last name of the user 88 | """ 89 | lastName: String 90 | 91 | """ 92 | email of the user 93 | """ 94 | email: String 95 | 96 | """ 97 | role of the user 98 | """ 99 | role: String 100 | userId: String! 101 | } 102 | -------------------------------------------------------------------------------- /src/app.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | 5 | describe('AppController', () => { 6 | let appController: AppController; 7 | 8 | beforeEach(async () => { 9 | const app: TestingModule = await Test.createTestingModule({ 10 | controllers: [AppController], 11 | providers: [AppService], 12 | }).compile(); 13 | 14 | appController = app.get(AppController); 15 | }); 16 | 17 | describe('root', () => { 18 | it('should return "Hello World!"', () => { 19 | expect(appController.getHello()).toBe('Hello World!'); 20 | }); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /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 | @Get() 9 | getHello(): string { 10 | return this.appService.getHello(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | import { GraphQLModule } from '@nestjs/graphql'; 5 | import { UsersModule } from './users/users.module'; 6 | import { TypeOrmModule } from '@nestjs/typeorm'; 7 | import * as dotenv from 'dotenv'; 8 | dotenv.config(); 9 | 10 | @Module({ 11 | imports: [ 12 | GraphQLModule.forRoot({ 13 | autoSchemaFile: './schema.gql', 14 | debug: true, 15 | playground: true, 16 | }), 17 | TypeOrmModule.forRoot({ 18 | keepConnectionAlive: true, 19 | type: 'postgres', 20 | host: process.env.DB_HOST, 21 | port: +process.env.DB_PORT, 22 | username: process.env.DB_USERNAME, 23 | password: process.env.DB_PASSWORD, 24 | database: process.env.DB_DATABASE, 25 | autoLoadEntities: true, 26 | synchronize: true, 27 | }), 28 | UsersModule, 29 | ], 30 | controllers: [AppController], 31 | providers: [AppService], 32 | }) 33 | export class AppModule {} 34 | -------------------------------------------------------------------------------- /src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class AppService { 5 | getHello(): string { 6 | return 'Hello World!'; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | 4 | async function bootstrap() { 5 | const app = await NestFactory.create(AppModule); 6 | await app.listen(3000); 7 | } 8 | bootstrap(); 9 | -------------------------------------------------------------------------------- /src/users/dto/create-user.input.ts: -------------------------------------------------------------------------------- 1 | import { InputType, Int, Field } from '@nestjs/graphql'; 2 | 3 | @InputType() 4 | export class CreateUserInput { 5 | @Field(() => Int, { description: 'Example field (placeholder)' }) 6 | exampleField: number; 7 | @Field(() => String, { description: 'first name of the user' }) 8 | firstName: string; 9 | @Field(() => String, { description: 'last name of the user' }) 10 | lastName: string; 11 | @Field(() => String, { description: 'email of the user' }) 12 | email: string; 13 | @Field(() => String, { description: 'role of the user' }) 14 | role: string; 15 | } 16 | -------------------------------------------------------------------------------- /src/users/dto/update-user.input.ts: -------------------------------------------------------------------------------- 1 | import { CreateUserInput } from './create-user.input'; 2 | import { InputType, Field, PartialType } from '@nestjs/graphql'; 3 | 4 | @InputType() 5 | export class UpdateUserInput extends PartialType(CreateUserInput) { 6 | @Field(() => String) 7 | userId: string; 8 | } 9 | -------------------------------------------------------------------------------- /src/users/entities/user.entity.ts: -------------------------------------------------------------------------------- 1 | import { ObjectType, Field, Int } from '@nestjs/graphql'; 2 | import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'; 3 | 4 | @Entity() 5 | @ObjectType() 6 | export class User { 7 | @PrimaryGeneratedColumn('uuid') 8 | @Field(() => String, { description: 'id of the user' }) 9 | userId: string; 10 | @Column('int') 11 | @Field(() => Int, { description: 'Example field (placeholder)' }) 12 | exampleField: number; 13 | @Column() 14 | @Field(() => String, { description: 'first name of the user' }) 15 | firstName: string; 16 | @Column() 17 | @Field(() => String, { description: 'last name of the user' }) 18 | lastName: string; 19 | @Column() 20 | @Field(() => String, { description: 'email of the user' }) 21 | email: string; 22 | @Column({ nullable: true }) 23 | @Field(() => String, { description: 'role of the user' }) 24 | role: string; 25 | } 26 | -------------------------------------------------------------------------------- /src/users/users.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { UsersService } from './users.service'; 3 | import { UsersResolver } from './users.resolver'; 4 | import { TypeOrmModule } from '@nestjs/typeorm'; 5 | import { User } from './entities/user.entity'; 6 | 7 | @Module({ 8 | imports: [TypeOrmModule.forFeature([User])], 9 | providers: [UsersResolver, UsersService], 10 | }) 11 | export class UsersModule {} 12 | -------------------------------------------------------------------------------- /src/users/users.resolver.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UsersResolver } from './users.resolver'; 3 | import { UsersService } from './users.service'; 4 | 5 | describe('UsersResolver', () => { 6 | let resolver: UsersResolver; 7 | 8 | beforeEach(async () => { 9 | const module: TestingModule = await Test.createTestingModule({ 10 | providers: [UsersResolver, UsersService], 11 | }).compile(); 12 | 13 | resolver = module.get(UsersResolver); 14 | }); 15 | 16 | it('should be defined', () => { 17 | expect(resolver).toBeDefined(); 18 | }); 19 | }); 20 | -------------------------------------------------------------------------------- /src/users/users.resolver.ts: -------------------------------------------------------------------------------- 1 | import { Resolver, Query, Mutation, Args } from '@nestjs/graphql'; 2 | import { UsersService } from './users.service'; 3 | import { User } from './entities/user.entity'; 4 | import { CreateUserInput } from './dto/create-user.input'; 5 | import { UpdateUserInput } from './dto/update-user.input'; 6 | 7 | @Resolver(() => User) 8 | export class UsersResolver { 9 | constructor(private readonly usersService: UsersService) {} 10 | 11 | @Mutation(() => User) 12 | createUser(@Args('createUserInput') createUserInput: CreateUserInput) { 13 | return this.usersService.create(createUserInput); 14 | } 15 | 16 | @Query(() => [User], { name: 'users' }) 17 | findAll() { 18 | return this.usersService.findAll(); 19 | } 20 | 21 | @Query(() => User, { name: 'user' }) 22 | findOne(@Args('userId', { type: () => String }) userId: string) { 23 | return this.usersService.findOne(userId); 24 | } 25 | 26 | @Mutation(() => User) 27 | updateUser(@Args('updateUserInput') updateUserInput: UpdateUserInput) { 28 | return this.usersService.update(updateUserInput.userId, updateUserInput); 29 | } 30 | 31 | @Mutation(() => User) 32 | removeUser(@Args('userId', { type: () => String }) userId: string) { 33 | return this.usersService.remove(userId); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/users/users.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UsersService } from './users.service'; 3 | 4 | describe('UsersService', () => { 5 | let service: UsersService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [UsersService], 10 | }).compile(); 11 | 12 | service = module.get(UsersService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/users/users.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, NotFoundException } from '@nestjs/common'; 2 | import { CreateUserInput } from './dto/create-user.input'; 3 | import { UpdateUserInput } from './dto/update-user.input'; 4 | import { User } from './entities/user.entity'; 5 | import { InjectRepository } from '@nestjs/typeorm'; 6 | import { Repository } from 'typeorm'; 7 | 8 | @Injectable() 9 | export class UsersService { 10 | constructor( 11 | @InjectRepository(User) 12 | private readonly userRepository: Repository, 13 | ) {} 14 | 15 | async create(createUserInput: CreateUserInput): Promise { 16 | const user = this.userRepository.create(createUserInput); 17 | return await this.userRepository.save(user); 18 | } 19 | 20 | async findAll(): Promise> { 21 | return await this.userRepository.find(); 22 | } 23 | 24 | async findOne(userId: string): Promise { 25 | const user = await this.userRepository.findOne(userId); 26 | if (!user) { 27 | throw new NotFoundException(`User #${userId} not found`); 28 | } 29 | return user; 30 | } 31 | 32 | async update( 33 | userId: string, 34 | updateUserInput: UpdateUserInput, 35 | ): Promise { 36 | const user = await this.userRepository.preload({ 37 | userId: userId, 38 | ...updateUserInput, 39 | }); 40 | if (!user) { 41 | throw new NotFoundException(`User #${userId} not found`); 42 | } 43 | return this.userRepository.save(user); 44 | } 45 | 46 | async remove(userId: string): Promise { 47 | const user = await this.findOne(userId); 48 | await this.userRepository.remove(user); 49 | return { 50 | userId: userId, 51 | firstName: '', 52 | lastName: '', 53 | email: '', 54 | role: '', 55 | exampleField: 0, 56 | }; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /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 | } 16 | } 17 | --------------------------------------------------------------------------------