├── .prettierrc ├── src ├── auth │ ├── constants.ts │ ├── jwt-auth.guard.ts │ ├── local-auth.guard.ts │ ├── dto │ │ └── login.dto.ts │ ├── auth.service.spec.ts │ ├── jwt.strategy.ts │ ├── local.strategy.ts │ ├── auth.module.ts │ └── auth.service.ts ├── ws │ ├── event.module.ts │ └── envent.gateway.ts ├── user │ ├── dto │ │ ├── update-user.dto.ts │ │ ├── has-avatar.dto.ts │ │ ├── upload-avatar.dto.ts │ │ └── create-user.dto.ts │ ├── model │ │ └── user.model.ts │ ├── user.module.ts │ ├── user.service.spec.ts │ ├── user.controller.spec.ts │ ├── user.controller.ts │ └── user.service.ts ├── message │ ├── dto │ │ ├── update-message.dto.ts │ │ ├── find-messageList.dto.ts │ │ └── create-message.dto.ts │ ├── model │ │ └── message.model.ts │ ├── message.service.spec.ts │ ├── message.module.ts │ ├── message.controller.spec.ts │ ├── message.controller.ts │ └── message.service.ts ├── app.controller.spec.ts ├── main.ts ├── app.controller.ts ├── app.module.ts └── app.service.ts ├── tsconfig.build.json ├── nest-cli.json ├── test ├── jest-e2e.json └── app.e2e-spec.ts ├── .gitignore ├── tsconfig.json ├── .eslintrc.js ├── README.md └── package.json /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /src/auth/constants.ts: -------------------------------------------------------------------------------- 1 | export const jwtConstants = { 2 | secret: 'secretKey', 3 | }; -------------------------------------------------------------------------------- /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/auth/jwt-auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { AuthGuard } from '@nestjs/passport'; 3 | 4 | @Injectable() 5 | export class JwtAuthGuard extends AuthGuard('jwt') { } -------------------------------------------------------------------------------- /src/auth/local-auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { AuthGuard } from '@nestjs/passport'; 3 | 4 | @Injectable() 5 | export class LocalAuthGuard extends AuthGuard('local') { } -------------------------------------------------------------------------------- /src/ws/event.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from "@nestjs/common"; 2 | import { EventsGateway } from "./envent.gateway"; 3 | 4 | @Module({ 5 | providers: [EventsGateway] 6 | }) 7 | export class EventsModule { } -------------------------------------------------------------------------------- /src/user/dto/update-user.dto.ts: -------------------------------------------------------------------------------- 1 | import { PartialType } from '@nestjs/mapped-types'; 2 | import { CreateUserDto } from './create-user.dto'; 3 | 4 | export class UpdateUserDto extends PartialType(CreateUserDto) {} 5 | -------------------------------------------------------------------------------- /src/message/dto/update-message.dto.ts: -------------------------------------------------------------------------------- 1 | import { PartialType } from '@nestjs/swagger'; 2 | import { CreateMessageDto } from './create-message.dto'; 3 | 4 | export class UpdateMessageDto extends PartialType(CreateMessageDto) {} 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/user/model/user.model.ts: -------------------------------------------------------------------------------- 1 | import { Column, Model, Table } from 'sequelize-typescript'; 2 | 3 | @Table 4 | export class User extends Model { 5 | @Column 6 | username: string; 7 | @Column 8 | password: string; 9 | @Column 10 | avatar: string; 11 | } -------------------------------------------------------------------------------- /src/user/dto/has-avatar.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from "@nestjs/swagger"; 2 | import { IsNotEmpty } from "class-validator"; 3 | 4 | export class hasAvatarDto { 5 | @IsNotEmpty() 6 | @ApiProperty({ 7 | default: "yang", 8 | description: "创建用户姓名" 9 | }) 10 | username: string; 11 | } 12 | -------------------------------------------------------------------------------- /src/auth/dto/login.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from "@nestjs/swagger"; 2 | 3 | export class LoginDTO { 4 | @ApiProperty({ 5 | default: "boyyang", 6 | required:true 7 | }) 8 | username: string; 9 | 10 | @ApiProperty({ 11 | default: "haoshuai", 12 | required: true 13 | }) 14 | password: string; 15 | } -------------------------------------------------------------------------------- /src/message/model/message.model.ts: -------------------------------------------------------------------------------- 1 | import { Column, Model, Table } from 'sequelize-typescript'; 2 | 3 | @Table 4 | export class Message extends Model { 5 | @Column 6 | content: string; 7 | @Column 8 | userId: number; 9 | @Column 10 | username: string; 11 | @Column 12 | sender: string; 13 | @Column 14 | receiver: string; 15 | 16 | } -------------------------------------------------------------------------------- /src/user/dto/upload-avatar.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from "@nestjs/swagger"; 2 | import { IsNotEmpty } from "class-validator"; 3 | 4 | export class uploadAvatarDto { 5 | @IsNotEmpty() 6 | @ApiProperty({ 7 | default: "yang", 8 | description: "创建用户姓名" 9 | }) 10 | username: string; 11 | 12 | @IsNotEmpty() 13 | @ApiProperty({ 14 | default: '2365539910' 15 | }) 16 | avatar: string; 17 | } 18 | -------------------------------------------------------------------------------- /src/user/user.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { SequelizeModule } from '@nestjs/sequelize'; 3 | import { User } from './model/user.model'; 4 | import { UserController } from './user.controller'; 5 | import { UserService } from './user.service'; 6 | 7 | @Module({ 8 | imports: [SequelizeModule.forFeature([User])], 9 | providers: [UserService], 10 | controllers: [UserController], 11 | exports: [UserService], 12 | }) 13 | export class UserModule { } -------------------------------------------------------------------------------- /src/message/dto/find-messageList.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from "@nestjs/swagger"; 2 | 3 | export class findMessageListDTO { 4 | @ApiProperty({ 5 | default: 'yang', 6 | description: '消息发送者', 7 | example: 'yang', 8 | required: true, 9 | }) 10 | 11 | username: string; 12 | @ApiProperty({ 13 | default: 'xiaoxin', 14 | description: '当前聊天对象', 15 | example: 'xiaoxin', 16 | required: true, 17 | }) 18 | currentChater: string; 19 | } 20 | -------------------------------------------------------------------------------- /src/auth/auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AuthService } from './auth.service'; 3 | 4 | describe('AuthService', () => { 5 | let service: AuthService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [AuthService], 10 | }).compile(); 11 | 12 | service = module.get(AuthService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 -------------------------------------------------------------------------------- /src/message/message.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { MessageService } from './message.service'; 3 | 4 | describe('MessageService', () => { 5 | let service: MessageService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [MessageService], 10 | }).compile(); 11 | 12 | service = module.get(MessageService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/message/message.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { MessageService } from './message.service'; 3 | import { MessageController } from './message.controller'; 4 | import { SequelizeModule } from '@nestjs/sequelize'; 5 | import { Message } from './model/message.model'; 6 | import { CreateMessageDto } from './dto/create-message.dto'; 7 | 8 | @Module({ 9 | imports: [SequelizeModule.forFeature([Message])], 10 | providers: [MessageService], 11 | controllers: [MessageController], 12 | exports: [MessageService], 13 | }) 14 | export class MessageModule { } 15 | -------------------------------------------------------------------------------- /src/user/dto/create-user.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from "@nestjs/swagger"; 2 | import { IsNotEmpty} from "class-validator"; 3 | 4 | export class CreateUserDto { 5 | @IsNotEmpty() 6 | @ApiProperty({ 7 | default: "boyyang", 8 | description:"创建用户姓名" 9 | }) 10 | username: string; 11 | 12 | @IsNotEmpty() 13 | @ApiProperty({ 14 | default:'haoshuai' 15 | }) 16 | password: string; 17 | 18 | @IsNotEmpty() 19 | @ApiProperty({ 20 | default: 'https://api.multiavatar.com/Binx%$77231.png' 21 | }) 22 | avatar: string; 23 | } 24 | -------------------------------------------------------------------------------- /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/user/user.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UserController } from './user.controller'; 3 | import { UserService } from './user.service'; 4 | 5 | describe('UserController', () => { 6 | let controller: UserController; 7 | 8 | beforeEach(async () => { 9 | const module: TestingModule = await Test.createTestingModule({ 10 | controllers: [UserController], 11 | providers: [UserService], 12 | }).compile(); 13 | 14 | controller = module.get(UserController); 15 | }); 16 | 17 | it('should be defined', () => { 18 | expect(controller).toBeDefined(); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /src/auth/jwt.strategy.ts: -------------------------------------------------------------------------------- 1 | import { ExtractJwt, Strategy } from 'passport-jwt'; 2 | import { PassportStrategy } from '@nestjs/passport'; 3 | import { Injectable } from '@nestjs/common'; 4 | import { jwtConstants } from './constants'; 5 | 6 | @Injectable() 7 | export class JwtStrategy extends PassportStrategy(Strategy) { 8 | constructor() { 9 | super({ 10 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 11 | ignoreExpiration: false, 12 | secretOrKey: jwtConstants.secret, 13 | }); 14 | } 15 | 16 | async validate(payload: any) { 17 | return { userId: payload.sub, username: payload.username }; 18 | } 19 | } -------------------------------------------------------------------------------- /src/message/dto/create-message.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from "@nestjs/swagger"; 2 | 3 | export class CreateMessageDto { 4 | @ApiProperty({ 5 | default: 'Hello', 6 | description: '消息内容', 7 | example: 'Hello', 8 | required: true, 9 | }) 10 | content: string; 11 | @ApiProperty({ 12 | default: 'yang', 13 | description: '消息发送者', 14 | example: 'yang', 15 | required: true, 16 | }) 17 | sender: string; 18 | 19 | @ApiProperty({ 20 | default: 'xiaoxin', 21 | description: '消息接收者', 22 | example: 'xiaoxin', 23 | required: true, 24 | }) 25 | receiver: string; 26 | } 27 | -------------------------------------------------------------------------------- /src/message/message.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { MessageController } from './message.controller'; 3 | import { MessageService } from './message.service'; 4 | 5 | describe('MessageController', () => { 6 | let controller: MessageController; 7 | 8 | beforeEach(async () => { 9 | const module: TestingModule = await Test.createTestingModule({ 10 | controllers: [MessageController], 11 | providers: [MessageService], 12 | }).compile(); 13 | 14 | controller = module.get(MessageController); 15 | }); 16 | 17 | it('should be defined', () => { 18 | expect(controller).toBeDefined(); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /src/auth/local.strategy.ts: -------------------------------------------------------------------------------- 1 | import { Strategy } from 'passport-local'; 2 | import { PassportStrategy } from '@nestjs/passport'; 3 | import { Injectable, UnauthorizedException } from '@nestjs/common'; 4 | import { AuthService } from './auth.service'; 5 | 6 | @Injectable() 7 | export class LocalStrategy extends PassportStrategy(Strategy) { 8 | constructor(private authService: AuthService) { 9 | super(); 10 | } 11 | 12 | async validate(username: string, password: string): Promise { 13 | const user = await this.authService.validateUser(username, password); 14 | if (!user) { 15 | throw new UnauthorizedException(); 16 | } 17 | return user; 18 | } 19 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | import { SwaggerModule, DocumentBuilder, } from '@nestjs/swagger'; 4 | import { ValidationPipe } from '@nestjs/common'; 5 | 6 | async function bootstrap() { 7 | const app = await NestFactory.create(AppModule, { 8 | cors: true, 9 | }); 10 | 11 | const config = new DocumentBuilder() 12 | .addBearerAuth() 13 | //开启swagger文档登录验证token 14 | .setTitle('API接口文档') 15 | .setDescription('Yang的nest+swagger接口文档') 16 | .setVersion('1.0') 17 | .build(); 18 | const document = SwaggerModule.createDocument(app, config); 19 | SwaggerModule.setup('api', app, document); 20 | app.useGlobalPipes(new ValidationPipe()); 21 | await app.listen(3000); 22 | } 23 | bootstrap(); 24 | -------------------------------------------------------------------------------- /src/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AuthService } from './auth.service'; 3 | import { LocalStrategy } from './local.strategy'; 4 | import { UserModule } from '../user/user.module'; 5 | import { PassportModule } from '@nestjs/passport'; 6 | import { JwtModule } from '@nestjs/jwt'; 7 | import { jwtConstants } from './constants'; 8 | import { JwtStrategy } from './jwt.strategy'; 9 | 10 | @Module 11 | ({ 12 | imports: [ 13 | UserModule, 14 | PassportModule, 15 | JwtModule.register({ 16 | secret: jwtConstants.secret, 17 | signOptions: { expiresIn: '60s' }, 18 | }), 19 | ], 20 | providers: [AuthService, LocalStrategy, JwtStrategy], 21 | exports: [AuthService, JwtModule], 22 | }) 23 | export class AuthModule { } -------------------------------------------------------------------------------- /src/message/message.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common'; 2 | import { MessageService } from './message.service'; 3 | import { CreateMessageDto } from './dto/create-message.dto'; 4 | import { UpdateMessageDto } from './dto/update-message.dto'; 5 | import { findMessageListDTO } from './dto/find-messageList.dto'; 6 | 7 | @Controller('message') 8 | export class MessageController { 9 | constructor(private readonly messageService: MessageService) { } 10 | 11 | @Post('send') 12 | async create(@Body() createMessageDto: CreateMessageDto) { 13 | return await this.messageService.create(createMessageDto); 14 | } 15 | @Post('list') 16 | async findAll(@Body() findMessageListDTO: findMessageListDTO) { 17 | 18 | return await this.messageService.findMessageList(findMessageListDTO); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Post, UseGuards, Request, Bind, Body } from '@nestjs/common'; 2 | import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'; 3 | import { AppService } from './app.service'; 4 | import { AuthService } from './auth/auth.service'; 5 | import { LoginDTO } from './auth/dto/login.dto'; 6 | import { CreateUserDto } from './user/dto/create-user.dto'; 7 | 8 | @Controller() 9 | export class AppController { 10 | constructor( 11 | private readonly appService: AppService, 12 | private authService: AuthService 13 | ) { } 14 | 15 | @ApiTags('JWT登录注册') 16 | @Post('auth/register') 17 | async AuthRegister(@Body() user: CreateUserDto) { 18 | return await this.appService.register(user) 19 | } 20 | @ApiTags('JWT登录注册') 21 | @Post('auth/login') 22 | async AuthLogin(@Body() loginParmas: LoginDTO) { 23 | return await this.appService.login(loginParmas) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### A simple instant messaging backend API written with Nest+ WebSocket 2 | The main use of enterprise Node server framework Nestjs and socket.io to complete the main functions
3 | You can simply try this simple instant messaging web
4 | [点击这里进入即时通讯](http://101.43.191.122:3001) Here👈 5 | 6 | 7 | This project is perfect for those who want to become full stack
8 | 这个项目非常适合想要入门全栈开发的朋友练手
9 | You can whip this project through in a few hours
10 | 你可以在几个小时内迅速完成这个项目 11 | 12 | This is just the back-end of Node, and the front-end React18 page is here
13 | 这里仅仅是Node后端部分,前端React18写的页面在这里
14 | [点击这里进入前端部分](https://github.com/BoyYangzai/Instant-messaging-React18) Here👈 15 | 16 | 完成这个项目你可以学会:✨
17 | 操作服务器+数据库以及项目部署💪
18 | Nestjs+JWT+Websocket💪
19 | React18(Hooks)+Nextjs服务端渲染💪
20 | 成为一个合格的初级菜鸟全栈开发者 21 | 22 | To complete this project you can learn: ✨
23 | Operation server + database and project deployment 💪
24 | JWT Nestjs + + Websocket 💪
25 | React18(Hooks)+Nextjs server render 💪
26 | Become a qualified beginner full stack developer 27 |
-------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | import { SequelizeModule } from '@nestjs/sequelize' 5 | import { User } from './user/model/user.model'; 6 | import { UserModule } from './user/user.module'; 7 | import { AuthModule } from './auth/auth.module'; 8 | import { EventsModule } from './ws/event.module'; 9 | import { MessageModule } from './message/message.module'; 10 | import { Message } from './message/model/message.model'; 11 | 12 | @Module({ 13 | imports: [ 14 | SequelizeModule.forRoot({ 15 | dialect: 'mysql', 16 | host: 'localhost', 17 | port: 3306, 18 | username: 'yang', 19 | password: 'niupi666', 20 | database: 'nest', 21 | models: [User, Message], 22 | autoLoadModels: true 23 | }), 24 | SequelizeModule.forFeature([User, Message]), 25 | UserModule, 26 | AuthModule, 27 | EventsModule, 28 | MessageModule 29 | ], 30 | controllers: [AppController], 31 | providers: [ 32 | AppService, 33 | ], 34 | }) 35 | export class AppModule { } 36 | -------------------------------------------------------------------------------- /src/user/user.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Post, Body} from '@nestjs/common'; 2 | import { UserService } from './user.service'; 3 | import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'; 4 | import { uploadAvatarDto } from './dto/upload-avatar.dto'; 5 | import { hasAvatarDto } from './dto/has-avatar.dto'; 6 | 7 | 8 | 9 | @ApiTags('用户') 10 | @Controller('user') 11 | @ApiBearerAuth() 12 | export class UserController { 13 | constructor(private readonly userService: UserService) { } 14 | 15 | @Post('all') 16 | async findAll() { 17 | let res = await this.userService.findAll() 18 | return res 19 | } 20 | @Post('avatar') 21 | async uploadAvatar(@Body() body:uploadAvatarDto) { 22 | let { username, avatar } = body 23 | if (avatar.length < 20) { 24 | avatar = `https://q2.qlogo.cn/headimg_dl?dst_uin=${avatar}&spec=100` 25 | } 26 | let res = await this.userService.uploadAvatar(username, avatar) 27 | return res 28 | } 29 | @Post('hasavatar') 30 | async hasAvatar(@Body() body:hasAvatarDto ) { 31 | let { username } = body 32 | let res = await this.userService.hasAvatar(username) 33 | return res 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { UserService } from 'src/user/user.service'; 3 | import { JwtService } from '@nestjs/jwt'; 4 | import * as bcrypt from 'bcrypt'; 5 | @Injectable() 6 | export class AuthService { 7 | constructor( 8 | private userService: UserService, 9 | private jwtService: JwtService 10 | ) { } 11 | 12 | async validateUser(username: string, pass: string): Promise { 13 | const user = await this.userService.findOne(username); 14 | if (user) { 15 | const passwordCompare = await bcrypt.compare(pass, user.password) 16 | //https://docs.nestjs.com/security/encryption-and-hashing#encryption 17 | if (user && passwordCompare) { 18 | const { password, ...result } = user; 19 | return result; 20 | } 21 | return null 22 | } else { 23 | return null 24 | } 25 | } 26 | async login(user: any) { 27 | const payload = { username: user.username, sub: user.userId }; 28 | return { 29 | code: '200', 30 | access_token: this.jwtService.sign(payload), 31 | msg:'登录成功' 32 | }; 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /src/message/message.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { InjectModel } from '@nestjs/sequelize'; 3 | import { CreateMessageDto } from './dto/create-message.dto'; 4 | import { Message } from './model/message.model'; 5 | 6 | @Injectable() 7 | export class MessageService { 8 | constructor( 9 | @InjectModel(Message) private messageModel: typeof Message 10 | ) { } 11 | 12 | async create(createMessageDto: CreateMessageDto) { 13 | const time = Date.now() 14 | await this.messageModel.create(createMessageDto) 15 | return { 16 | code: '200', 17 | msg: '发送成功' 18 | } 19 | } 20 | async findMessageList(findMessageListObj) { 21 | console.log(findMessageListObj) 22 | const res1 = await this.messageModel.findAll({ 23 | where: { 24 | sender: findMessageListObj.username, 25 | receiver: findMessageListObj.currentChater 26 | } 27 | }) 28 | const res2 = await this.messageModel.findAll({ 29 | where: { 30 | sender: findMessageListObj.currentChater, 31 | receiver: findMessageListObj.username 32 | } 33 | }) 34 | return { 35 | code: '200', 36 | msg: '查询成功', 37 | data: { 38 | messageList: [ 39 | ...res1, 40 | ...res2 41 | ].sort((a, b) => a.id - b.id) 42 | } 43 | } 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { InjectModel } from '@nestjs/sequelize'; 3 | import * as bcrypt from 'bcrypt'; 4 | import { User } from './user/model/user.model'; 5 | import { AuthService } from './auth/auth.service'; 6 | @Injectable() 7 | export class AppService { 8 | 9 | constructor( 10 | @InjectModel(User) private userModel: typeof User, 11 | private authService: AuthService 12 | ) { } 13 | 14 | async register(user) { 15 | const hash = await bcrypt.hash(user.password, 10) 16 | const isNotExist = await this.userModel.findOne({ 17 | where: { 18 | username: user.username 19 | } 20 | }) 21 | if (!isNotExist) { 22 | const res = await this.userModel.build( 23 | { 24 | username: user.username, 25 | password: hash, 26 | avatar: user.avatar, 27 | } 28 | ) 29 | await res.save() 30 | return { 31 | code: '200', 32 | msg: "用户注册成功", 33 | } 34 | } else { 35 | return { 36 | code: '1001', 37 | msg: '该用户已经存在' 38 | } 39 | } 40 | } 41 | async login(loginParmas) { 42 | const authResult = await this.authService.validateUser(loginParmas.username, loginParmas.password); 43 | //验证是否是有效用户 44 | if (authResult) { 45 | return this.authService.login(authResult) 46 | } else { 47 | return { 48 | code: '1002', 49 | msg: "请检查用户名或密码是否正确" 50 | } 51 | } 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/ws/envent.gateway.ts: -------------------------------------------------------------------------------- 1 | import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WsResponse } from "@nestjs/websockets"; 2 | import { Socket } from "socket.io"; 3 | @WebSocketGateway(2999, { 4 | cors: { 5 | origin: '*', 6 | }, 7 | }) 8 | 9 | export class EventsGateway { 10 | @SubscribeMessage('events') 11 | chufashijian( 12 | @MessageBody() data: string, 13 | @ConnectedSocket() client: Socket, 14 | ): string { 15 | return data; 16 | } 17 | 18 | @SubscribeMessage('connection') 19 | t( 20 | @MessageBody() data: { 21 | username: string, 22 | }, 23 | @ConnectedSocket() client: Socket, 24 | ): WsResponse { 25 | client.emit('join', async (client) => { 26 | client.join(data.username); 27 | }) 28 | return { event: 'join', data: '服务端推送到客户端' }; 29 | //这里相当于服务端向客户端emit一个qaq事件 30 | } 31 | 32 | @SubscribeMessage('rtc') 33 | connection( 34 | @MessageBody() data: { 35 | id: string, 36 | }, 37 | @ConnectedSocket() client: Socket, 38 | ): WsResponse { 39 | return; 40 | } 41 | 42 | @SubscribeMessage('sendMessage') 43 | sendMessage( 44 | @MessageBody() data: { 45 | to: string, 46 | }, 47 | @ConnectedSocket() client: Socket, 48 | ): WsResponse { 49 | client.broadcast.emit('showMessage'); 50 | client.emit('showMessage') 51 | return; 52 | } 53 | 54 | 55 | } -------------------------------------------------------------------------------- /src/user/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { CreateUserDto } from './dto/create-user.dto'; 3 | import { InjectModel } from '@nestjs/sequelize'; 4 | import { User } from './model/user.model'; 5 | @Injectable() 6 | export class UserService { 7 | constructor(@InjectModel(User) private userModel: typeof User,) { 8 | 9 | } 10 | async create(createUserDto: CreateUserDto) { 11 | let res = await this.userModel.build({ 12 | ...createUserDto 13 | }) 14 | await res.save() 15 | return res 16 | } 17 | async findAll() { 18 | let res = await this.userModel.findAll() 19 | return res 20 | } 21 | async find(createUserDto: CreateUserDto) { 22 | let res = await this.userModel.findOne({ 23 | where: { 24 | ...createUserDto 25 | } 26 | }) 27 | return res 28 | } 29 | async findOne(username: string) { 30 | let res = await this.userModel.findOne({ 31 | where: { 32 | username 33 | } 34 | }) 35 | return res !== null ? res : null 36 | } 37 | async uploadAvatar(username: string, avatar: string) { 38 | let res = await this.userModel.update({ 39 | avatar 40 | }, { 41 | where: { 42 | username: username 43 | } 44 | }) 45 | return { 46 | code: '200', 47 | msg: "上传成功", 48 | data: res 49 | } 50 | } 51 | async hasAvatar(username: string) { 52 | let res = await this.userModel.findOne({ 53 | where: { 54 | username: username 55 | } 56 | }) 57 | return res.avatar !== null 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "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/jwt": "^8.0.1", 27 | "@nestjs/mapped-types": "*", 28 | "@nestjs/passport": "^8.2.1", 29 | "@nestjs/platform-express": "^8.0.0", 30 | "@nestjs/platform-socket.io": "^8.4.5", 31 | "@nestjs/sequelize": "^8.0.0", 32 | "@nestjs/swagger": "^5.2.1", 33 | "@nestjs/typeorm": "^8.0.4", 34 | "@nestjs/websockets": "^8.4.5", 35 | "bcrypt": "^5.0.1", 36 | "class-transformer": "^0.5.1", 37 | "class-validator": "^0.13.2", 38 | "mysql": "^2.18.1", 39 | "mysql2": "^2.3.3", 40 | "passport": "^0.5.3", 41 | "passport-jwt": "^4.0.0", 42 | "passport-local": "^1.0.0", 43 | "reflect-metadata": "^0.1.13", 44 | "rimraf": "^3.0.2", 45 | "rxjs": "^7.2.0", 46 | "sequelize": "^6.20.0", 47 | "sequelize-typescript": "^2.1.3", 48 | "swagger-ui-express": "^4.4.0", 49 | "typeorm": "^0.2.45" 50 | }, 51 | "devDependencies": { 52 | "@nestjs/cli": "^8.0.0", 53 | "@nestjs/schematics": "^8.0.0", 54 | "@nestjs/testing": "^8.0.0", 55 | "@types/bcrypt": "^5.0.0", 56 | "@types/express": "^4.17.13", 57 | "@types/jest": "27.5.0", 58 | "@types/node": "^16.0.0", 59 | "@types/passport-jwt": "^3.0.6", 60 | "@types/passport-local": "^1.0.34", 61 | "@types/sequelize": "^4.28.13", 62 | "@types/supertest": "^2.0.11", 63 | "@typescript-eslint/eslint-plugin": "^5.0.0", 64 | "@typescript-eslint/parser": "^5.0.0", 65 | "eslint": "^8.0.1", 66 | "eslint-config-prettier": "^8.3.0", 67 | "eslint-plugin-prettier": "^4.0.0", 68 | "jest": "28.0.3", 69 | "prettier": "^2.3.2", 70 | "source-map-support": "^0.5.20", 71 | "supertest": "^6.1.3", 72 | "ts-jest": "28.0.1", 73 | "ts-loader": "^9.2.3", 74 | "ts-node": "^10.0.0", 75 | "tsconfig-paths": "4.0.0", 76 | "typescript": "^4.3.5" 77 | }, 78 | "jest": { 79 | "moduleFileExtensions": [ 80 | "js", 81 | "json", 82 | "ts" 83 | ], 84 | "rootDir": "src", 85 | "testRegex": ".*\\.spec\\.ts$", 86 | "transform": { 87 | "^.+\\.(t|j)s$": "ts-jest" 88 | }, 89 | "collectCoverageFrom": [ 90 | "**/*.(t|j)s" 91 | ], 92 | "coverageDirectory": "../coverage", 93 | "testEnvironment": "node" 94 | } 95 | } 96 | --------------------------------------------------------------------------------