├── .env ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── Dockerfile ├── README.md ├── docker-compose.yml ├── nest-cli.json ├── package.json ├── process.json ├── schema.gql ├── src ├── app.controller.spec.ts ├── app.controller.ts ├── app.module.ts ├── app.service.ts ├── constants.ts ├── database.spec.ts ├── database │ ├── database.module.ts │ └── database.providers.ts ├── main.ts └── user │ ├── user.input.ts │ ├── user.module.ts │ ├── user.providers.ts │ ├── user.resolver.spec.ts │ ├── user.resolver.ts │ ├── user.schema.ts │ ├── user.service.spec.ts │ └── user.service.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json ├── tsconfig.json └── yarn.lock /.env: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomanagle/GraphQL-NestJS-MongoDB-TypeScript-Tutorial/394e477bb300a165deea975c44857cff97556afd/.env -------------------------------------------------------------------------------- /.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/eslint-recommended', 10 | 'plugin:@typescript-eslint/recommended', 11 | 'prettier', 12 | 'prettier/@typescript-eslint', 13 | ], 14 | root: true, 15 | env: { 16 | node: true, 17 | jest: true, 18 | }, 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': '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 | yarn-debug.log* 10 | yarn-error.log* 11 | lerna-debug.log* 12 | 13 | # OS 14 | .DS_Store 15 | 16 | # Tests 17 | /coverage 18 | /.nyc_output 19 | 20 | # IDEs and editors 21 | /.idea 22 | .project 23 | .classpath 24 | .c9/ 25 | *.launch 26 | .settings/ 27 | *.sublime-workspace 28 | 29 | # IDE - VSCode 30 | .vscode/* 31 | !.vscode/settings.json 32 | !.vscode/tasks.json 33 | !.vscode/launch.json 34 | !.vscode/extensions.json -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # You can use any Node version you like, see the full list of available versions: 2 | # https://hub.docker.com/_/node 3 | FROM node:14-alpine 4 | 5 | ADD package.json /tmp/package.json 6 | 7 | RUN rm -rf dist 8 | 9 | # Install dependancies with yarn 10 | RUN cd /tmp && yarn 11 | 12 | # Copy all files to the /src directory 13 | ADD ./ /src 14 | 15 | ## Remove the node_modules folder in /src and copy the new node_modules folder to /src 16 | RUN rm -rf /src/node_modules && cp -a /tmp/node_modules /src/ 17 | 18 | # Define working directory 19 | WORKDIR /src 20 | 21 | # Run the build script 22 | RUN npm run-script build 23 | 24 | #Optional: Install pm2 globally 25 | # Docs: https://pm2.keymetrics.io/ 26 | RUN npm install pm2 -g 27 | 28 | #Expose port 300 where the qapplication will run 29 | EXPOSE 3000 30 | 31 | # Start the application with pm2 32 | # You can also start it with just node 33 | CMD ["pm2-runtime", "process.json"] 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | A GraphQL API built on top of NestJS and containerized by Docker. 2 | 3 | The application was built for the [Build a Scalable GraphQL Server With NestJS, MongoDB & TypeScript](https://tomanagle.medium.com/build-a-scalable-graphql-server-with-nestjs-mongodb-typescript-1eeda049f7c8) tutorial. 4 | 5 | ### Getting started 6 | Start the application 7 | 8 | `yarn dev` 9 | 10 | Build and start the container 11 | 12 | `docker-compose up` 13 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.7' 2 | services: 3 | app-server: 4 | container_name: app-server 5 | environment: 6 | - NODE_ENV=production 7 | # If you want to use a cloud service like Mongo Atlas, change this to your connection string, 8 | # or remove this like and store the connection string in a .env file so you don't have to commit it 9 | # - MONO_DB_CONNECTION_STRING=mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@cndb:27017/${MONGO_INITDB_DATABASE}?authSource=admin 10 | env_file: 11 | - .env 12 | build: 13 | context: ./ 14 | image: app-server 15 | ports: 16 | - "3000:3000" -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "graphql-nestjs-mongodb-typescript", 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 | "dev": "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/common": "^7.0.0", 25 | "@nestjs/core": "^7.0.0", 26 | "@nestjs/graphql": "^7.9.5", 27 | "@nestjs/platform-express": "^7.0.0", 28 | "apollo-server-express": "^2.19.2", 29 | "graphql": "^15.4.0", 30 | "graphql-tools": "^7.0.2", 31 | "mongoose": "^5.11.12", 32 | "reflect-metadata": "^0.1.13", 33 | "rimraf": "^3.0.2", 34 | "rxjs": "^6.5.4", 35 | "ws": "^7.4.2" 36 | }, 37 | "devDependencies": { 38 | "@nestjs/cli": "^7.0.0", 39 | "@nestjs/schematics": "^7.0.0", 40 | "@nestjs/testing": "^7.0.0", 41 | "@types/express": "^4.17.3", 42 | "@types/jest": "25.1.4", 43 | "@types/mongoose": "^5.10.3", 44 | "@types/node": "^14.14.21", 45 | "@types/supertest": "^2.0.8", 46 | "@typescript-eslint/eslint-plugin": "^2.23.0", 47 | "@typescript-eslint/parser": "^2.23.0", 48 | "eslint": "^6.8.0", 49 | "eslint-config-prettier": "^6.10.0", 50 | "eslint-plugin-import": "^2.20.1", 51 | "jest": "^25.1.0", 52 | "prettier": "^1.19.1", 53 | "supertest": "^4.0.2", 54 | "ts-jest": "25.2.1", 55 | "ts-loader": "^6.2.1", 56 | "ts-node": "^8.6.2", 57 | "tsconfig-paths": "^3.9.0", 58 | "typescript": "^3.7.4" 59 | }, 60 | "jest": { 61 | "moduleFileExtensions": [ 62 | "js", 63 | "json", 64 | "ts" 65 | ], 66 | "rootDir": "src", 67 | "testRegex": ".spec.ts$", 68 | "transform": { 69 | "^.+\\.(t|j)s$": "ts-jest" 70 | }, 71 | "coverageDirectory": "../coverage", 72 | "testEnvironment": "node" 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /process.json: -------------------------------------------------------------------------------- 1 | { 2 | "apps": [ 3 | { 4 | "name": "server", 5 | "script": "dist/main.js", 6 | "watch": false, 7 | "instances": "max", 8 | "exec_mode": "cluster", 9 | "env": { 10 | "NODE_ENV": "production" 11 | } 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /schema.gql: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------ 2 | # THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY) 3 | # ------------------------------------------------------ 4 | 5 | type User { 6 | name: String! 7 | email: String! 8 | age: Float! 9 | } 10 | 11 | type Query { 12 | users: [User!]! 13 | } 14 | 15 | type Mutation { 16 | createUser(input: CreateUserInput!): User! 17 | } 18 | 19 | input CreateUserInput { 20 | name: String! 21 | email: String! 22 | age: Float! 23 | } 24 | -------------------------------------------------------------------------------- /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 | // src/app.module.ts 2 | import { Module } from '@nestjs/common'; 3 | import { GraphQLModule } from '@nestjs/graphql'; 4 | import { AppController } from './app.controller'; 5 | import { AppService } from './app.service'; 6 | import { UserService } from './user/user.service'; 7 | import { UserResolver } from './user/user.resolver'; 8 | import { UserModule } from './user/user.module'; 9 | import { userProviders } from './user/user.providers'; 10 | import { databaseProviders } from './database/database.providers'; 11 | import { DatabaseModule } from './database/database.module'; 12 | 13 | @Module({ 14 | imports: [ 15 | GraphQLModule.forRoot({ 16 | autoSchemaFile: 'schema.gql', 17 | }), 18 | UserModule, 19 | DatabaseModule, 20 | ], 21 | controllers: [AppController], 22 | providers: [ 23 | AppService, 24 | UserService, 25 | UserResolver, 26 | ...databaseProviders, 27 | ...userProviders, 28 | ], 29 | }) 30 | export class AppModule {} 31 | -------------------------------------------------------------------------------- /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/constants.ts: -------------------------------------------------------------------------------- 1 | // src/constants.ts 2 | export const MONO_DB_CONNECTION_STRING = 3 | process.env.MONO_DB_CONNECTION_STRING || 'mongodb://localhost/nest'; 4 | -------------------------------------------------------------------------------- /src/database.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { Database } from './database'; 3 | 4 | describe('Database', () => { 5 | let provider: Database; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [Database], 10 | }).compile(); 11 | 12 | provider = module.get(Database); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(provider).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/database/database.module.ts: -------------------------------------------------------------------------------- 1 | // src/database/database.module.ts 2 | import { Module } from '@nestjs/common'; 3 | import { databaseProviders } from './database.providers'; 4 | 5 | @Module({ 6 | providers: [...databaseProviders], 7 | exports: [...databaseProviders], 8 | }) 9 | export class DatabaseModule {} 10 | -------------------------------------------------------------------------------- /src/database/database.providers.ts: -------------------------------------------------------------------------------- 1 | // src/database/database.providers.ts 2 | import mongoose from 'mongoose'; 3 | import { MONO_DB_CONNECTION_STRING } from '../constants'; 4 | 5 | export const databaseProviders = [ 6 | { 7 | provide: 'DATABASE_CONNECTION', 8 | useFactory: (): Promise => 9 | mongoose.connect(MONO_DB_CONNECTION_STRING), 10 | }, 11 | ]; 12 | -------------------------------------------------------------------------------- /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/user/user.input.ts: -------------------------------------------------------------------------------- 1 | // src/user/user.input.ts 2 | import { Field, InputType } from '@nestjs/graphql'; 3 | 4 | @InputType() 5 | export class CreateUserInput { 6 | @Field() 7 | name: string; 8 | 9 | @Field() 10 | email: string; 11 | 12 | @Field() 13 | age: number; 14 | } 15 | -------------------------------------------------------------------------------- /src/user/user.module.ts: -------------------------------------------------------------------------------- 1 | // src/user/user.module.ts 2 | import { Module } from '@nestjs/common'; 3 | import { UserResolver } from './user.resolver'; 4 | import { UserService } from './user.service'; 5 | import { DatabaseModule } from '../database/database.module'; 6 | import { userProviders } from './user.providers'; 7 | 8 | @Module({ 9 | imports: [DatabaseModule], 10 | providers: [UserResolver, UserService, ...userProviders], 11 | }) 12 | export class UserModule {} 13 | -------------------------------------------------------------------------------- /src/user/user.providers.ts: -------------------------------------------------------------------------------- 1 | import { Connection } from 'mongoose'; 2 | import { UserSchema } from './user.schema'; 3 | 4 | export const userProviders = [ 5 | { 6 | provide: 'USER_MODEL', 7 | useFactory: (connection: Connection) => 8 | connection.model('User', UserSchema), 9 | inject: ['DATABASE_CONNECTION'], 10 | }, 11 | ]; 12 | -------------------------------------------------------------------------------- /src/user/user.resolver.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UserResolver } from './user.resolver'; 3 | 4 | describe('UserResolver', () => { 5 | let resolver: UserResolver; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [UserResolver], 10 | }).compile(); 11 | 12 | resolver = module.get(UserResolver); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(resolver).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/user/user.resolver.ts: -------------------------------------------------------------------------------- 1 | // src/user/user.resolver.ts 2 | import { Args, Mutation, Resolver, Query } from '@nestjs/graphql'; 3 | import { CreateUserInput } from './user.input'; 4 | import { UserService } from '../user/user.service'; 5 | import { User } from './user.schema'; 6 | 7 | @Resolver(() => User) 8 | export class UserResolver { 9 | constructor(private userService: UserService) {} 10 | 11 | @Mutation(() => User) 12 | async createUser(@Args('input') input: CreateUserInput) { 13 | return this.userService.create(input); 14 | } 15 | 16 | @Query(() => [User]) 17 | async users() { 18 | return this.userService.find(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/user/user.schema.ts: -------------------------------------------------------------------------------- 1 | // src/user/user.schema.ts 2 | import { Field, ObjectType } from '@nestjs/graphql'; 3 | import * as mongoose from 'mongoose'; 4 | import { Document } from 'mongoose'; 5 | 6 | export const UserSchema = new mongoose.Schema({ 7 | name: String, 8 | email: String, 9 | age: Number, 10 | }); 11 | 12 | @ObjectType() 13 | export class User extends Document { 14 | @Field() 15 | name: string; 16 | 17 | @Field() 18 | email: string; 19 | 20 | @Field() 21 | age: number; 22 | } 23 | -------------------------------------------------------------------------------- /src/user/user.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UserService } from './user.service'; 3 | 4 | describe('UserService', () => { 5 | let service: UserService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [UserService], 10 | }).compile(); 11 | 12 | service = module.get(UserService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/user/user.service.ts: -------------------------------------------------------------------------------- 1 | // src/user/user.service.ts 2 | import { Model, FilterQuery, CreateQuery } from 'mongoose'; 3 | import { Injectable, Inject } from '@nestjs/common'; 4 | import { User } from './user.schema'; 5 | 6 | @Injectable() 7 | export class UserService { 8 | constructor( 9 | @Inject('USER_MODEL') 10 | private userModel: Model, 11 | ) {} 12 | 13 | async create(input: CreateQuery): Promise { 14 | return this.userModel.create(input); 15 | } 16 | 17 | async findOne(query: FilterQuery): Promise { 18 | return this.userModel.findOne(query).lean(); 19 | } 20 | 21 | async find(): Promise { 22 | return this.userModel.find().lean(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /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 | "esModuleInterop": true, 9 | "skipLibCheck": true, 10 | "target": "es2017", 11 | "sourceMap": true, 12 | "outDir": "./dist", 13 | "baseUrl": "./", 14 | "incremental": true 15 | }, 16 | "exclude": ["node_modules", "dist"] 17 | } 18 | --------------------------------------------------------------------------------