first commit
This commit is contained in:
commit
36234a7749
|
|
@ -0,0 +1,56 @@
|
|||
# compiled output
|
||||
/dist
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# Tests
|
||||
/coverage
|
||||
/.nyc_output
|
||||
|
||||
# IDEs and editors
|
||||
/.idea
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# temp directory
|
||||
.temp
|
||||
.tmp
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
|
||||
## Description
|
||||
|
||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||
|
||||
## Project setup
|
||||
|
||||
```bash
|
||||
$ npm install
|
||||
```
|
||||
|
||||
## Compile and run the project
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ npm run start
|
||||
|
||||
# watch mode
|
||||
$ npm run start:dev
|
||||
|
||||
# production mode
|
||||
$ npm run start:prod
|
||||
```
|
||||
|
||||
## Run tests
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ npm run test
|
||||
|
||||
# e2e tests
|
||||
$ npm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ npm run test:cov
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||
|
||||
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||
|
||||
```bash
|
||||
$ npm install -g @nestjs/mau
|
||||
$ mau deploy
|
||||
```
|
||||
|
||||
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||
|
||||
## Resources
|
||||
|
||||
Check out a few resources that may come in handy when working with NestJS:
|
||||
|
||||
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||
|
||||
## Support
|
||||
|
||||
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).
|
||||
|
||||
## Stay in touch
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
module.exports = {
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
project: 'tsconfig.json',
|
||||
tsconfigRootDir: __dirname,
|
||||
sourceType: 'module',
|
||||
},
|
||||
plugins: ['@typescript-eslint/eslint-plugin'],
|
||||
extends: [
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:prettier/recommended',
|
||||
],
|
||||
root: true,
|
||||
env: {
|
||||
node: true,
|
||||
jest: true,
|
||||
},
|
||||
ignorePatterns: ['.eslintrc.js'],
|
||||
rules: {
|
||||
'@typescript-eslint/interface-name-prefix': 'off',
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
'prettier/prettier': [
|
||||
'error',
|
||||
{
|
||||
endOfLine: 'auto',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,106 @@
|
|||
{
|
||||
"name": "server",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js",
|
||||
"migration:run": "npm run typeorm migration:run -- -d ./src/config/typeorm.ts",
|
||||
"migration:generate": "npm run typeorm -- -d ./src/config/typeorm.ts migration:generate ./src/migrations/$npm_config_name",
|
||||
"migration:create": "npm run typeorm -- migration:create ./src/migrations/$npm_config_name",
|
||||
"migration:revert": "npm run typeorm -- -d ./src/config/typeorm.ts migration:revert"
|
||||
},
|
||||
"dependencies": {
|
||||
"@faker-js/faker": "^9.9.0",
|
||||
"@keyv/redis": "^5.0.0",
|
||||
"@nestjs/cache-manager": "^3.0.1",
|
||||
"@nestjs/class-transformer": "^0.4.0",
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "^4.0.2",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/event-emitter": "^3.0.1",
|
||||
"@nestjs/jwt": "^11.0.0",
|
||||
"@nestjs/platform-express": "^11.1.5",
|
||||
"@nestjs/platform-socket.io": "^11.1.5",
|
||||
"@nestjs/throttler": "^6.4.0",
|
||||
"@nestjs/typeorm": "^11.0.0",
|
||||
"@nestjs/websockets": "^11.1.5",
|
||||
"bcrypt": "^6.0.0",
|
||||
"cache-manager": "^7.0.1",
|
||||
"cacheable": "^1.10.2",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.2",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"helmet": "^8.1.0",
|
||||
"image-size": "^2.0.2",
|
||||
"lodash": "^4.17.21",
|
||||
"multer": "^2.0.2",
|
||||
"mysql2": "^3.14.3",
|
||||
"nestjs-paginate": "^12.5.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"socket.io": "^4.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
"@eslint/js": "^9.18.0",
|
||||
"@nestjs/cli": "^11.0.0",
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/testing": "^11.0.1",
|
||||
"@swc/cli": "^0.6.0",
|
||||
"@swc/core": "^1.10.7",
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/cookie-parser": "^1.4.9",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/lodash": "^4.17.20",
|
||||
"@types/multer": "^2.0.0",
|
||||
"@types/node": "^22.10.7",
|
||||
"@types/supertest": "^6.0.2",
|
||||
"eslint": "^9.18.0",
|
||||
"eslint-config-prettier": "^10.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.2",
|
||||
"globals": "^16.0.0",
|
||||
"jest": "^29.7.0",
|
||||
"prettier": "^3.4.2",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-loader": "^9.5.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.7.3",
|
||||
"typescript-eslint": "^8.20.0"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { MessagesModule } from './modules/messages/messages.module';
|
||||
import { AppConfigsModule } from './modules/app-configs/app-configs.module';
|
||||
import { ConversationsModule } from './modules/conversations/conversations.module';
|
||||
|
||||
@Module({
|
||||
imports: [MessagesModule, AppConfigsModule, ConversationsModule],
|
||||
controllers: [],
|
||||
providers: [],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
import { registerAs } from '@nestjs/config';
|
||||
import { config as dotenvConfig } from 'dotenv';
|
||||
import { DataSource, DataSourceOptions } from 'typeorm';
|
||||
|
||||
dotenvConfig({ path: '.env' });
|
||||
|
||||
export const typeORMConfig = {
|
||||
type: 'mysql',
|
||||
host: `${process.env.DB_HOST}`,
|
||||
port: `${process.env.DB_PORT}`,
|
||||
username: `${process.env.DB_USERNAME}`,
|
||||
password: `${process.env.DB_PASSWORD}`,
|
||||
database: `${process.env.DB_NAME}`,
|
||||
charset: 'utf8mb4_unicode_ci',
|
||||
entities: ['dist/**/*.entity{.ts,.js}'],
|
||||
migrations: ['dist/migrations/*{.ts,.js}'],
|
||||
autoLoadEntities: true,
|
||||
synchronize: true,
|
||||
retryAttempts: 3,
|
||||
retryDelay: 3000,
|
||||
logging: false,
|
||||
};
|
||||
|
||||
export default registerAs('typeorm', () => typeORMConfig);
|
||||
export const connectionSource = new DataSource(
|
||||
typeORMConfig as DataSourceOptions,
|
||||
);
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
OneToMany,
|
||||
PrimaryColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { Message } from './message.entity';
|
||||
|
||||
@Entity('conversations')
|
||||
export class Conversation {
|
||||
@PrimaryColumn({ type: 'varchar', length: 400 })
|
||||
id: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
name: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
type: 'group' | 'personal';
|
||||
|
||||
@CreateDateColumn()
|
||||
created_at: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updated_at: Date;
|
||||
|
||||
@OneToMany(() => Message, (message) => message.group)
|
||||
messages: Message[];
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
import {
|
||||
Column,
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
CreateDateColumn,
|
||||
Unique,
|
||||
UpdateDateColumn,
|
||||
ManyToOne,
|
||||
JoinColumn,
|
||||
} from 'typeorm';
|
||||
import { Conversation } from './conversation.entity';
|
||||
|
||||
@Entity('messages')
|
||||
@Unique(['time_raw', 'room_id'])
|
||||
export class Message {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
name: string; // tên người gửi
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
message: string; // nội dung
|
||||
|
||||
@Column({ type: 'timestamp' })
|
||||
time: Date;
|
||||
|
||||
@Column({ type: 'bigint' })
|
||||
time_raw: number;
|
||||
|
||||
@Column({ type: 'bigint' })
|
||||
date_time: number;
|
||||
|
||||
@Column({ nullable: true })
|
||||
room_id: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
room_name: string;
|
||||
|
||||
@CreateDateColumn()
|
||||
created_at: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updated_at: Date;
|
||||
|
||||
@ManyToOne(() => Conversation, (group) => group.messages, {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'room_id', referencedColumnName: 'id' })
|
||||
group: Conversation;
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
import { NestFactory } from '@nestjs/core';
|
||||
import * as bodyParser from 'body-parser';
|
||||
import { useContainer } from 'class-validator';
|
||||
import * as cookieParser from 'cookie-parser';
|
||||
import helmet from 'helmet';
|
||||
import { AppModule } from './app.module';
|
||||
import { BadRequestExceptionFilter } from './system/filters/bad-request-exception-filter';
|
||||
import { AppValidationPipes } from './system/pipes/app-validation-pipe';
|
||||
|
||||
import * as fs from 'fs';
|
||||
|
||||
async function bootstrap() {
|
||||
const httpsOptions = {
|
||||
key: fs.readFileSync('ssl/key.pem'),
|
||||
cert: fs.readFileSync('ssl/cert.pem'),
|
||||
};
|
||||
|
||||
const app = await NestFactory.create(AppModule, {
|
||||
httpsOptions,
|
||||
});
|
||||
|
||||
const prefix_version = process.env.PREFIX_VERSION;
|
||||
|
||||
app.enableCors({
|
||||
origin: '*',
|
||||
methods: ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'],
|
||||
allowedHeaders: 'Content-Type, Authorization',
|
||||
// credentials: true,
|
||||
});
|
||||
|
||||
app.use(cookieParser());
|
||||
|
||||
app.setGlobalPrefix(prefix_version);
|
||||
|
||||
app.useGlobalFilters(new BadRequestExceptionFilter());
|
||||
|
||||
app.use(
|
||||
helmet({
|
||||
crossOriginResourcePolicy: false,
|
||||
}),
|
||||
);
|
||||
|
||||
// Set global body parser limits
|
||||
app.use(bodyParser.json({ limit: '10mb' })); // hoặc lớn hơn nếu cần
|
||||
app.use(bodyParser.urlencoded({ limit: '10mb', extended: true }));
|
||||
|
||||
app.useGlobalPipes(
|
||||
new AppValidationPipes({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
exceptionFactory: AppValidationPipes.exceptionFactory,
|
||||
}),
|
||||
);
|
||||
|
||||
useContainer(app.select(AppModule), { fallbackOnErrors: true });
|
||||
|
||||
await app.listen(Number(process.env.APP_PORT));
|
||||
// await app.listen(Number(process.env.APP_PORT), '172.18.10.21');
|
||||
}
|
||||
|
||||
bootstrap();
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
import { typeORMConfig } from '@/config/typeorm';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { EventEmitterModule } from '@nestjs/event-emitter';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { ThrottlerModule } from '@nestjs/throttler';
|
||||
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
}),
|
||||
ThrottlerModule.forRoot({
|
||||
throttlers: [
|
||||
{
|
||||
limit: 20,
|
||||
ttl: 60 * 1000,
|
||||
},
|
||||
],
|
||||
}),
|
||||
JwtModule.register({
|
||||
global: true,
|
||||
secret: process.env.SECRET_KEY,
|
||||
signOptions: { expiresIn: '15m' },
|
||||
}),
|
||||
EventEmitterModule.forRoot({ wildcard: true, global: true }),
|
||||
TypeOrmModule.forRoot({
|
||||
...(typeORMConfig as TypeOrmModuleOptions),
|
||||
}),
|
||||
],
|
||||
})
|
||||
export class AppConfigsModule {}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import { Controller, Get, Param } from '@nestjs/common';
|
||||
import { Paginate, PaginateQuery } from 'nestjs-paginate';
|
||||
import { ConversationsService } from './conversations.service';
|
||||
import { Conversation } from '@/entities/conversation.entity';
|
||||
|
||||
@Controller('conversations')
|
||||
export class ConversationsController {
|
||||
constructor(private readonly service: ConversationsService) {}
|
||||
|
||||
@Get('')
|
||||
getConversations(@Paginate() query: PaginateQuery) {
|
||||
return this.service.index(query);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
getConversation(@Param('id') id: Conversation['id']) {
|
||||
return this.service.getConversation(id);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { ConversationsController } from './conversations.controller';
|
||||
import { ConversationsService } from './conversations.service';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Conversation } from '@/entities/conversation.entity';
|
||||
import { MessagesModule } from '../messages/messages.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Conversation]), MessagesModule],
|
||||
controllers: [ConversationsController],
|
||||
providers: [ConversationsService],
|
||||
})
|
||||
export class ConversationsModule {}
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
import { Conversation } from '@/entities/conversation.entity';
|
||||
import AppResponse from '@/system/filters/response/app-response';
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { paginate, PaginateQuery } from 'nestjs-paginate';
|
||||
import { Repository } from 'typeorm';
|
||||
import { MessagesListener } from '../messages/messages.listener';
|
||||
import { SystemLang } from '@/system/lang/system.lang';
|
||||
import { Message } from '@/entities/message.entity';
|
||||
import { MessagesService } from '../messages/messages.service';
|
||||
import { CreateMessageDto } from '../messages/dtos/create-message.dto';
|
||||
|
||||
@Injectable()
|
||||
export class ConversationsService {
|
||||
constructor(
|
||||
@InjectRepository(Conversation)
|
||||
readonly repo: Repository<Conversation>,
|
||||
private event: MessagesListener,
|
||||
private messageService: MessagesService,
|
||||
) {}
|
||||
|
||||
async index(query: PaginateQuery) {
|
||||
await this.event.sendEvent(MessagesListener.EVENTS.GET_CONVERSATIONS, {});
|
||||
|
||||
try {
|
||||
const data = await this.event.waitForEvent<Conversation[]>(
|
||||
MessagesListener.EVENTS.RECEIVE_CONVERSATIONS,
|
||||
);
|
||||
|
||||
await this.repo.save(data);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
const result = await paginate(query, this.repo, {
|
||||
sortableColumns: ['created_at'],
|
||||
searchableColumns: ['name'],
|
||||
defaultLimit: 10,
|
||||
filterableColumns: {
|
||||
id: true,
|
||||
},
|
||||
maxLimit: 100,
|
||||
defaultSortBy: [['created_at', 'DESC']],
|
||||
});
|
||||
|
||||
return AppResponse.toPagination<Conversation>(result, true, Conversation);
|
||||
}
|
||||
|
||||
async getConversation(id: Conversation['id']) {
|
||||
await this.event.sendEvent(MessagesListener.EVENTS.GET_CONVERSATION, {
|
||||
id,
|
||||
});
|
||||
|
||||
try {
|
||||
const data = await this.event.waitForEvent<CreateMessageDto[]>(
|
||||
MessagesListener.EVENTS.RECEIVE_CONVERSATION,
|
||||
);
|
||||
|
||||
await this.messageService.bulkCreate(data);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
const result = await this.repo.findOne({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
const messages = await this.messageService.repo.find({
|
||||
where: { room_id: result.id },
|
||||
take: 20,
|
||||
});
|
||||
|
||||
result.messages = messages;
|
||||
|
||||
if (!result)
|
||||
throw new NotFoundException(
|
||||
AppResponse.toResponse(null, {
|
||||
message: SystemLang.getText('messages', 'no_data'),
|
||||
}),
|
||||
);
|
||||
|
||||
return AppResponse.toResponse(result);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
import { IsArray, ValidateNested } from 'class-validator';
|
||||
import { Type } from 'class-transformer'; // ⚠️ Đúng package
|
||||
import { CreateMessageDto } from './create-message.dto';
|
||||
|
||||
export class CreateBulkMessageDto {
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => CreateMessageDto)
|
||||
data: CreateMessageDto[];
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import { IsString, IsNumber, IsOptional } from 'class-validator';
|
||||
import { Expose } from '@nestjs/class-transformer';
|
||||
|
||||
export class CreateMessageDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Expose()
|
||||
name?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Expose()
|
||||
message?: string;
|
||||
|
||||
@IsNumber()
|
||||
@Expose()
|
||||
time: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Expose()
|
||||
room_id?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Expose()
|
||||
room_name?: string;
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import { IsNumber } from 'class-validator';
|
||||
import { SendMessageDto } from './send-message.dto';
|
||||
|
||||
export class ReplyMessageDto extends SendMessageDto {
|
||||
@IsNumber()
|
||||
time: number;
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
import { IsString } from 'class-validator';
|
||||
|
||||
export class SendMessageDto {
|
||||
@IsString()
|
||||
message: string;
|
||||
|
||||
@IsString()
|
||||
conversation_id: string;
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import { Body, Controller, Get, Post } from '@nestjs/common';
|
||||
import { MessagesService } from './messages.service';
|
||||
import { CreateMessageDto } from './dtos/create-message.dto';
|
||||
import { CreateBulkMessageDto } from './dtos/create-bulk-message.dto';
|
||||
import { SendMessageDto } from './dtos/send-message.dto';
|
||||
import { ReplyMessageDto } from './dtos/reply-message.dto';
|
||||
|
||||
@Controller('messages')
|
||||
export class MessagesController {
|
||||
constructor(private readonly service: MessagesService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() dto: CreateMessageDto) {
|
||||
return this.service.create(dto);
|
||||
}
|
||||
|
||||
@Post('send-message')
|
||||
sendMessage(@Body() data: SendMessageDto) {
|
||||
return this.service.sendMessage(data);
|
||||
}
|
||||
|
||||
@Post('reply-message')
|
||||
replyMessage(@Body() data: ReplyMessageDto) {
|
||||
return this.service.replyMessage(data);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import {
|
||||
MessageBody,
|
||||
OnGatewayConnection,
|
||||
SubscribeMessage,
|
||||
WebSocketGateway,
|
||||
WebSocketServer,
|
||||
} from '@nestjs/websockets';
|
||||
import { Server, Socket } from 'socket.io';
|
||||
import { MessagesListener } from './messages.listener';
|
||||
|
||||
@WebSocketGateway({
|
||||
cors: {
|
||||
origin: '*',
|
||||
},
|
||||
})
|
||||
export class MessagesGateway implements OnGatewayConnection {
|
||||
@WebSocketServer()
|
||||
server: Server;
|
||||
|
||||
constructor(private event: EventEmitter2) {}
|
||||
|
||||
async onModuleInit() {
|
||||
const eventsToForward = [
|
||||
MessagesListener.EVENTS.GET_CONVERSATIONS,
|
||||
MessagesListener.EVENTS.GET_CONVERSATION,
|
||||
MessagesListener.EVENTS.SEND_MESSAGE,
|
||||
MessagesListener.EVENTS.REPLY_MESSAGE,
|
||||
];
|
||||
|
||||
for (const event of eventsToForward) {
|
||||
this.event.on(event, (data) => {
|
||||
this.server.emit(event, data);
|
||||
});
|
||||
}
|
||||
}
|
||||
async handleConnection(client: Socket) {
|
||||
console.log(`📢 Client connected: ${client.id}`);
|
||||
}
|
||||
|
||||
@SubscribeMessage(MessagesListener.EVENTS.RECEIVE_CONVERSATIONS)
|
||||
async handleReiveConversations(@MessageBody() data: any) {
|
||||
this.event.emit(MessagesListener.EVENTS.RECEIVE_CONVERSATIONS, data);
|
||||
}
|
||||
|
||||
@SubscribeMessage(MessagesListener.EVENTS.RECEIVE_CONVERSATION)
|
||||
async handleReiveConversation(@MessageBody() data: any) {
|
||||
this.event.emit(MessagesListener.EVENTS.RECEIVE_CONVERSATION, data);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
// user.listener.ts
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
|
||||
@Injectable()
|
||||
export class MessagesListener {
|
||||
public static EVENTS = {
|
||||
GET_CONVERSATIONS: 'messages.get-conversations',
|
||||
GET_CONVERSATION: 'messages.get-conversation',
|
||||
RECEIVE_CONVERSATIONS: 'messages.receive-conversations',
|
||||
RECEIVE_CONVERSATION: 'messages.receive-conversation',
|
||||
SEND_MESSAGE: 'messages.send-messsage',
|
||||
REPLY_MESSAGE: 'messages.reply-messsage',
|
||||
};
|
||||
|
||||
constructor(private event: EventEmitter2) {}
|
||||
|
||||
public async waitForEvent<T>(
|
||||
eventName: string,
|
||||
timeoutMs = 10000,
|
||||
): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.event.off(eventName, listener); // cleanup
|
||||
resolve(null); // hoặc reject(new Error('Timeout')) nếu muốn
|
||||
}, timeoutMs);
|
||||
|
||||
const listener = (data: any) => {
|
||||
clearTimeout(timer);
|
||||
this.event.off(eventName, listener); // cleanup
|
||||
resolve(data);
|
||||
};
|
||||
|
||||
this.event.on(eventName, listener);
|
||||
});
|
||||
}
|
||||
|
||||
public async sendEvent<T>(eventName: string, data: T) {
|
||||
return this.event.emit(eventName, data);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { MessagesService } from './messages.service';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Message } from '@/entities/message.entity';
|
||||
import { MessagesController } from './messages.controller';
|
||||
import { MessagesGateway } from './messages.gateway';
|
||||
import { MessagesListener } from './messages.listener';
|
||||
import { EventEmitterModule } from '@nestjs/event-emitter';
|
||||
import { Conversation } from '@/entities/conversation.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Message, Conversation])],
|
||||
providers: [MessagesService, MessagesGateway, MessagesListener],
|
||||
controllers: [MessagesController],
|
||||
exports: [MessagesGateway, MessagesService, MessagesListener],
|
||||
})
|
||||
export class MessagesModule {}
|
||||
|
|
@ -0,0 +1,146 @@
|
|||
import { Message } from '@/entities/message.entity';
|
||||
import AppResponse from '@/system/filters/response/app-response';
|
||||
import { SystemLang } from '@/system/lang/system.lang';
|
||||
import {
|
||||
BadRequestException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { In, Repository } from 'typeorm';
|
||||
import { CreateMessageDto } from './dtos/create-message.dto';
|
||||
import { MessagesListener } from './messages.listener';
|
||||
import { Conversation } from '@/entities/conversation.entity';
|
||||
import { SendMessageDto } from './dtos/send-message.dto';
|
||||
import { ConversationsService } from '../conversations/conversations.service';
|
||||
import { ReplyMessageDto } from './dtos/reply-message.dto';
|
||||
@Injectable()
|
||||
export class MessagesService {
|
||||
constructor(
|
||||
@InjectRepository(Message)
|
||||
readonly repo: Repository<Message>,
|
||||
@InjectRepository(Conversation)
|
||||
readonly conversationRepo: Repository<Conversation>,
|
||||
private event: MessagesListener,
|
||||
) {}
|
||||
|
||||
async create(dto: CreateMessageDto): Promise<Message> {
|
||||
const time = new Date(dto.time);
|
||||
|
||||
const existing = await this.repo.findOne({
|
||||
where: { time_raw: dto.time, room_id: dto.room_id },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
return existing; // hoặc throw error nếu muốn
|
||||
}
|
||||
|
||||
const entity = this.repo.create({
|
||||
...dto,
|
||||
time,
|
||||
time_raw: dto.time,
|
||||
});
|
||||
|
||||
return this.repo.save(entity);
|
||||
}
|
||||
|
||||
async bulkCreate(dtos: CreateMessageDto[]): Promise<Message[]> {
|
||||
const conditions = dtos.map((dto) => ({
|
||||
time_raw: dto.time,
|
||||
room_id: dto.room_id ?? null,
|
||||
}));
|
||||
|
||||
// Dùng QueryBuilder để tìm các message đã tồn tại
|
||||
const qb = this.repo.createQueryBuilder('message');
|
||||
conditions.forEach((cond, i) => {
|
||||
const timeParam = `time_${i}`;
|
||||
const roomParam = `room_${i}`;
|
||||
const clause = cond.room_id
|
||||
? `(message.time_raw = :${timeParam} AND message.room_id = :${roomParam})`
|
||||
: `(message.time_raw = :${timeParam} AND message.room_id IS NULL)`;
|
||||
if (i === 0) {
|
||||
qb.where(clause);
|
||||
} else {
|
||||
qb.orWhere(clause);
|
||||
}
|
||||
qb.setParameter(timeParam, cond.time_raw);
|
||||
if (cond.room_id) qb.setParameter(roomParam, cond.room_id);
|
||||
});
|
||||
const existingMessages = await qb.getMany();
|
||||
|
||||
const existingMap = new Map<string, Message>();
|
||||
for (const m of existingMessages) {
|
||||
const key = `${m.time_raw}-${m.room_id ?? ''}`;
|
||||
existingMap.set(key, m);
|
||||
}
|
||||
|
||||
const toUpdate: Message[] = [];
|
||||
const toCreate: Message[] = [];
|
||||
|
||||
for (const dto of dtos) {
|
||||
const time = new Date(dto.time);
|
||||
const key = `${dto.time}-${dto.room_id ?? ''}`;
|
||||
const entity = this.repo.create({ ...dto, time, time_raw: dto.time });
|
||||
|
||||
const existing = existingMap.get(key);
|
||||
if (existing) {
|
||||
entity.id = existing.id;
|
||||
toUpdate.push(entity);
|
||||
} else {
|
||||
toCreate.push(entity);
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await this.repo.save(toUpdate);
|
||||
const created = await this.repo.save(toCreate);
|
||||
|
||||
return [...updated, ...created];
|
||||
}
|
||||
|
||||
async sendMessage(data: SendMessageDto) {
|
||||
const conversation = await this.conversationRepo.findOne({
|
||||
where: { id: data.conversation_id },
|
||||
});
|
||||
|
||||
if (!conversation)
|
||||
throw new NotFoundException(
|
||||
AppResponse.toResponse(null, {
|
||||
message: SystemLang.getText('messages', 'not_found'),
|
||||
status_code: HttpStatus.NOT_FOUND,
|
||||
}),
|
||||
);
|
||||
|
||||
this.event.sendEvent(MessagesListener.EVENTS.SEND_MESSAGE, data);
|
||||
|
||||
return AppResponse.toResponse({
|
||||
conversation,
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
async replyMessage(data: ReplyMessageDto) {
|
||||
const conversation = await this.conversationRepo.findOne({
|
||||
where: {
|
||||
id: data.conversation_id,
|
||||
messages: { time_raw: data.time },
|
||||
},
|
||||
relations: { messages: true },
|
||||
});
|
||||
|
||||
if (!conversation)
|
||||
throw new NotFoundException(
|
||||
AppResponse.toResponse(null, {
|
||||
message: SystemLang.getText('messages', 'not_found'),
|
||||
status_code: HttpStatus.NOT_FOUND,
|
||||
}),
|
||||
);
|
||||
|
||||
this.event.sendEvent(MessagesListener.EVENTS.REPLY_MESSAGE, data);
|
||||
|
||||
return AppResponse.toResponse({
|
||||
conversation,
|
||||
data,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import {
|
||||
ExceptionFilter,
|
||||
Catch,
|
||||
ArgumentsHost,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { Request, Response } from 'express';
|
||||
import AppResponse from './response/app-response';
|
||||
|
||||
@Catch(BadRequestException)
|
||||
export class BadRequestExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: BadRequestException, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
const request = ctx.getRequest<Request>();
|
||||
const status = exception.getStatus();
|
||||
|
||||
const jsonException = JSON.stringify(exception.getResponse());
|
||||
|
||||
if (
|
||||
jsonException.includes('status_code') ||
|
||||
jsonException.includes('Validation pipes failed')
|
||||
) {
|
||||
response.status(status).json(exception.getResponse());
|
||||
} else {
|
||||
response.status(status).json(
|
||||
AppResponse.toResponse(null, {
|
||||
message: exception.getResponse()['message'] ?? '',
|
||||
status_code: status,
|
||||
bonus: { errors: exception.getResponse()['error'] },
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,105 @@
|
|||
import { SystemLang } from '@/system/lang/system.lang';
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
import { plainToClass, plainToInstance } from 'class-transformer';
|
||||
import { FilterOperator, FilterSuffix, Paginated } from 'nestjs-paginate';
|
||||
import { Column } from 'nestjs-paginate/lib/helper';
|
||||
|
||||
export default class AppResponse {
|
||||
public static toResponse(
|
||||
data: any,
|
||||
options?: { message?: string; status_code?: number; bonus?: any },
|
||||
) {
|
||||
return {
|
||||
message:
|
||||
options?.message ||
|
||||
(!Boolean(data)
|
||||
? SystemLang.getText('messages', 'default_action')
|
||||
: SystemLang.getText('messages', 'success')),
|
||||
status_code:
|
||||
options?.status_code || (!Boolean(data) ? HttpStatus.BAD_REQUEST : 200),
|
||||
data: data,
|
||||
timestamp: new Date().toISOString(),
|
||||
...(options?.bonus || {}),
|
||||
};
|
||||
}
|
||||
|
||||
public static plainToInStance<M>(this: new (...args: any[]) => M, obj: M): M {
|
||||
return plainToClass(this, obj);
|
||||
}
|
||||
|
||||
public static toPagination<M>(
|
||||
{ data, meta }: Paginated<M>,
|
||||
transform = true,
|
||||
dtoClass?: new () => M,
|
||||
) {
|
||||
const transformedData =
|
||||
transform && dtoClass
|
||||
? data.map((item) => plainToClass(dtoClass, item))
|
||||
: data;
|
||||
|
||||
return this.toResponse(plainToInstance(dtoClass, transformedData), {
|
||||
bonus: {
|
||||
current_page: meta.currentPage,
|
||||
from: meta.currentPage * meta.itemsPerPage - (meta.itemsPerPage - 1),
|
||||
to:
|
||||
meta.currentPage * meta.itemsPerPage > meta.totalItems
|
||||
? meta.totalItems
|
||||
: meta.currentPage * meta.itemsPerPage,
|
||||
last_page: meta.totalPages,
|
||||
per_page: meta.itemsPerPage,
|
||||
total: meta.totalItems,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public static processFilters<T>(
|
||||
queryFilters: any,
|
||||
filterableColumns: {
|
||||
[key in Column<T> | (string & {})]?:
|
||||
| (FilterOperator | FilterSuffix)[]
|
||||
| true;
|
||||
},
|
||||
): any {
|
||||
if (!queryFilters) return {};
|
||||
|
||||
const processedFilters = { ...queryFilters };
|
||||
|
||||
for (const key in queryFilters) {
|
||||
const value = queryFilters[key];
|
||||
|
||||
if (filterableColumns[key]) {
|
||||
const columnConfig = filterableColumns[key];
|
||||
|
||||
if (Array.isArray(columnConfig)) {
|
||||
for (const operator of columnConfig) {
|
||||
if (
|
||||
operator === FilterOperator.ILIKE &&
|
||||
!value.startsWith('$ilike')
|
||||
) {
|
||||
processedFilters[key] = `$ilike:%${value}%`; // Thêm ký tự đại diện %
|
||||
break;
|
||||
}
|
||||
if (operator === FilterOperator.LTE && !value.startsWith('$lte')) {
|
||||
processedFilters[key] = `$lte:${value}`;
|
||||
break;
|
||||
}
|
||||
if (operator === FilterOperator.GTE && !value.startsWith('$gte')) {
|
||||
processedFilters[key] = `$gte:${value}`;
|
||||
break;
|
||||
}
|
||||
if (operator === FilterOperator.EQ && !value.startsWith('$eq')) {
|
||||
processedFilters[key] = `$eq:${value}`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Nếu cột chỉ có giá trị `true` (mặc định EQ)
|
||||
else if (columnConfig === true && !value.startsWith('$eq')) {
|
||||
processedFilters[key] = `$eq:${value}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return processedFilters;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
export class SystemLang {
|
||||
private static texts = {
|
||||
messages: {
|
||||
vi: {
|
||||
error: 'Đã xảy ra lỗi!',
|
||||
not_found: 'Không tìm thấy dữ liệu!',
|
||||
file_not_found: 'Không tìm thấy tệp tin!',
|
||||
unauthorized: 'Bạn không có quyền truy cập!',
|
||||
forbidden: 'Truy cập bị từ chối!',
|
||||
success: 'Thành công!',
|
||||
server_error: 'Lỗi máy chủ, vui lòng thử lại sau!',
|
||||
connection_lost: 'Mất kết nối, kiểm tra lại mạng!',
|
||||
try_again: 'Vui lòng thử lại!',
|
||||
logout_success: 'Bạn đã đăng xuất thành công!',
|
||||
login_error_input: 'Tên đăng nhập hoặc mật khẩu không chính xác',
|
||||
login_error_valid: 'Input phải là username hoặc email',
|
||||
login_required: 'Vui lòng đăng nhập để tiếp tục!',
|
||||
login_success: 'Đăng nhập thành công!',
|
||||
save_success: 'Lưu thành công!',
|
||||
delete_success: 'Xóa thành công!',
|
||||
delete_failure: 'Xóa không thành công!',
|
||||
can_not_delete: 'Không thể xóa @key',
|
||||
no_data: 'Không có dữ liệu để hiển thị!',
|
||||
default_action: `Hành động này không thể thực hiện được!`,
|
||||
register_failure: 'Đăng ký tài khoản không thành công!',
|
||||
register_success: 'Đăng ký tài khoản thành công!',
|
||||
create_success: 'Đã tạo @key thành công!',
|
||||
create_failed: 'Không thể tạo @key!',
|
||||
update_success: 'Đã cập nhật @key thành công!',
|
||||
update_failed: 'Không thể cập nhật @key!',
|
||||
already_exists: '@key đã tồn tại!',
|
||||
required: '@key là bắt buộc!',
|
||||
invalid: '@key không hợp lệ!',
|
||||
no_permission: 'Bạn không có quyền thực hiện thao tác với @key!',
|
||||
password_invalid: 'Mật khẩu không hợp lệ !',
|
||||
change_pass_success:
|
||||
'Đổi mật khẩu thành công. Vui lòng đăng nhập lại !',
|
||||
too_many_request: 'Yêu cầu vượt quá mức quy định',
|
||||
feature_disabled: 'Tính năng này đang tạm ngưng',
|
||||
},
|
||||
en: {
|
||||
error: 'An error occurred!',
|
||||
not_found: 'Data not found!',
|
||||
file_not_found: 'File not found!',
|
||||
unauthorized: 'You are not authorized!',
|
||||
forbidden: 'Access denied!',
|
||||
success: 'Success!',
|
||||
server_error: 'Server error, please try again later!',
|
||||
connection_lost: 'Connection lost, check your network!',
|
||||
try_again: 'Please try again!',
|
||||
logout_success: 'You have successfully logged out!',
|
||||
login_error_input: 'Username or Password is cornet',
|
||||
login_error_valid: 'Input must be a valid username or email',
|
||||
login_required: 'Please log in to continue!',
|
||||
login_success: 'Login Success!',
|
||||
save_success: 'Saved successfully!',
|
||||
delete_success: 'Delete success!',
|
||||
delete_failure: 'Delete fail!',
|
||||
can_not_delete: "Can't delete @key",
|
||||
no_data: 'No data available!',
|
||||
default_action: `This action cannot be performed`,
|
||||
register_failure: 'Register account is fail!',
|
||||
register_success: 'Register account is success!',
|
||||
create_success: '@key created successfully!',
|
||||
create_failed: 'Failed to create @key!',
|
||||
update_success: '@key updated successfully!',
|
||||
update_failed: 'Failed to update @key!',
|
||||
already_exists: '@key already exists!',
|
||||
required: '@key is required!',
|
||||
invalid: '@key is invalid!',
|
||||
no_permission:
|
||||
'You do not have permission to perform this action on @key!',
|
||||
password_invalid: 'Password is invalid !',
|
||||
change_pass_success: 'Change password success. Please re-login !',
|
||||
too_many_request: 'To many request',
|
||||
feature_disabled: 'This feature is disabled',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// default lang is VIỆT NAM
|
||||
public static lang = process.env.PUBLIC_NEXT_LANG === 'en' ? 'en' : 'vi';
|
||||
|
||||
/** ✅ Lấy text từ messages hoặc labels */
|
||||
static getText<T extends keyof typeof SystemLang.texts>(
|
||||
type: T,
|
||||
key: keyof (typeof SystemLang.texts)[T]['vi'],
|
||||
after?: string,
|
||||
): string {
|
||||
const text: string = SystemLang.texts[type][SystemLang.lang][key];
|
||||
|
||||
return after
|
||||
? text.includes('@key')
|
||||
? text.replaceAll('@key', after)
|
||||
: `${text} ${after}`
|
||||
: (text ?? `Missing ${type}: ${String(key)}`);
|
||||
}
|
||||
|
||||
/** ✅ Trả về text từ custom object, fallback nếu không có */
|
||||
static getCustomText(
|
||||
texts: { vi?: string; en?: string },
|
||||
fallbackType: keyof typeof SystemLang.texts = 'messages',
|
||||
): string {
|
||||
return (
|
||||
texts[SystemLang.lang] ||
|
||||
Object.values(texts)[0] ||
|
||||
SystemLang.getText(fallbackType, 'error')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
import {
|
||||
ArgumentMetadata,
|
||||
BadRequestException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
ValidationPipe,
|
||||
ValidationPipeOptions,
|
||||
} from '@nestjs/common';
|
||||
import { ValidationError } from 'class-validator';
|
||||
import { SystemLang } from '../lang/system.lang';
|
||||
import AppResponse from '../filters/response/app-response';
|
||||
|
||||
@Injectable()
|
||||
export class AppValidationPipes extends ValidationPipe {
|
||||
private EXCLUDE = ['CreateKtqProductDto'];
|
||||
|
||||
public static errorsResponse(customErrors: any) {
|
||||
return AppResponse.toResponse(null, {
|
||||
message: 'Validation pipes failed',
|
||||
status_code: HttpStatus.BAD_REQUEST,
|
||||
bonus: { errors: customErrors },
|
||||
});
|
||||
}
|
||||
|
||||
public static internalServerResponse() {
|
||||
return AppResponse.toResponse(null, {
|
||||
message: SystemLang.getText('messages', 'server_error'),
|
||||
status_code: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
});
|
||||
}
|
||||
|
||||
public static exceptionFactory(errors: ValidationError[]) {
|
||||
const customErrors = errors.map((error) => ({
|
||||
field: error.property,
|
||||
errors: Object.values(error.constraints || {}),
|
||||
}));
|
||||
|
||||
return new BadRequestException(
|
||||
AppValidationPipes.errorsResponse(customErrors),
|
||||
);
|
||||
}
|
||||
|
||||
constructor(options?: ValidationPipeOptions) {
|
||||
super({ ...options });
|
||||
}
|
||||
|
||||
async transform(value: any, metadata: ArgumentMetadata) {
|
||||
if (this.EXCLUDE.includes(metadata.metatype?.name)) {
|
||||
return value;
|
||||
}
|
||||
return super.transform(value, metadata);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
-----BEGIN CERTIFICATE-----
|
||||
MIIDvTCCAqWgAwIBAgIUV9payTNbqF6ZM2mCjfPLqSIicKwwDQYJKoZIhvcNAQEL
|
||||
BQAwbjELMAkGA1UEBhMCVk4xCzAJBgNVBAgMAlZOMQswCQYDVQQHDAJWTjELMAkG
|
||||
A1UECgwCVk4xCzAJBgNVBAsMAlZOMQswCQYDVQQDDAJWTjEeMBwGCSqGSIb3DQEJ
|
||||
ARYPYWRtaW5AZ21haWwuY29tMB4XDTI1MDgwNjA5MDQyMVoXDTI2MDgwNjA5MDQy
|
||||
MVowbjELMAkGA1UEBhMCVk4xCzAJBgNVBAgMAlZOMQswCQYDVQQHDAJWTjELMAkG
|
||||
A1UECgwCVk4xCzAJBgNVBAsMAlZOMQswCQYDVQQDDAJWTjEeMBwGCSqGSIb3DQEJ
|
||||
ARYPYWRtaW5AZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
|
||||
AQEAwb6Ze/+uLOC2vHZZwH0BeTLCPesBf8vgHkvU6wmkPgDl9ulY5XWJxVhiBya3
|
||||
tkIZFLUleejaz+9ckhK6USZQX3iTlkZ57YW1w2VhCCH0/XCGwEteRX1JaREzJDUm
|
||||
u5z+5vekcDSvMTmFgu4Qc23Z2PSW2oN42dae3iYpm/StMT78GpGc4bayZ7KX7FaY
|
||||
rmB7bEF2/rGJRpVWBITi8zxT5ZOcERbk0KSjbzcdwoa98C5OVF8U6aHvkjfKm6qE
|
||||
LjJz8JgV/QcLahM7gK+5b1rGYWT5EYslm2+Wik2CjDzOVDq0TpqZNLynA+HCszSp
|
||||
9RVTfLciIRsk7ppA76SHI4nkQwIDAQABo1MwUTAdBgNVHQ4EFgQUNQ84Z6IsYPMv
|
||||
AJfGXKekSp/lFiwwHwYDVR0jBBgwFoAUNQ84Z6IsYPMvAJfGXKekSp/lFiwwDwYD
|
||||
VR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAfkTLU1+B/VfNTYbzgSJF
|
||||
8pABU+PfaXjFqL1Wrwg4v6q4qttaTVnUuwNDwmBTy36uMMrQ5BEGVlHON6vw188N
|
||||
y1LMOGcFXnmHd0cmczi7H0OXLYzfGu7a756TePPp45Hl/PWLx8SFvd09rlGp34NK
|
||||
E1H/2C8sbbJEqa9EcRKx3q1DMF+NWB436patnxdQOlI2cpIcEz4InbpoMTBoTPje
|
||||
MmPsDIK81beLzVZ/JSRvShfncSdwGGxWWRZnUbKWbJXU4cKU3qCscKBTyB8Kmok0
|
||||
S6XumKi3HNSzAwFvrbzxaUilrTkOWO2QNp8nlkH8ZDfGE0ieCDvw+S1b0d4h7VKU
|
||||
Jg==
|
||||
-----END CERTIFICATE-----
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDBvpl7/64s4La8
|
||||
dlnAfQF5MsI96wF/y+AeS9TrCaQ+AOX26VjldYnFWGIHJre2QhkUtSV56NrP71yS
|
||||
ErpRJlBfeJOWRnnthbXDZWEIIfT9cIbAS15FfUlpETMkNSa7nP7m96RwNK8xOYWC
|
||||
7hBzbdnY9Jbag3jZ1p7eJimb9K0xPvwakZzhtrJnspfsVpiuYHtsQXb+sYlGlVYE
|
||||
hOLzPFPlk5wRFuTQpKNvNx3Chr3wLk5UXxTpoe+SN8qbqoQuMnPwmBX9BwtqEzuA
|
||||
r7lvWsZhZPkRiyWbb5aKTYKMPM5UOrROmpk0vKcD4cKzNKn1FVN8tyIhGyTumkDv
|
||||
pIcjieRDAgMBAAECggEAHKFCRBEd13LjfgkNLUUrtRG7o3O5Vn21ojR5g7v6gdEX
|
||||
KnwED3BlifyMC9t8VVoCI826+n9e6lBIQSu0Ta6YPOtv/8ptVRynpfaytoVyEwuQ
|
||||
VhUtGp6vfO+2O3kBPsMt5cqdiZk3dFI4OQdd9fi7MvS94A+CicpN0q0YA/xNpZOT
|
||||
XaTXV+opBit+evy356R+pzOuBkjHPLDt3zkU0HmREiSi3fzd7bAk/H03LAVtV8NH
|
||||
cAqF3jDDuC+uL7v5Mltkhi/FmF58px/qs94HcsS6P2GKv0fPybsy+q3ma4HcLA1O
|
||||
Em6CTOhrzoeRphfjHavEjpdlgWr1bfdGX+VS76UICQKBgQD6hQ8lZRd8d+cVe37R
|
||||
IvIMfYV+Mu0NhvdaiXAEnnGxxPdql/npF03kjmhyZ+NpXtkRw3Padel/L/D2yk6U
|
||||
Meosivl379GLNxIFTpZCTJC4LyuatVlTFrGPphD/LBnuLDwcFVEYtT92MCp4QW+S
|
||||
Rbffkl7GifV4kaoyf+Kh34JaKQKBgQDF+5edQRRJ2JJ8yM9ZkdgikqEip7d9ksEV
|
||||
w+9RaP2BGxR3t9kdwZxa3JKRQegJL6f4PS1Q0qDSlmTYuTvf9S61B6OQ+exYGI5B
|
||||
PNNXQwi64vejF9x3FQu5XSYODPsPr9bjMpIcKCHNgKnlsz71/kzOe2PC8GOm3eP6
|
||||
8z+ASelwiwKBgQDlTfOuI9kaidmPtUk//n+VZTNSbyTCE/7G9TP+VlT1Bbf97nvG
|
||||
mhknEh6SUXs7kKCZ/NBHb1Q5odUq38SLKyEQgmiUGoQvrEmnZ+Zraw+wNyTvZ/0J
|
||||
66S9OqEmH+TgN8cRYYWoWwZqlO3awvJv7ba/QofTrKVuJc6miJ4V0rLK+QKBgGM6
|
||||
gTfo2VFVwb3XK82Zwnk5gpeK9fVzK2FMTdNAyuX9e5mxRJmcY1BLAw7YuIJ6JzbM
|
||||
+rxqhP5nMG5LEM5j5aAIDxvnl2RkElByOv6ec26vuSw+Flp86t5h6GPcb6ziFdLT
|
||||
ktWX67FDDmQ5HZJPfZFz2IFo2JlW1x/88NPMt7qXAoGAWTi9QIKR0XKzljEvdwJQ
|
||||
B2j0/u3cDXlLwVhKAzbDrRFoKR7Yna/1Sfrg649CiNCFQ5bGx6tjMBEJpXpsMjcE
|
||||
NmcRw4ExAMBAS6WtTezNtx2dN2StCKLMfQsfoMQ2J014fnqw0pgJswxyWMbR1LIS
|
||||
vvSukbujOOAEIllSpEIsaVM=
|
||||
-----END PRIVATE KEY-----
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import * as request from 'supertest';
|
||||
import { App } from 'supertest/types';
|
||||
import { AppModule } from './../src/app.module';
|
||||
|
||||
describe('AppController (e2e)', () => {
|
||||
let app: INestApplication<App>;
|
||||
|
||||
beforeEach(async () => {
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
|
||||
app = moduleFixture.createNestApplication();
|
||||
await app.init();
|
||||
});
|
||||
|
||||
it('/ (GET)', () => {
|
||||
return request(app.getHttpServer())
|
||||
.get('/')
|
||||
.expect(200)
|
||||
.expect('Hello World!');
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2021",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": false,
|
||||
"noImplicitAny": false,
|
||||
"strictBindCallApply": false,
|
||||
"forceConsistentCasingInFileNames": false,
|
||||
"noFallthroughCasesInSwitch": false,
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue