├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── README.md ├── nest-cli.json ├── package-lock.json ├── package.json ├── src ├── app.module.ts ├── filters │ └── http-exception.filter.ts ├── main.ts └── posts │ ├── posts.controller.spec.ts │ ├── posts.controller.ts │ ├── posts.interface.ts │ ├── posts.module.ts │ ├── posts.service.spec.ts │ └── posts.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 | 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 | 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 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NestJS RESTful API 2 | 3 | ## Description 4 | 5 | An introduction to RESTful APIs with NestJS. NestJS is used to build an API that implements CRUD functionality for blog posts. 6 | 7 | ## Installation 8 | 9 | ```bash 10 | $ npm install 11 | ``` 12 | 13 | ## Running the app 14 | 15 | ```bash 16 | # development 17 | $ npm run start 18 | 19 | # watch mode 20 | $ npm run start:dev 21 | 22 | # production mode 23 | $ npm run start:prod 24 | ``` 25 | 26 | ## Using the app 27 | 28 | When the app is run locally, it is available at `http://localhost:3000`. 29 | 30 | ## OpenAPI (Swagger) 31 | 32 | OpenAPI specification is a language-agnostic definition format used to describe RESTful APIs. 33 | 34 | When running the project locally, visit `http://localhost:3000/api` to access the Swagger UI. 35 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rest-api", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "prebuild": "rimraf dist", 10 | "build": "nest build", 11 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 12 | "start": "nest start", 13 | "start:dev": "nest start --watch", 14 | "start:debug": "nest start --debug --watch", 15 | "start:prod": "node dist/main", 16 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 17 | "test": "jest", 18 | "test:watch": "jest --watch", 19 | "test:cov": "jest --coverage", 20 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 21 | "test:e2e": "jest --config ./test/jest-e2e.json" 22 | }, 23 | "dependencies": { 24 | "@nestjs/common": "^8.0.0", 25 | "@nestjs/core": "^8.0.0", 26 | "@nestjs/platform-express": "^8.0.0", 27 | "@nestjs/swagger": "^5.0.9", 28 | "reflect-metadata": "^0.1.13", 29 | "rimraf": "^3.0.2", 30 | "rxjs": "^6.6.6", 31 | "swagger-ui-express": "^4.1.6" 32 | }, 33 | "devDependencies": { 34 | "@nestjs/cli": "^8.0.0", 35 | "@nestjs/schematics": "^8.0.0", 36 | "@nestjs/testing": "^8.0.0", 37 | "@types/express": "^4.17.11", 38 | "@types/jest": "^26.0.22", 39 | "@types/node": "^14.14.36", 40 | "@types/supertest": "^2.0.10", 41 | "@typescript-eslint/eslint-plugin": "^4.19.0", 42 | "@typescript-eslint/parser": "^4.19.0", 43 | "eslint": "^7.22.0", 44 | "eslint-config-prettier": "^8.1.0", 45 | "eslint-plugin-prettier": "^3.3.1", 46 | "jest": "^26.6.3", 47 | "prettier": "^2.2.1", 48 | "supertest": "^6.1.3", 49 | "ts-jest": "^26.5.4", 50 | "ts-loader": "^8.0.18", 51 | "ts-node": "^9.1.1", 52 | "tsconfig-paths": "^3.9.0", 53 | "typescript": "^4.2.3" 54 | }, 55 | "jest": { 56 | "moduleFileExtensions": [ 57 | "js", 58 | "json", 59 | "ts" 60 | ], 61 | "rootDir": "src", 62 | "testRegex": ".*\\.spec\\.ts$", 63 | "transform": { 64 | "^.+\\.(t|j)s$": "ts-jest" 65 | }, 66 | "collectCoverageFrom": [ 67 | "**/*.(t|j)s" 68 | ], 69 | "coverageDirectory": "../coverage", 70 | "testEnvironment": "node" 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { PostsModule } from './posts/posts.module'; 3 | 4 | @Module({ 5 | imports: [PostsModule], 6 | controllers: [], 7 | providers: [], 8 | }) 9 | export class AppModule {} 10 | -------------------------------------------------------------------------------- /src/filters/http-exception.filter.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ExceptionFilter, 3 | Catch, 4 | ArgumentsHost, 5 | HttpException, 6 | Logger, 7 | } from '@nestjs/common'; 8 | import { Request, Response } from 'express'; 9 | 10 | @Catch(HttpException) 11 | export class HttpExceptionFilter implements ExceptionFilter { 12 | private readonly logger = new Logger(HttpExceptionFilter.name); 13 | 14 | catch(exception: HttpException, host: ArgumentsHost) { 15 | const ctx = host.switchToHttp(); 16 | const response = ctx.getResponse(); 17 | const request = ctx.getRequest(); 18 | const statusCode = exception.getStatus(); 19 | const message = exception.message || null; 20 | 21 | const body = { 22 | statusCode, 23 | message, 24 | timestamp: new Date().toISOString(), 25 | endpoint: request.url, 26 | }; 27 | 28 | this.logger.warn(`${statusCode} ${message}`); 29 | 30 | response.status(statusCode).json(body); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; 3 | import { AppModule } from './app.module'; 4 | 5 | async function bootstrap() { 6 | const app = await NestFactory.create(AppModule); 7 | 8 | const config = new DocumentBuilder() 9 | .setTitle('Blog API') 10 | .setDescription('Blog API') 11 | .setVersion('1.0') 12 | .build(); 13 | 14 | const document = SwaggerModule.createDocument(app, config); 15 | SwaggerModule.setup('api', app, document); 16 | 17 | await app.listen(3000); 18 | } 19 | bootstrap(); 20 | -------------------------------------------------------------------------------- /src/posts/posts.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { PostsController } from './posts.controller'; 3 | 4 | describe('PostsController', () => { 5 | let controller: PostsController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | controllers: [PostsController], 10 | }).compile(); 11 | 12 | controller = module.get(PostsController); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(controller).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/posts/posts.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Body, 3 | Controller, 4 | Delete, 5 | Get, 6 | Param, 7 | ParseIntPipe, 8 | Post, 9 | Put, 10 | UseFilters, 11 | } from '@nestjs/common'; 12 | import { 13 | ApiCreatedResponse, 14 | ApiNotFoundResponse, 15 | ApiOkResponse, 16 | ApiTags, 17 | ApiUnprocessableEntityResponse, 18 | } from '@nestjs/swagger'; 19 | import { HttpExceptionFilter } from '../filters/http-exception.filter'; 20 | import { PostModel } from './posts.interface'; 21 | import { PostsService } from './posts.service'; 22 | 23 | @Controller('posts') 24 | @ApiTags('posts') 25 | @UseFilters(HttpExceptionFilter) 26 | export class PostsController { 27 | constructor(private readonly postsService: PostsService) {} 28 | 29 | @Get() 30 | @ApiOkResponse({ description: 'Posts retrieved successfully.' }) 31 | public findAll(): Array { 32 | return this.postsService.findAll(); 33 | } 34 | 35 | @Get(':id') 36 | @ApiOkResponse({ description: 'Post retrieved successfully.' }) 37 | @ApiNotFoundResponse({ description: 'Post not found.' }) 38 | public findOne(@Param('id', ParseIntPipe) id: number): PostModel { 39 | return this.postsService.findOne(id); 40 | } 41 | 42 | @Post() 43 | @ApiCreatedResponse({ description: 'Post created successfully.' }) 44 | @ApiUnprocessableEntityResponse({ description: 'Post title already exists.' }) 45 | public create(@Body() post: PostModel): PostModel { 46 | return this.postsService.create(post); 47 | } 48 | 49 | @Delete(':id') 50 | @ApiOkResponse({ description: 'Post deleted successfully.' }) 51 | @ApiNotFoundResponse({ description: 'Post not found.' }) 52 | public delete(@Param('id', ParseIntPipe) id: number): void { 53 | this.postsService.delete(id); 54 | } 55 | 56 | @Put(':id') 57 | @ApiOkResponse({ description: 'Post updated successfully.' }) 58 | @ApiNotFoundResponse({ description: 'Post not found.' }) 59 | @ApiUnprocessableEntityResponse({ description: 'Post title already exists.' }) 60 | public update( 61 | @Param('id', ParseIntPipe) id: number, 62 | @Body() post: PostModel, 63 | ): PostModel { 64 | return this.postsService.update(id, post); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/posts/posts.interface.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; 2 | 3 | export class PostModel { 4 | @ApiPropertyOptional({ type: Number }) 5 | id?: number; 6 | @ApiProperty({ type: String, format: 'date-time' }) 7 | date: Date; 8 | @ApiProperty({ type: String }) 9 | title: string; 10 | @ApiProperty({ type: String }) 11 | body: string; 12 | @ApiProperty({ type: String }) 13 | category: string; 14 | } 15 | -------------------------------------------------------------------------------- /src/posts/posts.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { PostsService } from './posts.service'; 3 | import { PostsController } from './posts.controller'; 4 | 5 | @Module({ 6 | providers: [PostsService], 7 | controllers: [PostsController], 8 | }) 9 | export class PostsModule {} 10 | -------------------------------------------------------------------------------- /src/posts/posts.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { PostsService } from './posts.service'; 3 | 4 | describe('PostsService', () => { 5 | let service: PostsService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [PostsService], 10 | }).compile(); 11 | 12 | service = module.get(PostsService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/posts/posts.service.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Injectable, 3 | Logger, 4 | NotFoundException, 5 | UnprocessableEntityException, 6 | } from '@nestjs/common'; 7 | import { PostModel } from './posts.interface'; 8 | 9 | @Injectable() 10 | export class PostsService { 11 | private posts: Array = []; 12 | private readonly logger = new Logger(PostsService.name); 13 | 14 | public findAll(): Array { 15 | this.logger.log('Returning all posts'); 16 | 17 | return this.posts; 18 | } 19 | 20 | public findOne(id: number): PostModel { 21 | this.logger.log(`Returning post with id: ${id}`); 22 | 23 | const post: PostModel = this.posts.find((post) => post.id === id); 24 | 25 | if (!post) { 26 | throw new NotFoundException('Post not found.'); 27 | } 28 | 29 | return post; 30 | } 31 | 32 | public create(post: PostModel): PostModel { 33 | this.logger.log(`Creating post with title: ${post.title}`); 34 | 35 | // if the title is already in use by another post 36 | const titleExists: boolean = this.posts.some( 37 | (item) => item.title === post.title, 38 | ); 39 | if (titleExists) { 40 | throw new UnprocessableEntityException('Post title already exists.'); 41 | } 42 | 43 | // find the next id for a new blog post 44 | const maxId: number = Math.max(...this.posts.map((post) => post.id), 0); 45 | const id: number = maxId + 1; 46 | 47 | const blogPost: PostModel = { 48 | ...post, 49 | id, 50 | }; 51 | 52 | this.posts.push(blogPost); 53 | 54 | return blogPost; 55 | } 56 | 57 | public delete(id: number): void { 58 | this.logger.log(`Deleting post with id: ${id}`); 59 | 60 | const index: number = this.posts.findIndex((post) => post.id === id); 61 | 62 | // -1 is returned when no findIndex() match is found 63 | if (index === -1) { 64 | throw new NotFoundException('Post not found.'); 65 | } 66 | 67 | this.posts.splice(index, 1); 68 | } 69 | 70 | public update(id: number, post: PostModel): PostModel { 71 | this.logger.log(`Updating post with id: ${id}`); 72 | 73 | const index: number = this.posts.findIndex((post) => post.id === id); 74 | 75 | // -1 is returned when no findIndex() match is found 76 | if (index === -1) { 77 | throw new NotFoundException('Post not found.'); 78 | } 79 | 80 | // if the title is already in use by another post 81 | const titleExists: boolean = this.posts.some( 82 | (item) => item.title === post.title && item.id !== id, 83 | ); 84 | if (titleExists) { 85 | throw new UnprocessableEntityException('Post title already exists.'); 86 | } 87 | 88 | const blogPost: PostModel = { 89 | ...post, 90 | id, 91 | }; 92 | 93 | this.posts[index] = blogPost; 94 | 95 | return blogPost; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /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 | } 15 | } 16 | --------------------------------------------------------------------------------