├── .prettierrc ├── .firebaserc ├── tsconfig.build.json ├── nest-cli.json ├── src ├── todo │ ├── entities │ │ └── todo.entity.ts │ ├── dto │ │ ├── update-todo.dto.ts │ │ └── create-todo.dto.ts │ ├── todo.module.ts │ ├── todo.service.spec.ts │ ├── todo.controller.spec.ts │ ├── todo.controller.ts │ └── todo.service.ts ├── main.ts ├── app.module.ts └── auth │ ├── auth.module.ts │ └── firebase-auth.strategy.ts ├── test ├── jest-e2e.json └── app.e2e-spec.ts ├── firebase.json ├── .gitignore ├── tsconfig.json ├── .eslintrc.js ├── index.ts ├── package.json └── README.md /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /.firebaserc: -------------------------------------------------------------------------------- 1 | { 2 | "projects": { 3 | "default": "todo-e5e78" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src" 5 | } 6 | -------------------------------------------------------------------------------- /src/todo/entities/todo.entity.ts: -------------------------------------------------------------------------------- 1 | export class Todo { 2 | id: string; 3 | title: string; 4 | details: string; 5 | userId: string; 6 | createdAt: string; 7 | } 8 | -------------------------------------------------------------------------------- /src/todo/dto/update-todo.dto.ts: -------------------------------------------------------------------------------- 1 | import { PartialType } from '@nestjs/mapped-types'; 2 | import { CreateTodoDto } from './create-todo.dto'; 3 | 4 | export class UpdateTodoDto extends PartialType(CreateTodoDto) {} 5 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/todo/dto/create-todo.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsNotEmpty, IsString } from 'class-validator'; 2 | 3 | export class CreateTodoDto { 4 | @IsNotEmpty() 5 | @IsString() 6 | title: string; 7 | 8 | @IsString() 9 | details: string; 10 | } 11 | -------------------------------------------------------------------------------- /firebase.json: -------------------------------------------------------------------------------- 1 | { 2 | "functions": { 3 | "ignore": [ 4 | "node_modules", 5 | ".git", 6 | "firebase-debug.log", 7 | "firebase-debug.*.log" 8 | ], 9 | "predeploy": "npm --prefix \"$RESOURCE_DIR\" run build", 10 | "source": "." 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/todo/todo.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TodoService } from './todo.service'; 3 | import { TodoController } from './todo.controller'; 4 | 5 | @Module({ 6 | controllers: [TodoController], 7 | providers: [TodoService], 8 | }) 9 | export class TodoModule {} 10 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TodoModule } from './todo/todo.module'; 3 | import { AuthModule } from './auth/auth.module'; 4 | 5 | @Module({ 6 | imports: [TodoModule, AuthModule], 7 | controllers: [], 8 | providers: [], 9 | }) 10 | export class AppModule {} 11 | -------------------------------------------------------------------------------- /src/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { Global, Module } from '@nestjs/common'; 2 | import { PassportModule } from '@nestjs/passport'; 3 | import { FirebaseAuthStrategy } from './firebase-auth.strategy'; 4 | 5 | @Global() 6 | @Module({ 7 | imports: [PassportModule.register({ defaultStrategy: 'firebase-jwt' })], 8 | providers: [FirebaseAuthStrategy], 9 | exports: [PassportModule], 10 | }) 11 | export class AuthModule {} 12 | -------------------------------------------------------------------------------- /src/todo/todo.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { TodoService } from './todo.service'; 3 | 4 | describe('TodoService', () => { 5 | let service: TodoService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [TodoService], 10 | }).compile(); 11 | 12 | service = module.get(TodoService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /.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 | # Configurations 38 | .runtimeconfig.json 39 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/todo/todo.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { TodoController } from './todo.controller'; 3 | import { TodoService } from './todo.service'; 4 | 5 | describe('TodoController', () => { 6 | let controller: TodoController; 7 | 8 | beforeEach(async () => { 9 | const module: TestingModule = await Test.createTestingModule({ 10 | controllers: [TodoController], 11 | providers: [TodoService], 12 | }).compile(); 13 | 14 | controller = module.get(TodoController); 15 | }); 16 | 17 | it('should be defined', () => { 18 | expect(controller).toBeDefined(); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /src/auth/firebase-auth.strategy.ts: -------------------------------------------------------------------------------- 1 | import { PassportStrategy } from '@nestjs/passport'; 2 | import { Injectable, UnauthorizedException } from '@nestjs/common'; 3 | import { ExtractJwt, Strategy } from 'passport-firebase-jwt'; 4 | import { auth } from 'firebase-admin'; 5 | 6 | @Injectable() 7 | export class FirebaseAuthStrategy extends PassportStrategy(Strategy) { 8 | constructor() { 9 | super({ 10 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 11 | }); 12 | } 13 | 14 | validate(token) { 15 | return auth() 16 | .verifyIdToken(token, true) 17 | .catch((err) => { 18 | console.warn(err); 19 | throw new UnauthorizedException(); 20 | }); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { ExpressAdapter } from '@nestjs/platform-express'; 3 | import * as express from 'express'; 4 | import * as functions from 'firebase-functions'; 5 | import { AppModule } from './src/app.module'; 6 | import * as admin from 'firebase-admin'; 7 | import { ValidationPipe } from '@nestjs/common'; 8 | 9 | admin.initializeApp({ 10 | credential: admin.credential.cert(functions.config().todo_firebase_config), 11 | databaseURL: 'https://todo-c9f6e-default-rtdb.firebaseio.com', 12 | }); 13 | 14 | const expressServer = express(); 15 | const createFunction = async (expressInstance): Promise => { 16 | const app = await NestFactory.create( 17 | AppModule, 18 | new ExpressAdapter(expressInstance), 19 | ); 20 | app.enableCors(); 21 | app.useGlobalPipes(new ValidationPipe()); 22 | await app.init(); 23 | }; 24 | export const api = functions.https.onRequest(async (request, response) => { 25 | await createFunction(expressServer); 26 | expressServer(request, response); 27 | }); 28 | -------------------------------------------------------------------------------- /src/todo/todo.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Body, 3 | Controller, 4 | Delete, 5 | Get, 6 | Param, 7 | Patch, 8 | Post, 9 | UseGuards, 10 | } from '@nestjs/common'; 11 | import { TodoService } from './todo.service'; 12 | import { CreateTodoDto } from './dto/create-todo.dto'; 13 | import { UpdateTodoDto } from './dto/update-todo.dto'; 14 | import { AuthGuard } from '@nestjs/passport'; 15 | 16 | @UseGuards(AuthGuard()) 17 | @Controller('todo') 18 | export class TodoController { 19 | constructor(private readonly todoService: TodoService) {} 20 | 21 | @Post() 22 | create(@Body() createTodoDto: CreateTodoDto) { 23 | return this.todoService.create(createTodoDto); 24 | } 25 | 26 | @Get() 27 | findAll() { 28 | return this.todoService.findAll(); 29 | } 30 | 31 | @Get(':id') 32 | findOne(@Param('id') id: string) { 33 | return this.todoService.findOne(id); 34 | } 35 | 36 | @Patch(':id') 37 | update(@Param('id') id: string, @Body() updateTodoDto: UpdateTodoDto) { 38 | return this.todoService.update(id, updateTodoDto); 39 | } 40 | 41 | @Delete(':id') 42 | remove(@Param('id') id: string) { 43 | return this.todoService.remove(id); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/todo/todo.service.ts: -------------------------------------------------------------------------------- 1 | import { Inject, Injectable } from '@nestjs/common'; 2 | import { CreateTodoDto } from './dto/create-todo.dto'; 3 | import { UpdateTodoDto } from './dto/update-todo.dto'; 4 | import { firestore } from 'firebase-admin'; 5 | import { REQUEST } from '@nestjs/core'; 6 | import { Todo } from './entities/todo.entity'; 7 | import DocumentSnapshot = firestore.DocumentSnapshot; 8 | import QuerySnapshot = firestore.QuerySnapshot; 9 | 10 | @Injectable() 11 | export class TodoService { 12 | private collection: FirebaseFirestore.CollectionReference; 13 | 14 | constructor(@Inject(REQUEST) private readonly request: { user: any }) { 15 | this.collection = firestore().collection('todos'); 16 | } 17 | 18 | async create(createTodoDto: CreateTodoDto) { 19 | const userId = this.request.user.uid; 20 | const todo: Omit = { 21 | ...createTodoDto, 22 | createdAt: new Date().toISOString(), 23 | userId, 24 | }; 25 | 26 | return this.collection.add(todo).then((doc) => { 27 | return { id: doc.id, ...todo }; 28 | }); 29 | } 30 | 31 | findAll() { 32 | return this.collection 33 | .where('userId', '==', this.request.user.uid) 34 | .get() 35 | .then((querySnapshot: QuerySnapshot) => { 36 | if (querySnapshot.empty) { 37 | return []; 38 | } 39 | 40 | const todos: Todo[] = []; 41 | for (const doc of querySnapshot.docs) { 42 | todos.push(this.transformTodo(doc)); 43 | } 44 | 45 | return todos; 46 | }); 47 | } 48 | 49 | findOne(id: string) { 50 | return this.collection 51 | .doc(id) 52 | .get() 53 | .then((querySnapshot: DocumentSnapshot) => { 54 | return this.transformTodo(querySnapshot); 55 | }); 56 | } 57 | 58 | async update(id: string, updateTodoDto: UpdateTodoDto) { 59 | await this.collection.doc(id).update(updateTodoDto); 60 | } 61 | 62 | async remove(id: string) { 63 | await this.collection.doc(id).delete(); 64 | } 65 | 66 | private transformTodo(querySnapshot: DocumentSnapshot) { 67 | if (!querySnapshot.exists) { 68 | throw new Error(`no todo found with the given id`); 69 | } 70 | 71 | const todo = querySnapshot.data(); 72 | const userId = this.request.user.uid; 73 | 74 | if (todo.userId !== userId) { 75 | throw new Error(`no todo found with the given id`); 76 | } 77 | 78 | return { 79 | id: querySnapshot.id, 80 | ...todo, 81 | }; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "todo", 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 | "build:watch": "nest build --watch", 12 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 13 | "start": "nest start", 14 | "start:dev": "nest start --watch", 15 | "start:debug": "nest start --debug --watch", 16 | "start:prod": "node dist/main", 17 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 18 | "test": "jest", 19 | "test:watch": "jest --watch", 20 | "test:cov": "jest --coverage", 21 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 22 | "test:e2e": "jest --config ./test/jest-e2e.json", 23 | "get:config": "firebase functions:config:get > .runtimeconfig.json", 24 | "firebase:emulator": "firebase emulators:start --only functions", 25 | "serve": "npm run get:config && npm run build && npm run firebase:emulator", 26 | "serve:watch": "concurrently npm:get:config npm:build && concurrently npm:build:watch npm:firebase:emulator", 27 | "shell": "npm run build && firebase functions:shell", 28 | "deploy": "firebase deploy --only functions", 29 | "logs": "firebase functions:log" 30 | }, 31 | "engines": { 32 | "node": "16" 33 | }, 34 | "main": "dist/index.js", 35 | "dependencies": { 36 | "@nestjs/common": "^9.0.0", 37 | "@nestjs/core": "^10.3.7", 38 | "@nestjs/mapped-types": "*", 39 | "@nestjs/passport": "^9.0.0", 40 | "@nestjs/platform-express": "^10.3.7", 41 | "class-transformer": "^0.5.1", 42 | "firebase-admin": "^12.0.0", 43 | "firebase-functions": "^3.21.0", 44 | "passport": "^0.6.0", 45 | "passport-firebase-jwt": "^1.2.1", 46 | "reflect-metadata": "^0.1.13", 47 | "rimraf": "^3.0.2", 48 | "rxjs": "^7.2.0" 49 | }, 50 | "devDependencies": { 51 | "@nestjs/cli": "^9.3.0", 52 | "@nestjs/schematics": "^9.0.0", 53 | "@nestjs/testing": "^10.3.7", 54 | "@types/express": "^4.17.13", 55 | "@types/jest": "28.1.4", 56 | "@types/node": "^16.0.0", 57 | "@types/supertest": "^2.0.11", 58 | "@typescript-eslint/eslint-plugin": "^5.0.0", 59 | "@typescript-eslint/parser": "^5.0.0", 60 | "class-validator": "^0.14.0", 61 | "concurrently": "^7.3.0", 62 | "eslint": "^8.0.1", 63 | "eslint-config-prettier": "^8.3.0", 64 | "eslint-plugin-prettier": "^4.0.0", 65 | "jest": "28.1.2", 66 | "prettier": "^2.3.2", 67 | "source-map-support": "^0.5.20", 68 | "supertest": "^6.1.3", 69 | "ts-jest": "28.0.5", 70 | "ts-loader": "^9.2.3", 71 | "ts-node": "^10.0.0", 72 | "tsconfig-paths": "4.0.0", 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 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------