├── .env ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── README.md ├── docker-compose.yml ├── docker.env ├── nest-cli.json ├── package.json ├── src ├── app.controller.spec.ts ├── app.controller.ts ├── app.module.ts ├── app.service.ts ├── database │ └── database.module.ts ├── main.ts └── message │ ├── message.entity.ts │ ├── message.gateway.ts │ ├── message.module.ts │ ├── messages.controller.ts │ └── messages.service.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json ├── tsconfig.json └── yarn.lock /.env: -------------------------------------------------------------------------------- 1 | POSTGRES_HOST=localhost 2 | POSTGRES_PORT=5432 3 | POSTGRES_USER=admin 4 | POSTGRES_PASSWORD=admin 5 | POSTGRES_DB=nestjs 6 | PORT=5000 -------------------------------------------------------------------------------- /.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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | postgres: 4 | container_name: postgres 5 | image: postgres:latest 6 | ports: 7 | - '5432:5432' 8 | volumes: 9 | - /var/folders/postgres:/data/postgres 10 | env_file: 11 | - docker.env 12 | networks: 13 | - postgres 14 | 15 | networks: 16 | postgres: 17 | driver: bridge 18 | -------------------------------------------------------------------------------- /docker.env: -------------------------------------------------------------------------------- 1 | POSTGRES_USER=admin 2 | POSTGRES_PASSWORD=admin 3 | POSTGRES_DB=nestjs 4 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src" 5 | } 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nestjs-websocket", 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 | "@hapi/joi": "^17.1.1", 25 | "@nestjs/common": "^9.0.0", 26 | "@nestjs/config": "^2.2.0", 27 | "@nestjs/core": "^9.0.0", 28 | "@nestjs/platform-express": "^9.0.0", 29 | "@nestjs/platform-socket.io": "^9.2.1", 30 | "@nestjs/typeorm": "^9.0.1", 31 | "@nestjs/websockets": "^9.2.1", 32 | "@types/hapi__joi": "^17.1.8", 33 | "pg": "^8.8.0", 34 | "reflect-metadata": "^0.1.13", 35 | "rimraf": "^3.0.2", 36 | "rxjs": "^7.2.0", 37 | "socket.io": "^4.5.4", 38 | "typeorm": "^0.3.10" 39 | }, 40 | "devDependencies": { 41 | "@nestjs/cli": "^9.0.0", 42 | "@nestjs/schematics": "^9.0.0", 43 | "@nestjs/testing": "^9.0.0", 44 | "@types/express": "^4.17.13", 45 | "@types/jest": "28.1.8", 46 | "@types/node": "^16.0.0", 47 | "@types/supertest": "^2.0.11", 48 | "@typescript-eslint/eslint-plugin": "^5.0.0", 49 | "@typescript-eslint/parser": "^5.0.0", 50 | "eslint": "^8.0.1", 51 | "eslint-config-prettier": "^8.3.0", 52 | "eslint-plugin-prettier": "^4.0.0", 53 | "jest": "28.1.3", 54 | "prettier": "^2.3.2", 55 | "source-map-support": "^0.5.20", 56 | "supertest": "^6.1.3", 57 | "ts-jest": "28.0.8", 58 | "ts-loader": "^9.2.3", 59 | "ts-node": "^10.0.0", 60 | "tsconfig-paths": "4.1.0", 61 | "typescript": "^4.7.4" 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 | -------------------------------------------------------------------------------- /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 { ConfigModule } from '@nestjs/config'; 5 | import * as Joi from '@hapi/joi'; 6 | import { DatabaseModule } from './database/database.module'; 7 | import { MessagesModule } from './message/message.module'; 8 | 9 | @Module({ 10 | imports: [ 11 | ConfigModule.forRoot({ 12 | validationSchema: Joi.object({ 13 | POSTGRES_HOST: Joi.string().required(), 14 | POSTGRES_PORT: Joi.number().required(), 15 | POSTGRES_USER: Joi.string().required(), 16 | POSTGRES_PASSWORD: Joi.string().required(), 17 | POSTGRES_DB: Joi.string().required(), 18 | PORT: Joi.number(), 19 | }), 20 | }), 21 | DatabaseModule, 22 | MessagesModule, 23 | ], 24 | controllers: [AppController], 25 | providers: [AppService], 26 | }) 27 | export class AppModule {} 28 | -------------------------------------------------------------------------------- /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/database/database.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import { ConfigModule, ConfigService } from '@nestjs/config'; 4 | 5 | @Module({ 6 | imports: [ 7 | TypeOrmModule.forRootAsync({ 8 | imports: [ConfigModule], 9 | inject: [ConfigService], 10 | useFactory: (configService: ConfigService) => ({ 11 | type: 'postgres', 12 | host: configService.get('POSTGRES_HOST'), 13 | port: configService.get('POSTGRES_PORT'), 14 | username: configService.get('POSTGRES_USER'), 15 | password: configService.get('POSTGRES_PASSWORD'), 16 | database: configService.get('POSTGRES_DB'), 17 | entities: [__dirname + '/../**/*.entity.{js,ts}'], 18 | synchronize: true, 19 | }), 20 | }), 21 | ], 22 | }) 23 | export class DatabaseModule {} 24 | -------------------------------------------------------------------------------- /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 | app.enableCors(); 7 | await app.listen(3000); 8 | } 9 | bootstrap(); 10 | -------------------------------------------------------------------------------- /src/message/message.entity.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Column, 3 | CreateDateColumn, 4 | Entity, 5 | PrimaryGeneratedColumn, 6 | } from 'typeorm'; 7 | 8 | @Entity() 9 | class Message { 10 | @PrimaryGeneratedColumn() 11 | public id: number; 12 | 13 | @Column() 14 | public content: string; 15 | 16 | @CreateDateColumn() 17 | createdAt: Date; 18 | } 19 | 20 | export default Message; 21 | -------------------------------------------------------------------------------- /src/message/message.gateway.ts: -------------------------------------------------------------------------------- 1 | import { Logger } from '@nestjs/common'; 2 | import { 3 | OnGatewayConnection, 4 | OnGatewayDisconnect, 5 | OnGatewayInit, 6 | SubscribeMessage, 7 | WebSocketGateway, 8 | WebSocketServer, 9 | } from '@nestjs/websockets'; 10 | import { Server, Socket } from 'socket.io'; 11 | import { MessagesService } from './messages.service'; 12 | 13 | @WebSocketGateway({ cors: true }) 14 | export class MessageGateway 15 | implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect 16 | { 17 | constructor(private readonly messagesService: MessagesService) {} 18 | 19 | private logger: Logger = new Logger('MessageGateway'); 20 | 21 | @WebSocketServer() wss: Server; 22 | 23 | afterInit(server: Server) { 24 | this.logger.log('Initialized'); 25 | } 26 | 27 | handleDisconnect(client: Socket) { 28 | this.logger.log(`Client Disconnected: ${client.id}`); 29 | } 30 | 31 | handleConnection(client: Socket, ...args: any[]) { 32 | this.logger.log(`Client Connected: ${client.id}`); 33 | } 34 | 35 | @SubscribeMessage('sendMessage') 36 | async handleSendMessage(client: Socket, payload: string): Promise { 37 | const newMessage = await this.messagesService.createMessage(payload); 38 | this.wss.emit('receiveMessage', newMessage); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/message/message.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { MessagesController } from './messages.controller'; 3 | import { MessagesService } from './messages.service'; 4 | import Message from './message.entity'; 5 | import { TypeOrmModule } from '@nestjs/typeorm'; 6 | import { MessageGateway } from './message.gateway'; 7 | 8 | @Module({ 9 | imports: [TypeOrmModule.forFeature([Message])], 10 | controllers: [MessagesController], 11 | providers: [MessagesService, MessageGateway], 12 | }) 13 | export class MessagesModule {} 14 | -------------------------------------------------------------------------------- /src/message/messages.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, Controller, Get, Param, Post } from '@nestjs/common'; 2 | import Message from './message.entity'; 3 | import { MessagesService } from './messages.service'; 4 | 5 | @Controller('messages') 6 | export class MessagesController { 7 | constructor(private readonly messagesService: MessagesService) {} 8 | 9 | @Get() 10 | async getAllMessages(): Promise { 11 | const messages = await this.messagesService.getAllMessages(); 12 | return messages; 13 | } 14 | 15 | @Get(':id') 16 | async getMessageById(@Param('id') id: string): Promise { 17 | const message = await this.messagesService.getMessageById(Number(id)); 18 | return message; 19 | } 20 | 21 | @Post() 22 | async createMessage(@Body('content') content: string) { 23 | const newMessage = await this.messagesService.createMessage(content); 24 | return newMessage; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/message/messages.service.ts: -------------------------------------------------------------------------------- 1 | import { NotFoundException } from '@nestjs/common'; 2 | import { InjectRepository } from '@nestjs/typeorm'; 3 | import { Repository } from 'typeorm'; 4 | import Message from './message.entity'; 5 | import { MessageGateway } from './message.gateway'; 6 | 7 | export class MessagesService { 8 | constructor( 9 | @InjectRepository(Message) 10 | private messagesRepository: Repository, 11 | ) {} 12 | 13 | async getAllMessages() { 14 | const messages = this.messagesRepository.find(); 15 | return messages; 16 | } 17 | 18 | async getMessageById(id: number) { 19 | const message = await this.messagesRepository.findOne({ 20 | where: { 21 | id: id, 22 | }, 23 | }); 24 | if (message) { 25 | return message; 26 | } 27 | throw new NotFoundException('Could not find the message'); 28 | } 29 | 30 | async createMessage(content: string) { 31 | const newMessage = await this.messagesRepository.create({ content }); 32 | await this.messagesRepository.save(newMessage); 33 | return newMessage; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /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 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false 20 | } 21 | } 22 | --------------------------------------------------------------------------------