├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── README.md ├── nest-cli.json ├── package-lock.json ├── package.json ├── src ├── app.controller.spec.ts ├── app.controller.ts ├── app.gateway.spec.ts ├── app.gateway.ts ├── app.module.ts ├── app.service.ts ├── chat.entity.ts └── main.ts ├── static └── app.js ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json ├── tsconfig.json └── views └── index.ejs /.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 -------------------------------------------------------------------------------- /.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 | # Chat-with-Nestjs 75 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nestchat", 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/passport": "^8.2.1", 27 | "@nestjs/platform-express": "^8.0.0", 28 | "@nestjs/platform-socket.io": "^8.4.4", 29 | "@nestjs/typeorm": "^8.0.3", 30 | "@nestjs/websockets": "^8.4.4", 31 | "ejs": "^3.1.6", 32 | "hbs": "^4.2.0", 33 | "passport": "^0.5.2", 34 | "passport-local": "^1.0.0", 35 | "pg": "^8.7.3", 36 | "pg2": "^0.0.1", 37 | "reflect-metadata": "^0.1.13", 38 | "rimraf": "^3.0.2", 39 | "rxjs": "^7.2.0", 40 | "typeorm": "^0.2.45" 41 | }, 42 | "devDependencies": { 43 | "@nestjs/cli": "^8.0.0", 44 | "@nestjs/schematics": "^8.0.0", 45 | "@nestjs/testing": "^8.0.0", 46 | "@types/express": "^4.17.13", 47 | "@types/jest": "27.0.2", 48 | "@types/node": "^16.0.0", 49 | "@types/passport-local": "^1.0.34", 50 | "@types/supertest": "^2.0.11", 51 | "@typescript-eslint/eslint-plugin": "^5.0.0", 52 | "@typescript-eslint/parser": "^5.0.0", 53 | "eslint": "^8.0.1", 54 | "eslint-config-prettier": "^8.3.0", 55 | "eslint-plugin-prettier": "^4.0.0", 56 | "jest": "^27.2.5", 57 | "prettier": "^2.3.2", 58 | "source-map-support": "^0.5.20", 59 | "supertest": "^6.1.3", 60 | "ts-jest": "^27.0.3", 61 | "ts-loader": "^9.2.3", 62 | "ts-node": "^10.0.0", 63 | "tsconfig-paths": "^3.10.1", 64 | "typescript": "^4.3.5" 65 | }, 66 | "jest": { 67 | "moduleFileExtensions": [ 68 | "js", 69 | "json", 70 | "ts" 71 | ], 72 | "rootDir": "src", 73 | "testRegex": ".*\\.spec\\.ts$", 74 | "transform": { 75 | "^.+\\.(t|j)s$": "ts-jest" 76 | }, 77 | "collectCoverageFrom": [ 78 | "**/*.(t|j)s" 79 | ], 80 | "coverageDirectory": "../coverage", 81 | "testEnvironment": "node" 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /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, Render, Get, Res } from '@nestjs/common'; 2 | import { AppService } from './app.service'; 3 | import { Chat } from './chat.entity'; 4 | 5 | @Controller() 6 | export class AppController { 7 | constructor(private readonly appService: AppService) {} 8 | 9 | @Get('/chat') 10 | @Render('index') 11 | Home() { 12 | return { message: 'Hello world!' }; 13 | } 14 | 15 | @Get('/api/chat') 16 | async Chat(@Res() res) { 17 | const messages = await this.appService.getMessages(); 18 | res.json(messages); 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /src/app.gateway.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AppGateway } from './app.gateway'; 3 | 4 | describe('AppGateway', () => { 5 | let gateway: AppGateway; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [AppGateway], 10 | }).compile(); 11 | 12 | gateway = module.get(AppGateway); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(gateway).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/app.gateway.ts: -------------------------------------------------------------------------------- 1 | import { 2 | SubscribeMessage, 3 | WebSocketGateway, 4 | OnGatewayInit, 5 | WebSocketServer, 6 | OnGatewayConnection, 7 | OnGatewayDisconnect, 8 | } from '@nestjs/websockets'; 9 | import { Socket, Server } from 'socket.io'; 10 | import { AppService } from './app.service'; 11 | import { Chat } from './chat.entity'; 12 | @WebSocketGateway({ 13 | cors: { 14 | origin: '*', 15 | }, 16 | }) 17 | export class AppGateway 18 | implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect 19 | { 20 | constructor(private appService: AppService) {} 21 | 22 | @WebSocketServer() server: Server; 23 | 24 | @SubscribeMessage('sendMessage') 25 | async handleSendMessage(client: Socket, payload: Chat): Promise { 26 | await this.appService.createMessage(payload); 27 | this.server.emit('recMessage', payload); 28 | } 29 | 30 | afterInit(server: Server) { 31 | console.log(server); 32 | //Do stuffs 33 | } 34 | 35 | handleDisconnect(client: Socket) { 36 | console.log(`Disconnected: ${client.id}`); 37 | //Do stuffs 38 | } 39 | 40 | handleConnection(client: Socket, ...args: any[]) { 41 | console.log(`Connected ${client.id}`); 42 | //Do stuffs 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | import { AppGateway } from './app.gateway'; 5 | import { TypeOrmModule } from '@nestjs/typeorm'; 6 | import { Chat } from './chat.entity'; 7 | @Module({ 8 | imports: [ 9 | TypeOrmModule.forRoot({ 10 | type: 'postgres', 11 | host: 'localhost', 12 | username: 'postgres', 13 | password: '1234', 14 | database: 'task', 15 | entities: [Chat], 16 | synchronize: true, 17 | }), 18 | TypeOrmModule.forFeature([Chat]), 19 | // AuthModule, 20 | ], 21 | controllers: [AppController], 22 | providers: [AppService, AppGateway], 23 | }) 24 | export class AppModule {} 25 | -------------------------------------------------------------------------------- /src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { InjectRepository } from '@nestjs/typeorm'; 3 | import { Repository } from 'typeorm'; 4 | import { Chat } from './chat.entity'; 5 | 6 | @Injectable() 7 | export class AppService { 8 | constructor( 9 | @InjectRepository(Chat) private chatRepository: Repository, 10 | ) {} 11 | async createMessage(chat: Chat): Promise { 12 | return await this.chatRepository.save(chat); 13 | } 14 | 15 | async getMessages(): Promise { 16 | return await this.chatRepository.find(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/chat.entity.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Entity, 3 | Column, 4 | PrimaryGeneratedColumn, 5 | CreateDateColumn, 6 | } from 'typeorm'; 7 | 8 | @Entity() 9 | export class Chat { 10 | @PrimaryGeneratedColumn('uuid') 11 | id: number; 12 | 13 | @Column() 14 | email: string; 15 | 16 | @Column({ unique: true }) 17 | text: string; 18 | 19 | @CreateDateColumn() 20 | createdAt: Date; 21 | } 22 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | import { NestExpressApplication } from '@nestjs/platform-express'; 4 | import { join } from 'path'; 5 | 6 | async function bootstrap() { 7 | const app = await NestFactory.create(AppModule); 8 | app.useStaticAssets(join(__dirname, '..', 'static')); 9 | app.setBaseViewsDir(join(__dirname, '..', 'views')); 10 | app.setViewEngine('ejs'); 11 | await app.listen(3002); 12 | } 13 | bootstrap(); 14 | -------------------------------------------------------------------------------- /static/app.js: -------------------------------------------------------------------------------- 1 | const socket = io('http://localhost:3002'); 2 | const msgBox = document.getElementById('exampleFormControlTextarea1'); 3 | const msgCont = document.getElementById('data-container'); 4 | const email = document.getElementById('email'); 5 | 6 | //get old messages from the server 7 | const messages = []; 8 | function getMessages() { 9 | fetch('http://localhost:3002/api/chat') 10 | .then((response) => response.json()) 11 | .then((data) => { 12 | loadDate(data); 13 | data.forEach((el) => { 14 | messages.push(el); 15 | }); 16 | }) 17 | .catch((err) => console.error(err)); 18 | } 19 | getMessages(); 20 | 21 | //When a user press the enter key,send message. 22 | msgBox.addEventListener('keydown', (e) => { 23 | if (e.keyCode === 13) { 24 | sendMessage({ email: email.value, text: e.target.value }); 25 | e.target.value = ''; 26 | } 27 | }); 28 | 29 | //Display messages to the users 30 | function loadDate(data) { 31 | let messages = ''; 32 | data.map((message) => { 33 | messages += `
  • 34 | ${message.email} 35 | ${message.text} 36 |
  • `; 37 | }); 38 | msgCont.innerHTML = messages; 39 | } 40 | 41 | //socket.io 42 | //emit sendMessage event to send message 43 | function sendMessage(message) { 44 | socket.emit('sendMessage', message); 45 | } 46 | //Listen to recMessage event to get the messages sent by users 47 | socket.on('recMessage', (message) => { 48 | messages.push(message); 49 | loadDate(messages); 50 | }); 51 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 12 | 13 | Let Chat 14 | 15 | 16 | 17 | 22 |
    23 |
    24 |
      25 |
      26 |
      27 | 28 |
      29 |
      30 | 31 |
      32 |
      33 | 36 | 37 | 38 | 41 | 42 | 43 | 44 | --------------------------------------------------------------------------------