Commit a54baa38 by 李敏

Merge branch 'dev' into 'master'

Dev

See merge request !1
2 parents 48d214db f470f75d
Showing 125 changed files with 2858 additions and 0 deletions
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
DATABASE_URL="mysql://limin:limin1018@192.168.1.129:3306/app_admin?schema=public"
QIWEI_WEBHOOK='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=8541005c-5f60-416b-821e-64b4d872cd77'
SOCKET_PORT= 8080
APP_PORT= 3000
STATIC_PATH= "public"
\ No newline at end of file \ No newline at end of file
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
],
root: true,
env: {
node: true,
jest: true,
},
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/camelcase': 'off',
// "quote-props": ["error", "always"],
// "quotes": ["error", "single"]
},
};
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-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
\ No newline at end of file \ No newline at end of file
{
"printWidth": 800,
"tabWidth": 2,
"singleQuote": true,
"trailingComma": "none",
"semi": false,
"wrap_line_length": 820,
"wrap_attributes": "auto",
"proseWrap": "always",
"arrowParens": "avoid",
"bracketSpacing": true,
"htmlWhitespaceSensitivity": "ignore",
"javascript.format.insertSpaceBeforeFunctionParenthesis": true,
"jsxBracketSameLine": true,
"files.insertFinalNewline": true,
"prettier.ignorePath": ".prettierignore",
"useTabs": false,
"eslintIntegration": false,
"overrides": [
{
"files": ".prettierrc",
"options": {
"parser": "json"
}
}
],
"endOfLine": "auto"
}
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": ["templates/**/*"]
}
}
{
"name": "app-admin",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"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",
"prisma:pull": "npx prisma db pull",
"prisma:studio": "npx prisma studio",
"prisma:generate": "npx prisma generate",
"prisma:generate:watch": "npx prisma generate --watch",
"migrate:dev": "prisma migrate dev --preview-feature",
"migrate:dev:create": "prisma migrate dev --create-only --preview-feature",
"migrate:reset": "prisma migrate reset --preview-feature",
"migrate:deploy": "npx prisma migrate deploy --preview-feature",
"migrate:status": "npx prisma migrate status --preview-feature",
"migrate:resolve": "npx prisma migrate resolve --preview-feature",
"db": "rimraf ./src/modules/entities & typeorm-model-generator -h 192.168.3.113 -d app_admin -p 3306 -u user_limin -x LmotGSOY -e mysql -o ./src/modules/entities --noConfig true --ce pascal --cp camel"
},
"dependencies": {
"@nest-modules/mailer": "^1.3.22",
"@nestjs-modules/mailer": "^1.6.0",
"@nestjs/axios": "^3.0.3",
"@nestjs/bull": "^0.1.1",
"@nestjs/common": "^10.4.1",
"@nestjs/core": "^10.4.1",
"@nestjs/event-emitter": "^2.0.4",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^7.0.0",
"@nestjs/platform-express": "^10.4.1",
"@nestjs/platform-socket.io": "^10.4.1",
"@nestjs/platform-ws": "^10.4.1",
"@nestjs/schedule": "^0.3.1",
"@nestjs/swagger": "^7.4.2",
"@nestjs/typeorm": "^7.0.0",
"@nestjs/websockets": "^10.4.1",
"@prisma/client": "^5.19.1",
"@socket.io/redis-adapter": "^8.3.0",
"axios": "^1.7.7",
"bull": "^3.14.0",
"class-transformer": "^0.3.1",
"class-validator": "^0.12.2",
"compressing": "^1.5.1",
"global": "^4.4.0",
"mysql": "^2.18.1",
"nest-status-monitor": "^0.1.3",
"nestjs-config": "^1.4.6",
"nestjs-prisma": "^0.23.0",
"nodemailer": "^6.4.16",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"redis": "^4.7.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.8.1",
"socket.io": "4.7.4",
"swagger-ui-express": "^5.0.1",
"typeorm": "0.2.25"
},
"devDependencies": {
"@nestjs/cli": "^10.4.5",
"@nestjs/schematics": "^10.1.4",
"@nestjs/testing": "^7.0.0",
"@types/bull": "^3.13.0",
"@types/express": "^4.17.6",
"@types/ioredis": "^5.0.0",
"@types/jest": "25.1.4",
"@types/multer": "^1.4.12",
"@types/node": "^22.5.5",
"@types/socket.io": "^3.0.2",
"@types/supertest": "^2.0.8",
"@typescript-eslint/eslint-plugin": "5.62.0",
"@typescript-eslint/parser": "5.62.0",
"eslint": "8.42.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.30.0",
"jest": "^25.1.0",
"prettier": "^3.3.3",
"prisma": "^5.19.1",
"prisma-dbml-generator": "^0.12.0",
"supertest": "^4.0.2",
"ts-jest": "25.2.1",
"ts-loader": "^6.2.1",
"ts-node": "^8.6.2",
"tsconfig-paths": "^3.9.0",
"typescript": "^5.6.2"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
-- CreateTable
CREATE TABLE `device` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`sn` VARCHAR(20) NOT NULL,
`create_time` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `device_info` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`device_id` INTEGER NOT NULL DEFAULT 0,
`user` VARCHAR(20) NULL,
`last_log_upload_time` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`last_log_remove_time` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`mobile` VARCHAR(20) NULL,
`merchant_name` VARCHAR(50) NULL,
UNIQUE INDEX `device_info_device_id_key`(`device_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `device_status` (
`device_id` INTEGER NOT NULL,
`status` TINYINT NOT NULL DEFAULT 0,
PRIMARY KEY (`device_id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `log` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`device_id` INTEGER NOT NULL DEFAULT 0,
`path` VARCHAR(255) NOT NULL,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
UNIQUE INDEX `log_device_id_key`(`device_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `log_config` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`device_id` INTEGER NOT NULL DEFAULT 0,
`log_saved_days` TINYINT NULL DEFAULT 7,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
UNIQUE INDEX `log_config_device_id_key`(`device_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `log_config_userfield_relation` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`config_id` INTEGER NOT NULL DEFAULT 0,
`user_field_id` INTEGER NOT NULL DEFAULT 0,
INDEX `FK_log_config_userfield_relation_log_config`(`config_id`),
INDEX `FK_log_config_userfield_relation_log_user_field`(`user_field_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `log_user_field` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(20) NOT NULL,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- AddForeignKey
ALTER TABLE `device_info` ADD CONSTRAINT `FK_device_info_device` FOREIGN KEY (`device_id`) REFERENCES `device`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `device_status` ADD CONSTRAINT `FK__device` FOREIGN KEY (`device_id`) REFERENCES `device`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `device_status` ADD CONSTRAINT `FK__device_info` FOREIGN KEY (`device_id`) REFERENCES `device_info`(`device_id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log` ADD CONSTRAINT `FK_log_device` FOREIGN KEY (`device_id`) REFERENCES `device`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log` ADD CONSTRAINT `FK_log_device_info` FOREIGN KEY (`device_id`) REFERENCES `device_info`(`device_id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log_config` ADD CONSTRAINT `FK_log_config_device` FOREIGN KEY (`device_id`) REFERENCES `device`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log_config` ADD CONSTRAINT `FK_log_config_device_info` FOREIGN KEY (`device_id`) REFERENCES `device_info`(`device_id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log_config_userfield_relation` ADD CONSTRAINT `FK_log_config_userfield_relation_log_config` FOREIGN KEY (`config_id`) REFERENCES `log_config`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log_config_userfield_relation` ADD CONSTRAINT `FK_log_config_userfield_relation_log_user_field` FOREIGN KEY (`user_field_id`) REFERENCES `log_user_field`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
/*
Warnings:
- A unique constraint covering the columns `[sn]` on the table `device` will be added. If there are existing duplicate values, this will fail.
*/
-- AlterTable
ALTER TABLE `device_info` MODIFY `last_log_upload_time` TIMESTAMP(0) NULL,
MODIFY `last_log_remove_time` TIMESTAMP(0) NULL;
-- CreateIndex
CREATE UNIQUE INDEX `device_sn_key` ON `device`(`sn`);
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "mysql"
\ No newline at end of file \ No newline at end of file
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model device {
id Int @id @default(autoincrement())
sn String @unique @db.VarChar(20)
create_time DateTime @default(now()) @db.Timestamp(0)
device_info device_info?
device_status device_status?
logs file[]
log_config log_config?
}
model device_info {
id Int @id @default(autoincrement())
device_id Int @unique @default(0)
user String? @db.VarChar(20)
last_log_upload_time DateTime? @db.Timestamp(0)
last_log_remove_time DateTime? @db.Timestamp(0)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
mobile String? @db.VarChar(20)
merchant_name String? @db.VarChar(50)
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_device_info_device")
device_status device_status?
logs file[]
log_config log_config?
}
model device_status {
device_id Int @id
status Int @default(0) @db.TinyInt
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK__device")
device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK__device_info")
}
model file {
id Int @id @default(autoincrement())
device_id Int @default(0)
path String @db.VarChar(255)
mimetype String? @db.VarChar(100)
filename String? @db.VarChar(100)
originalname String? @db.VarChar(255)
size Int? @default(0)
created_at DateTime @default(now()) @db.Timestamp(0)
type String @default("other") @db.VarChar(10)
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_device")
device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_device_info")
}
model log_config {
id Int @id @default(autoincrement())
device_id Int @unique @default(0)
log_saved_days Int? @default(7) @db.TinyInt
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device")
device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device_info")
user_fields log_config_userfield_relation[]
}
model log_config_userfield_relation {
id Int @id @default(autoincrement())
config_id Int @default(0)
user_field_id Int @default(0)
log_config log_config @relation(fields: [config_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_userfield_relation_log_config")
log_user_field log_user_field @relation(fields: [user_field_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_userfield_relation_log_user_field")
@@index([config_id], map: "FK_log_config_userfield_relation_log_config")
@@index([user_field_id], map: "FK_log_config_userfield_relation_log_user_field")
}
model log_user_field {
id Int @id @default(autoincrement())
name String @db.VarChar(20)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
log_config_userfield_relation log_config_userfield_relation[]
}
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
import { resolve } from 'path'
import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common'
import { ScheduleModule } from '@nestjs/schedule'
import { ConfigModule, ConfigService } from 'nestjs-config'
// import { MailerModule } from '@nest-modules/mailer'
import { StatusMonitorModule } from 'nest-status-monitor'
import statusMonitorConfig from './config/statusMonitor'
import { LoggerMiddleware } from './common/middleware/logger.middleware'
import { TasksModule } from './tasks/tasks.module'
// import { AudioModule } from './jobs/audio/audio.module'
// import { AuthModule } from './modules/auth/auth.module'
// import { HelloModule } from './modules/hello/hello.module'
import { DeviceModule } from './modules/device/device.module'
// import { ExceptionModule } from './modules/exception/exception.module'
// import { RoleGuardModule } from './modules/role-guard/role-guard.module'
// import { EmailModule } from './modules/email/email.module'
// import { UsersModule } from './modules/users/users.module'
import { FileModule } from './modules/file/file.module'
import { WsModule } from './modules/ws/ws.module'
// import { WsGateway } from './modules/ws/ws.gateway';
// import { SseModule } from './modules/sse/sse.module'
import { LogConfigModule } from './modules/config/config.module'
import { BroadcastModule } from './modules/broadcast/broadcast.module'
import { EventEmitterModule } from '@nestjs/event-emitter'
import { HttpModule } from '@nestjs/axios'
@Module({
imports: [
ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')),
// TypeOrmModule.forRootAsync({
// useFactory: (config: ConfigService) => config.get('database'),
// inject: [ConfigService]
// }),
HttpModule.registerAsync({
useFactory: async (config: ConfigService) => config.get('http'),
inject: [ConfigService]
}),
// TODO @nestjs/terminus almost the same
StatusMonitorModule.setUp(statusMonitorConfig),
// MailerModule.forRootAsync({
// useFactory: (config: ConfigService) => config.get('email'),
// inject: [ConfigService]
// }),
ScheduleModule.forRoot(),
EventEmitterModule.forRoot(),
TasksModule,
// AudioModule,
// AuthModule,
// HelloModule,
// ExceptionModule,
// RoleGuardModule,
// EmailModule,
// UsersModule,
FileModule,
// SseModule,
WsModule,
DeviceModule,
BroadcastModule,
LogConfigModule
]
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
// 为 hello 路由添加中间件
// consumer.apply(LoggerMiddleware).exclude({ path: 'hello', method: RequestMethod.POST }).forRoutes('hello')
consumer.apply(LoggerMiddleware).forRoutes('*')
}
}
export * from './redis-io.adapter';
\ No newline at end of file \ No newline at end of file
import { IoAdapter } from '@nestjs/platform-socket.io';
import { ConfigService } from 'nestjs-config';
import { ServerOptions } from 'socket.io';
import { createAdapter } from '@socket.io/redis-adapter';
import { createClient } from 'redis';
export class RedisIoAdapter extends IoAdapter {
private adapterConstructor: ReturnType<typeof createAdapter>;
async connectToRedis(): Promise<void> {
const pubClient = createClient({ url: `redis://localhost:6379` });
const subClient = pubClient.duplicate();
await Promise.all([pubClient.connect(), subClient.connect()]);
this.adapterConstructor = createAdapter(pubClient, subClient);
}
createIOServer(port: number, options?: ServerOptions): any {
const server = super.createIOServer(port, options);
server.adapter(this.adapterConstructor);
return server;
}
}
import { applyDecorators, UseInterceptors } from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface'
export function UploadFile(fieldName = 'file', options: MulterOptions = {}) {
return applyDecorators(UseInterceptors(FileInterceptor(fieldName, options)))
}
export * from './file.decorator'
import { SetMetadata } from '@nestjs/common';
export const Roles = (...roles: string[]) => SetMetadata('roles', roles);
/**
* @description: 响应码
*/
export enum RESPONSE_CODE {
NOSUCCESS = -1, // 表示请求成功,但操作未成功
SUCCESS = 200, // 请求成功
BAD_REQUEST = 400, // 请求错误
UNAUTHORIZED = 401, // 未授权
FORBIDDEN = 403, // 禁止访问
NOT_FOUND = 404, // 资源未找到
INTERNAL_SERVER_ERROR = 500 // 服务器错误
}
/**
* @description: 请求提示语
*/
export enum RESPONSE_MSG {
SUCCESS = '请求成功',
FAILURE = '请求失败'
}
export enum WsMessageType {
/**
* 私有订阅
*/
Private = 'private',
/**
* 系统订阅
*/
System = 'system'
}
export enum WsStatus {
Disuse = 0,
Online = 1,
Offline = 2
}
export enum WsAccess {
NotAllowed = '无访问权限',
InValidToken = '无效token',
InvalidDeviceId = '无效设备id',
IsOnline = '通过验证,设备上线',
IsOffline = '设备下线',
ConnFailure = '设备连接失败,请检查设备号是否正确'
}
export enum Events {
OnConnected = 'device.connected',
OnConnectError = 'device.connect.error',
OnOfflineAll='device.offline.all',
OnMessage='client.mesage.received',
OnLogFileUploaded = 'log.file.uploaded',
OnLogFileRemoved='log.file.removed',
OnTaskStart='task.start'
}
export enum DocTypes {
Log = 'log',
Image = 'image',
Video = 'video',
Other = 'other'
}
export enum Command{
GetLog='getLog',
GetStorage='getStorage',
Message='message',
File='file'
}
export enum FileCommand{
GetList='getList',
Remove='remove'
}
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common'
import { Response, Request } from 'express'
import { BodyResponse } from '../utils'
// @Catch() 装饰器绑定所需的元数据到异常过滤器上。它告诉 Nest这个特定的过滤器正在寻找
@Catch()
export class ExceptionsFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
// 获取上下文
const ctx = host.switchToHttp()
// 获取响应体
const response = ctx.getResponse<Response>()
const request = ctx.getRequest<Request>()
Logger.error(exception)
// console.log(exception)
// 获取状态码,判断是HTTP异常还是服务器异常
const code = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR
const message = exception.meta?.cause || exception.message || '服务器异常'
// 自定义异常返回体
response.status(code).json(BodyResponse({ message, code, error: exception, url: request.url }))
}
}
import { UnsupportedMediaTypeException } from '@nestjs/common'
export function FileMimeTypeFilter(...mimes: string[]) {
return (req: any, file: Express.Multer.File, callback: (error: Error | null, acceptFile: boolean) => void) => {
if (mimes.some(mime => file.mimetype.includes(mime))) {
callback(null, true)
} else {
callback(new UnsupportedMediaTypeException('文件类型错误'), false)
}
}
}
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, Logger } from '@nestjs/common'
import { Request, Response } from 'express'
import { BodyResponse } from '../utils'
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp()
const response = ctx.getResponse<Response>()
const request = ctx.getRequest<Request>()
const status = exception.getStatus()
Logger.error(exception)
// console.log(exception)
const exceptionRes: any = exception.getResponse()
const { message } = exceptionRes
// response.status(status).json({
// status,
// timestamp: new Date().toISOString(),
// path: request.url,
// error,
// message,
// });
// 自定义异常返回体
response.status(status).json(BodyResponse({message, code:status,error:exception, url:request.url}))
}
}
export * from './http-exception.filter'
export * from './exception.filter'
export * from './validate-exception.filter'
export * from './file-mime.filter'
import { ArgumentsHost, Catch, ExceptionFilter,HttpStatus, Logger } from '@nestjs/common'
import { ValidationError } from 'class-validator';
import { Request, Response } from 'express'
import { BodyResponse } from '../utils'
@Catch(ValidationError)
export class ValidateExceptionFilter implements ExceptionFilter<ValidationError> {
catch(exception: ValidationError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const status = HttpStatus.BAD_REQUEST;
Logger.error(exception)
// response
// .status(status)
// .json({
// statusCode: status,
// // message: exception.message,
// });
// // 自定义异常返回体
// response.status(status).json(BodyResponse(null, message, status, request.url))
}
}
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
return true;
}
const request = context.switchToHttp().getRequest();
const { user } = request.query;
// const hasRole = () =>
// user.roles.some(role => !!roles.find(item => item === role));
// return user && user.roles && hasRole();
return !!roles.find(role => role === user);
}
}
export * as enums from './enums'
export * as utils from './utils'
import { CallHandler, ExecutionContext, HttpException, HttpStatus, Injectable, NestInterceptor } from '@nestjs/common'
import { Observable, throwError } from 'rxjs'
import { catchError } from 'rxjs/operators'
@Injectable()
export class ErrorsInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<CommonTypes.IResData> {
return next.handle().pipe(catchError(err => throwError(new HttpException('New message', HttpStatus.BAD_GATEWAY))))
}
}
export * from './transform.interceptor'
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
import { Observable } from 'rxjs'
import { tap } from 'rxjs/operators'
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
console.log('Before...')
const now = Date.now()
return next.handle().pipe(tap(() => console.log(`After... ${Date.now() - now}ms`)))
}
}
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
import { Observable } from 'rxjs'
import { timeout } from 'rxjs/operators'
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(timeout(5000))
}
}
import { map } from 'rxjs/operators'
import { Observable } from 'rxjs'
import { BodyResponse } from '../../common/utils'
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, CommonTypes.IResData> {
intercept(context: ExecutionContext, next: CallHandler<T>): Observable<CommonTypes.IResData> {
return next.handle().pipe(map((data:CommonTypes.IResData) => BodyResponse(data)))
}
}
import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: () => void) {
const { method, path , url,params,query } = req;
Logger.debug(`method -> ${method} url -> ${url} params -> ${JSON.stringify(params)} query -> ${JSON.stringify(query)}`);
next();
}
}
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'
@Injectable()
export class PagesPipe implements PipeTransform<CommonTypes.IPageIn> {
async transform(value: CommonTypes.IPageIn) {
const { pageIndex = 1, pageSize = 10 } = value
const skip = (pageIndex - 1) * pageSize
value.skip = +skip < 0 ? 0 : skip
value.take = +pageSize
return value
}
}
@Injectable()
export class FilePathPipe implements PipeTransform<Express.Multer.File> {
async transform(file: Express.Multer.File) {
file.path = file.path.split(process.env.STATIC_PATH).pop().replace(/\\/g, '/')
return file
}
}
@Injectable()
export class ParseDeviceIdPipe implements PipeTransform<any, any> {
transform(value: any, metadata: ArgumentMetadata): any {
// 创建一个新对象,以避免直接修改原始值
const transformedValue = { ...value }
// 检查 device_id 是否存在并且是字符串类型
if (typeof transformedValue.device_id === 'string') {
const deviceId = parseInt(transformedValue.device_id, 10)
// 检查转换后的值是否是有效的数字
if (isNaN(deviceId)) {
throw new BadRequestException('device_id must be a valid number')
}
// 更新 device_id 字段为数字类型
transformedValue.device_id = deviceId
}
// 返回转换后的值,其中 device_id 是数字类型,其他字段保持不变
return transformedValue
}
}
@Injectable()
export class ParseIdPipe implements PipeTransform<any, any> {
transform(value: any, metadata: ArgumentMetadata): any {
// 创建一个新对象,以避免直接修改原始值
const transformedValue = { ...value }
// 检查 id 是否存在并且是字符串类型
if (typeof transformedValue.id === 'string') {
const id = parseInt(transformedValue.id, 10)
// 检查转换后的值是否是有效的数字
if (isNaN(id)) {
throw new BadRequestException('id must be a valid number')
}
// 更新 id 字段为数字类型
transformedValue.id = id
}
// 返回转换后的值,其中 id 是数字类型,其他字段保持不变
return transformedValue
}
}
export * from './arguments.pipe'
export * from "./parse-int.pipe";
export * from "./validation.pipe";
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
@Injectable()
export class ParseIntPipe implements PipeTransform<string> {
async transform(value: string, metadata: ArgumentMetadata) {
const val = parseInt(value, 10);
if (isNaN(val)) {
throw new BadRequestException('Validation failed');
}
return val;
}
}
import { ArgumentMetadata,BadRequestException, HttpException, HttpStatus, Injectable, Logger, PipeTransform, Type } from '@nestjs/common'
import { plainToClass } from 'class-transformer'
import { validate } from 'class-validator'
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, metadata: ArgumentMetadata) {
const { metatype } = metadata
if (!metatype || !this.toValidate(metatype)) {
return value
}
const object = plainToClass(metatype, value)
let errors = await validate(object)
if (errors.length > 0) {
if(!errors[0].constraints && errors[0].children?.length){
errors = errors[0].children
}
const msg = Object.values(errors[0]?.constraints)[0]; // 只需要取第一个错误信息并返回即可
Logger.error(`Validation failed: ${msg}`);
throw new BadRequestException(`参数验证失败: ${msg}`);
// const errObj = {}
// errors.forEach(err => {
// const { property, constraints } = err
// errObj[property] = Object.values(constraints)
// })
// throw new HttpException({ message: errObj||'Request params validation failed', error: errObj }, HttpStatus.BAD_REQUEST)
}
return value
}
private toValidate(metatype: Type<any>): boolean {
const types = [String, Boolean, Number, Array, Object]
return !types.find(type => metatype === type)
}
}
import { types } from 'util'
import { RESPONSE_CODE, RESPONSE_MSG } from '../enums'
import { Logger } from '@nestjs/common'
export const getCurrentTimestamp = (): number => {
return Date.parse(new Date().toString()) / 1000
}
/**
* @description: 统一返回体
*/
export const BodyResponse: CommonTypes.TBodyResponse = ({ message = RESPONSE_MSG.SUCCESS, code = RESPONSE_CODE.SUCCESS, error, url, total, data }) => {
if (message instanceof Array) {
message = message.join(';')
}
const result = { url, data, total, error, message, code, timestamp: getCurrentTimestamp() }
Logger.debug('返回结果:', result)
return result
}
import { join } from 'path';
export default {
type: 'mysql',
host: '192.168.3.113',
// socketPath: '/tmp/mysql.sock',
port: 3306,
username: 'user_limin',
password: 'LmotGSOY',
database: 'app_admin',
// entities: [join(__dirname, '../', '**/**.entity{.ts,.js}')],
entities: [join(__dirname, '../', 'modules/entities/**{.ts,.js}')],
synchronize: true,
};
import { join } from 'path';
import { PugAdapter } from '@nestjs-modules/mailer/dist/adapters/pug.adapter';
export default {
transport: 'smtps://1255968521@qq.com:tsjjzmqcmhmoheje@smtp.qq.com',
defaults: {
from: '"nest-modules" <modules@nestjs.com>',
},
template: {
dir: join(__dirname, '../templates/email/'),
adapter: new PugAdapter(),
options: {
strict: true,
},
},
};
export default {
AppWebhook: process.env.QIWEI_WEBHOOK
}
import { join,extname } from 'path';
import { diskStorage } from 'multer';
export default {
root: join(__dirname,'..','..',process.env.STATIC_PATH),
storage: diskStorage({
destination: join(__dirname,'..','..', `${process.env.STATIC_PATH}/${new Date().toLocaleDateString()}`),
filename: (req, file, cb) => {
const deviceId = req.body.deviceId;
// const name=file.originalname.split('.');
// const filename = `${name[0]}-${new Date().getTime()}.${name.pop()}`//${file.mimetype.split('/')[1]}`;
const path = `${file.originalname.split('.').shift()}@${deviceId}@${Date.now()}-${Math.round(Math.random() * 1e10)}${extname(file.originalname)}`
return cb(null, path);
},
}),
};
export default {
timeout: 5000,
maxRedirects: 5
}
export default {
host: 'localhost',
port: 6379,
}
\ No newline at end of file \ No newline at end of file
export default {
pageTitle: 'Nest.js Monitoring Page',
port: 3000,
path: '/status',
ignoreStartsWith: '/healt/alive',
spans: [
{
interval: 1, // Every second
retention: 60, // Keep 60 datapoints in memory
},
{
interval: 5, // Every 5 seconds
retention: 60,
},
{
interval: 15, // Every 15 seconds
retention: 60,
},
],
chartVisibility: {
cpu: true,
mem: true,
load: true,
responseTime: true,
rps: true,
statusCodes: true,
},
healthChecks: [],
};
import { ApiProperty } from '@nestjs/swagger'
import { Transform } from 'class-transformer'
import { IsOptional, isString, Matches, registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'
// 自定义验证装饰器
export function IsNumberOrNumberString(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
name: 'isNumberOrNumberString',
target: object.constructor,
propertyName: propertyName,
constraints: [],
options: validationOptions,
validator: {
validate(value: any, args: ValidationArguments) {
// 如果值为空(null, undefined, ''),则验证通过
if (value === null || value === undefined || value === '') {
return true
}
// 尝试将值转换为数字,如果转换成功或原本就是数字,则验证通过
// 注意:这里使用了 Number.isNaN 来检查转换结果是否为 NaN,从而排除非数字字符串
return !Number.isNaN(Number(value))
},
defaultMessage(args: ValidationArguments): string {
// 这里可以返回自定义的错误消息
return `${args.property} must be a number or a numeric string`
}
}
})
}
}
export class BaseDto {
@ApiProperty({
type: Number,
description: '设备ID',
required: false,
default: 0
})
@IsOptional()
@IsNumberOrNumberString()
device_id?: number
@ApiProperty({
type: Number,
description: '每页显示的条数',
required: false,
default: 10
})
@IsOptional()
@IsNumberOrNumberString()
pageSize?: number
@ApiProperty({
type: Number,
description: '当前页码',
required: false,
default: 1
})
@IsOptional()
@IsNumberOrNumberString()
pageIndex?: number
}
import { ApiProperty } from '@nestjs/swagger'
import { Command, WsMessageType } from '../common/enums'
import { IsDefined, IsEnum, IsNotEmpty, IsNumber, IsString, ValidateIf, ValidateNested } from 'class-validator'
import { Type } from 'class-transformer'
class DataDto {
@ApiProperty({
type: String,
description: '指令类型'
})
@IsEnum(Command, { message: '指令类型错误' })
@IsString({ message: '指令为必填参数' })
@IsNotEmpty({ message: '指令不能为空' })
readonly command: Command
@ApiProperty({
description: '下发的参数'
})
readonly payload: unknown
}
export class BroadcastDto {
@ApiProperty({
type: String,
description: '事件类型: private-私有消息,system-系统消息',
})
@IsEnum(WsMessageType, { message: '事件类型错误' })
@IsNotEmpty({ message: '事件类型不能为空' })
readonly event: WsMessageType
@ValidateIf(o => o.event === WsMessageType.Private)
@IsDefined({ message: '发送私有消息时,device_id是必填的' })
@ApiProperty({
type: Number,
description: '设备号,私发信息必填',
})
readonly device_id: number
@IsNotEmpty({ message: '消息不能为空' })
@ApiProperty({ description: '要发送的数据' })
@ValidateNested()
@Type(() => DataDto)
readonly data: any
}
import { ApiProperty } from "@nestjs/swagger"
import { Transform } from "class-transformer"
import { IsNotEmpty, IsNumber, isString, Matches } from "class-validator"
/*
model log_config {
id Int @id @default(autoincrement())
device_id Int @unique(map: "device_id") @default(0)
log_saved_days Int? @default(7) @db.TinyInt
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device")
device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device_info")
user_fields log_config_userfield_relation[]
}*/
export class LogConfigDto {
@ApiProperty({
type: Number,
description: '设备信息ID',
required: false,
default: 0
})
id: number
@ApiProperty({
type: Number,
description: '设备ID',
required: true,
default: 0
})
@IsNotEmpty({ message: '设备ID不能为空' })
device_id: number
@ApiProperty({
type: Number,
description: '日志保存天数',
required: false,
default: ''
})
log_saved_days: number
@ApiProperty({
type: Number,
description: '创建时间',
required: false,
default: ''
})
created_at: Date | string
@ApiProperty({
type: Date,
description: '更新时间',
required: false,
default: ''
})
updated_at: Date | string
@ApiProperty({
type: Array,
description: '需要上传的用户字段',
required: false,
default: []
})
user_fields: []
}
import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone, IsOptional } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger'
import { BaseDto } from './base.dto'
export class DeviceQueryDto extends BaseDto {
@ApiProperty({
type: String,
description: '设备SN',
required: false,
default: ''
})
sn?: string
@ApiProperty({
type: String,
description: '设备用户',
required: false,
default: ''
})
user?: string
@ApiProperty({
type: String,
description: '使用者手机号',
required: false,
default: ''
})
mobile?: string
}
export class AddDeviceDto {
@ApiProperty({
type: String,
description: '设备SN',
required: true,
default: ''
})
@MaxLength(20, { message: '设备SN不能超过20个字符' })
@IsNotEmpty({ message: '设备SN不能为空' })
sn: string
}
/**
* model device_info {
id Int @id @default(autoincrement())
device_id Int @unique(map: "device_id") @default(0)
user String? @db.VarChar(20)
status Int? @db.TinyInt
last_log_upload_time String? @db.VarChar(30)
last_log_remove_time String? @db.VarChar(30)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
mobile String? @db.VarChar(20)
merchant_name String? @db.VarChar(50)
log_config log_config?
}
*/
export class AddDeviceInfoDto {
@ApiProperty({
type: Number,
description: '设备信息ID',
default: 0
})
id: number
@ApiProperty({
type: Number,
description: '设备ID',
default: 0
})
@IsNumber({}, { message: '设备ID必须是数字' })
@IsNotEmpty({ message: '设备ID不能为空' })
device_id: number
@ApiProperty({
type: String,
description: '设备用户',
default: ''
})
user: string
@ApiProperty({
type: Number,
description: '设备状态',
default: 0
})
status: number
@ApiProperty({
type: String,
description: '最后一次上传日志的时间',
default: ''
})
last_log_upload_time: string
@ApiProperty({
type: String,
description: '最后一次移除日志的时间',
default: ''
})
last_log_remove_time: string
@ApiProperty({
type: Number,
description: '创建时间',
default: ''
})
created_at: Date
@ApiProperty({
type: Date,
description: '更新时间',
default: ''
})
updated_at: Date
@IsMobilePhone('zh-CN', {}, { message: '手机号格式不正确' })
@IsOptional()
@ApiProperty({
type: String,
description: '使用者手机号',
default: ''
})
mobile: string
@ApiProperty({
type: String,
description: '使用者商户名称',
default: ''
})
merchant_name: string
@ApiProperty({
type: Object,
description: '日志配置',
default: {}
})
log_config: {}
}
import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone, IsOptional } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger'
export class DeviceStatusDto {
@ApiProperty({
type: Number,
description: '设备ID',
default: 0
})
@IsNumber({}, { message: '设备ID必须是数字' })
@IsNotEmpty({ message: '设备ID不能为空' })
device_id: number
@IsNumber({}, { message: '设备状态必须是数字' })
@IsNotEmpty({ message: '设备状态不能为空' })
@ApiProperty({
type: Number,
description: '设备状态',
default: 0
})
status: number
@IsNotEmpty({ message: 'SocketID不能为空' })
@ApiProperty({
type: String,
description: 'SocketID',
default: ''
})
socket_id: string
}
import { IsNumber, IsNotEmpty, ValidateIf, IsInt, Matches, isString, IsEnum, IsDefined, isEnum, IsOptional, } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger'
import { Transform } from 'class-transformer'
import { DocTypes } from '../common/enums'
import { BaseDto } from './base.dto'
export class FileQueryDto extends BaseDto {
@ApiProperty({
type: String,
description: '文件名称',
required: false,
default: ''
})
filename?: string
@ApiProperty({
type: String,
description: '文件类型',
required: false,
default: ''
})
@IsOptional() // 允许为空
@IsEnum(DocTypes) // 非空时必须为 DocTypes 枚举中的一个值
type?: DocTypes
}
export class FileDeleteDto {
@ApiProperty({
type: Number,
description: '文件记录表主键Id',
default: 0
})
@Transform(({ value }) => (isString(value) && !isNaN(Number(value)) ? value : undefined), {
toClassOnly: true,
})
@Matches(/[0-9]+$/, { message: 'id must be a numeric string' })
@IsNotEmpty({ message: 'id不能为空' })
id: number | string
}
\ No newline at end of file \ No newline at end of file
export * from './broadcast.dto'
export * from './config.dto'
export * from './device.dto'
export * from './response.dto'
export * from './device.status.dto'
export * from './file.dto'
\ No newline at end of file \ No newline at end of file
import { ApiProperty } from '@nestjs/swagger';
import { RESPONSE_CODE, RESPONSE_MSG } from '../common/enums';
export class ResponseDto {
@ApiProperty({
type: Number,
description: '业务状态码',
default: RESPONSE_CODE.SUCCESS,
})
code: number;
@ApiProperty({
type: String,
description: '业务信息',
default: RESPONSE_MSG.SUCCESS,
})
msg: string;
@ApiProperty({ description: '请求接口路径' })
url: string;
@ApiProperty({ description: '业务数据' })
data?: any;
@ApiProperty({ type: Number, description: '时间戳', default: 1720685424078 })
timestamp: number;
}
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
import { name, description, version } from '../../package.json'
import { INestApplication } from '@nestjs/common'
export const docBuilder = (app: INestApplication<any>) => {
const options = new DocumentBuilder()
.setTitle(name)
.setDescription(description)
.setVersion(version)
.addBearerAuth() // 允许tonken鉴权
.build()
const document = SwaggerModule.createDocument(app, options)
SwaggerModule.setup('/api/doc', app, document)
}
import { INestApplication } from '@nestjs/common'
import { ValidationPipe } from '../common/pipes/validation.pipe'
// import { LoggingInterceptor } from '../common/interceptors/logging.interceptor'
import { ExceptionsFilter, HttpExceptionFilter } from '../common/filters'
import { docBuilder } from './doc'
import { wsRedisAdapter } from './ws'
import { join } from 'path'
export default class Initializer {
static async use(app) {
app.useGlobalFilters(new ExceptionsFilter())
app.useGlobalFilters(new HttpExceptionFilter())
app.enableCors()
// 全局使用中间件
// app.use(logger)
// app.useGlobalFilters(new ValidateExceptionFilter())
// 全局管道
app.useGlobalPipes(new ValidationPipe())
// 全局拦截器
// app.useGlobalInterceptors(new LoggingInterceptor())
app.useStaticAssets(join(__dirname, '..', '..', process.env.STATIC_PATH))
// 初始化文档
docBuilder(app)
// 初始化websocket
await wsRedisAdapter(app)
}
}
import { INestApplication } from '@nestjs/common'
import { RedisIoAdapter } from '../common/adapters'
export const wsRedisAdapter = async (app: INestApplication<any>) => {
const redisIoAdapter = new RedisIoAdapter(app)
await redisIoAdapter.connectToRedis()
app.useWebSocketAdapter(redisIoAdapter)
}
import { InjectQueue } from '@nestjs/bull';
import { Controller, Post } from '@nestjs/common';
import { Queue } from 'bull';
@Controller('audio')
export class AudioController {
constructor(@InjectQueue('audio') private readonly audioQueue: Queue) {}
@Post('transcode')
async transcode() {
await this.audioQueue.add(
'transcode',
{
file: 'audio.mp3',
},
{ delay: 1000 },
);
}
}
import { BullModule } from '@nestjs/bull';
import { Module } from '@nestjs/common';
import { ConfigService } from 'nestjs-config';
import { AudioController } from './audio.controller';
import { AudioProcessor } from './audio.processor';
@Module({
imports: [
BullModule.registerQueueAsync({
name: 'audio',
useFactory: (config: ConfigService) => ({
redis: config.get('redis')
}),
inject: [ConfigService]
}),
],
controllers: [AudioController],
providers: [AudioProcessor],
})
export class AudioModule {}
import { Process, Processor, OnQueueActive } from '@nestjs/bull';
import { Logger } from '@nestjs/common';
import { Job } from 'bull';
@Processor('audio')
export class AudioProcessor {
private readonly logger = new Logger(AudioProcessor.name);
@OnQueueActive()
onActive(job: Job) {
this.logger.debug(`Processing job ${job.id} of type ${job.name} with data ${job.data}...`)
}
@Process('transcode')
handleTranscode(job: Job) {
this.logger.debug('Start transcoding...');
this.logger.debug(job.data);
this.logger.debug('Transcoding completed');
}
}
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { NestExpressApplication } from '@nestjs/platform-express'
import Initializer from './initor'
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule)
await Initializer.use(app)
await app.listen(process.env.APP_PORT)
}
bootstrap()
import { Controller, Get, Post, Request, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
@Controller()
export class AuthController {
constructor(private readonly authService: AuthService) {}
// 登录测试
@UseGuards(AuthGuard('local'))
@Post('/auth/login')
async login(@Request() req) {
return this.authService.login(req.user);
}
// 测试登录后才可访问的接口,在需要的地方使用守卫,可保证必须携带token才能访问
@UseGuards(AuthGuard('jwt'))
@Get('me')
getProfile(@Request() req) {
return req.user;
}
}
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
// import { UsersModule } from '../users/users.module';
import { AuthController } from './auth.controller';
import { LocalStrategy } from './local.strategy';
import { JwtStrategy } from './jwt.strategy';
import { jwtConstants } from './constants';
@Module({
imports: [
// UsersModule,
PassportModule,
JwtModule.register({
secret: jwtConstants.secret,
signOptions: { expiresIn: '60s' },
}),
],
controllers: [AuthController],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
constructor(
// private readonly usersService: UsersService,
private readonly jwtService: JwtService,
) {}
async validateUser(username: string, pass: string): Promise<any> {
// const user = await this.usersService.find(username);
const user = { name: 'walker123', password: '123321' };
if (user && user.password) {
const { password, ...result } = user;
return result;
}
return null;
}
async login(user: any): Promise<any> {
const payload = {username: user.username, sub: user.userId};
return {
access_token: this.jwtService.sign(payload),
};
}
}
export const jwtConstants = {
secret: 'secretKey',
};
import { Strategy, ExtractJwt } from 'passport-jwt';
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { jwtConstants } from './constants';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromHeader('token'),
ignoreExpiration: false,
secretOrKey: jwtConstants.secret,
});
}
async validate(payload: any) {
return {userId: payload.sub, username: payload.username};
}
}
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { AuthService } from './auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<any> {
// tslint:disable-next-line
console.log(username, password)
return {username, password};
const user = await this.authService.validateUser(username, password);
if (!user) {
throw new HttpException(
{ message: 'authorized failed', error: 'please try again later.' },
HttpStatus.BAD_REQUEST);
}
return user;
}
}
import { Controller, Post, Body, UseInterceptors, UsePipes, Logger } from '@nestjs/common'
import { BroadcastService } from './broadcast.service'
import { TransformInterceptor } from '../../common/interceptors'
import { WsGateway } from '../ws/ws.gateway'
import { BroadcastDto } from '../../dto'
import { ValidationPipe } from '../../common/pipes'
import { ApiOperation, ApiTags } from '@nestjs/swagger'
import { OnEvent } from '@nestjs/event-emitter'
import { Events } from '../../common/enums'
@ApiTags('广播')
@Controller('broadcast')
@UseInterceptors(TransformInterceptor)
@UsePipes(new ValidationPipe()) // 使用管道验证
export class BroadcastController {
/**
* @param wsGateway - WsGateway实例
*/
constructor(
private readonly wsGateway: WsGateway,
private readonly broadcastService: BroadcastService
) {}
/**
* 发送广播消息
* @param params - 包含广播消息的对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@Post('/cmd')
@ApiOperation({ summary: '给设备发送指令' })
async message(@Body() params: BroadcastDto): Promise<CommonTypes.IResData> {
return this.wsGateway.send(params)
}
@OnEvent(Events.OnMessage)
onMessage(@Body() params: any): Promise<CommonTypes.IResData> {
Logger.debug('收到私有订阅消息:', params)
return this.broadcastService.onMessage(params)
}
}
import { Module } from '@nestjs/common'
import { BroadcastController } from './broadcast.controller'
import { BroadcastService } from './broadcast.service'
import { WsModule } from '../ws/ws.module';
import { WsService } from '../ws/ws.service';
import { HttpModule } from '@nestjs/axios';
@Module({
imports: [WsModule,HttpModule],
controllers: [BroadcastController],
providers: [BroadcastService,WsService]
})
export class BroadcastModule {}
import { HttpService } from '@nestjs/axios'
import { Inject, Injectable } from '@nestjs/common'
import { AxiosResponse } from 'axios'
import { ConfigService } from 'nestjs-config'
import { Command, Events, FileCommand, RESPONSE_CODE } from '../../common/enums'
import { EventEmitter2 } from '@nestjs/event-emitter'
@Injectable()
export class BroadcastService {
private webHook: string
constructor(
private readonly httpService: HttpService,
private readonly config: ConfigService,
@Inject(EventEmitter2)
private readonly eventEmitter: EventEmitter2
) {
this.webHook = this.config.get('env').AppWebhook
}
// // 广播消息
async onMessage(param: any): Promise<CommonTypes.IResData> {
if (param?.code === RESPONSE_CODE.SUCCESS && param?.data?.command === Command.File && param?.data?.payload?.command === FileCommand.Remove) {
this.eventEmitter.emit(Events.OnLogFileRemoved, { device_id: param.device_id, last_log_remove_time: new Date() })
return
}
const res: AxiosResponse<any, any> = await this.httpService
.post(this.webHook, {
msgtype: 'text',
text: {
content: JSON.stringify(param)
}
})
.toPromise()
return { code: res.status, message: '发送企微消息成功' }
}
}
import { Controller, Post, Body, UseInterceptors, Get, UsePipes, Param, Query } from '@nestjs/common'
import { ConfigService } from './config.service'
import { TransformInterceptor } from '../../common/interceptors'
import { LogConfigDto } from '../../dto/config.dto'
import { PagesPipe, ParseDeviceIdPipe, ValidationPipe } from '../../common/pipes'
import { ApiOperation, ApiTags } from '@nestjs/swagger'
@ApiTags('设备配置信息')
@Controller('config')
@UseInterceptors(TransformInterceptor)
@UsePipes(new ValidationPipe()) // 使用管道验证
export class ConfigController {
constructor(private readonly configService: ConfigService) {}
@Get()
@UsePipes(new PagesPipe())
@UsePipes(new ParseDeviceIdPipe())
@ApiOperation({ summary: '根据设备号获取配置' })
async findAll(@Query() params: LogConfigDto): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> {
return this.configService.findAll(params)
}
@Post('/add')
@ApiOperation({ summary: '新增设备配置' })
addConfig(@Body() param: LogConfigDto): Promise<CommonTypes.IResData> {
return this.configService.addConfig(param)
}
}
import { Module } from '@nestjs/common'
import { ConfigController } from './config.controller'
import { ConfigService } from './config.service'
import { PrismaService } from 'nestjs-prisma'
@Module({
controllers: [ConfigController],
providers: [ConfigService,PrismaService]
})
export class LogConfigModule {}
import { Injectable, Inject } from '@nestjs/common'
import { PrismaService } from 'nestjs-prisma'
import { RESPONSE_CODE } from '../../common/enums'
@Injectable()
export class ConfigService {
constructor(
@Inject(PrismaService)
private readonly prisma: PrismaService // private connection: Connection,
) {}
async findAll({ device_id, skip, take }: ConfigTypes.LogConfigQuery): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> {
const where: any = {
device_id
}
const result: ConfigTypes.LogConfigResult[] = await this.prisma.log_config.findMany({
skip,
take,
select: {
id: true,
device_id: true,
log_saved_days: true,
user_fields: {
select: {
log_user_field: {
select: {
name: true
}
}
}
}
},
where
})
const data: ConfigTypes.LogConfigResponse[] = result.map(item => {
return {
id: item.id,
device_id: item.device_id,
log_saved_days: item.log_saved_days,
user_fields: item.user_fields.map(item => item.log_user_field.name)
}
})
const total = await this.prisma.log_config.count({
where
})
const resBody: CommonTypes.IResData<ConfigTypes.LogConfigResponse[]> = { total, data }
return resBody
}
async addConfig(config: ConfigTypes.LogConfigAdd): Promise<CommonTypes.IResData> {
const { user_fields, ...data } = config
let config_id: number = 0
await this.prisma.$transaction(async prisma => {
const date = new Date()
const { id } = (await prisma.log_config.findUnique({ where: { device_id: data.device_id }, select: { id: true } })) || {}
config.updated_at = date
if (id) {
config_id = id
await prisma.log_config.update({ where: { device_id: data.device_id }, data })
await prisma.log_config_userfield_relation.deleteMany({ where: { config_id: id } })
} else {
config.created_at = date
const { id } = await prisma.log_config.create({ data, select: { id: true } })
config_id = id
}
const relations: RelationsTypes.LogConfigUserFieldsRel[] = user_fields.map((ufid: number) => {
return {
config_id,
user_field_id: ufid
}
})
await prisma.log_config_userfield_relation.createMany({ data: relations, skipDuplicates: true })
})
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
}
}
import { Controller, Get, Post, Body, UseInterceptors, Query, UsePipes, Inject } from '@nestjs/common'
import { DeviceService } from './device.service'
import { TransformInterceptor } from '../../common/interceptors'
import { AddDeviceDto, AddDeviceInfoDto, DeviceQueryDto, DeviceStatusDto } from '../../dto'
import { PagesPipe, ValidationPipe } from '../../common/pipes'
import { OnEvent, EventEmitter2 } from '@nestjs/event-emitter'
import { WsAccess, Events, WsMessageType, Command, RESPONSE_CODE, FileCommand } from '../../common/enums'
import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'
@ApiTags('设备管理')
@Controller('device')
@UseInterceptors(TransformInterceptor)
// @UsePipes(new ValidationPipe({transform: true}))
@UsePipes(new ValidationPipe()) // 使用管道验证
export class DeviceController {
/**
* 构造函数,注入DeviceService和EventEmitter2
* @param param - 包含设备信息的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
constructor(
@Inject(DeviceService)
private readonly deviceService: DeviceService,
@Inject(EventEmitter2)
private eventEmitter: EventEmitter2
) {}
/**
* 查找所有设备的方法
* 该方法接收一个包含查询条件的对象,并返回符合条件的设备列表
* @param param - 包含查询条件的对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@Get()
@UsePipes(new PagesPipe())
@ApiOperation({ summary: '获取所有设备列表' })
findAll(@Query() params: DeviceQueryDto): Promise<CommonTypes.IResData> {
return this.deviceService.findAll(params)
}
/**
* 添加设备的方法
* 该方法接收一个包含设备信息的DTO对象,并返回添加后的设备信息
* @param param - 包含设备信息的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@Post('/add')
@ApiOperation({ summary: '添加设备' })
addDevice(@Body() param: AddDeviceDto): Promise<CommonTypes.IResponseBase> {
// console.log(param)
return this.deviceService.addDevice(param)
}
/**
* 添加设备信息的方法
* 该方法接收一个包含设备信息的DTO对象,并返回添加后的设备信息
* @param param - 包含设备信息的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@Post('/addInfo')
@ApiOperation({ summary: '添加设备信息' })
addDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> {
// console.log(param)
return this.deviceService.addDeviceInfo(param)
}
/**
* 更新设备信息的方法
* 该方法接收一个包含设备信息的DTO对象,并返回更新后的设备信息
* @param param - 包含设备信息的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@Post('/updateInfo')
@ApiOperation({ summary: '修改设备信息' })
@OnEvent(Events.OnLogFileRemoved)
updateDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> {
return this.deviceService.updateDeviceInfo(param)
}
/**
* 更新设备状态的方法
* 该方法接收一个包含设备状态的DTO对象,并返回更新后的设备状态
* @param param - 包含设备状态的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@OnEvent(Events.OnConnected)
@Post('/upsertStatus')
@ApiOperation({ summary: '更新设备状态' })
async upsertDeviceStatus(@Body() param: DeviceStatusDto): Promise<void | CommonTypes.IResponseBase> {
return await this.deviceService.upsertDeviceStatus(param).catch(error => {
const out: WsTypes.WsConnError = { message: WsAccess.ConnFailure, device_id: param.device_id }
this.eventEmitter.emit(Events.OnConnectError, out)
})
}
/**
* 重置所有设备状态的方法
* 该方法接收一个包含设备状态的DTO对象,并返回更新后的设备状态
* @param param - 包含设备状态的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@Post('/offlineAll')
@OnEvent(Events.OnOfflineAll)
@ApiOperation({ summary: '修改所有设备状态为离线' })
async resetAllDeviceStatus(): Promise<void | CommonTypes.IResponseBase> {
return await this.deviceService.resetAllDeviceStatus()
}
@Get('/task')
@OnEvent(Events.OnTaskStart)
@ApiOperation({ summary: '日任务' })
async task(): Promise<void | CommonTypes.IResData> {
return await this.deviceService.removeFilesTask()
}
@Get('/addAll')
@ApiOperation({ summary: '批量导入设备,用于初始化数据' })
async addAll(devices: Array<any>): Promise<void | CommonTypes.IResponseBase> {
// return this.deviceService.addAll(devices)
}
}
import { Module } from '@nestjs/common';
import { DeviceController } from './device.controller';
import { DeviceService } from './device.service';
import { PrismaService } from 'nestjs-prisma';
import { WsModule } from '../ws/ws.module';
import { WsService } from '../ws/ws.service';
// import { EventEmitter2 } from '@nestjs/event-emitter';
@Module({
imports: [WsModule],
controllers: [DeviceController],
providers: [DeviceService,PrismaService,WsService],
})
export class DeviceModule {}
import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } from '@nestjs/common'
// import { Repository, Connection, getRepository } from 'typeorm';
// import { InjectRepository } from '@nestjs/typeorm';
// import { Device as DeviceEntity } from '../entities/Device'
import { PrismaService } from 'nestjs-prisma'
import { Command, FileCommand, RESPONSE_CODE, WsMessageType, WsStatus } from '../../common/enums'
import { WsGateway } from '../ws/ws.gateway'
@Injectable()
export class DeviceService implements OnModuleInit {
constructor(
@Inject(PrismaService)
private readonly prisma: PrismaService, // private connection: Connection,
private readonly wsGateway: WsGateway
) {}
async onModuleInit() {
this.resetAllDeviceStatus()
}
async findAll({ user, mobile, sn, skip, take }: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData<DeviceTypes.IDeviceInfo[]>> {
const where = {
sn: {
contains: sn
},
AND: {
device_info: {
mobile: {
contains: mobile
},
user: {
contains: user
}
}
}
}
const result: Omit<DeviceTypes.IDeviceResult, 'id'>[] = await this.prisma.device.findMany({
skip,
take,
select: {
sn: true,
device_info: {
select: {
user: true,
mobile: true,
merchant_name: true,
log_config: {
select: {
log_saved_days: true,
user_fields: {
select: {
log_user_field: {
select: {
name: true
}
}
}
}
}
},
device_status: {
select: { status: true }
}
}
}
},
where
})
const total: number = await this.prisma.device.count({
where
})
const data: DeviceTypes.IDeviceInfo[] = result.reduce((pre: DeviceTypes.IDeviceInfo[], cur: DeviceTypes.IDeviceResult) => {
pre.push({
sn: cur.sn,
user: cur.device_info?.user,
mobile: cur.device_info?.mobile,
status: cur.device_info?.device_status?.status,
merchant_name: cur.device_info?.merchant_name,
log_saved_days: cur.device_info?.log_config?.log_saved_days,
log_user_fields: cur.device_info?.log_config?.user_fields?.map((item: DeviceTypes.ILogUserFields) => item.log_user_field.name)
})
return pre
}, [])
const resBody: CommonTypes.IResData<DeviceTypes.IDeviceInfo[]> = { total, data }
return resBody
}
async addDevice(device: Omit<DeviceTypes.IDevice, 'id' | 'create_time'>): Promise<CommonTypes.IResData> {
await this.prisma.$transaction(async prisma => {
const { id } = await prisma.device.create({ data: device, select: { id: true } })
// await this.addDeviceInfo({device_id:id})
await prisma.device_info.create({ data: { device_id: id, created_at: new Date(), updated_at: new Date() } })
await prisma.device_status.create({ data: { device_id: id, status: WsStatus.Offline } })
})
return { code: RESPONSE_CODE.SUCCESS, message: '添加设备成功' }
}
async addDeviceInfo(deviceInfo: Omit<DeviceTypes.IDeviceInfoInput, 'sn'>): Promise<CommonTypes.IResData> {
deviceInfo.created_at = new Date()
deviceInfo.updated_at = new Date()
await this.prisma.$transaction(async prisma => {
await prisma.device_info.create({ data: deviceInfo })
await prisma.device_status.create({ data: { device_id: deviceInfo.device_id, status: WsStatus.Offline } })
})
return { code: RESPONSE_CODE.SUCCESS, message: '添加设备信息成功' }
}
async updateDeviceInfo(deviceInfo: Omit<DeviceTypes.IDeviceInfoInput, 'sn'>): Promise<CommonTypes.IResData> {
const { device_id, ...data } = deviceInfo
data.updated_at = new Date()
await this.prisma.device_info.update({
where: {
device_id: deviceInfo.device_id
},
data
})
return { code: RESPONSE_CODE.SUCCESS, message: '设备信息更新成功' }
}
async upsertDeviceStatus(data: DeviceStatus.IDeviceStatus): Promise<CommonTypes.IResData> {
await this.prisma.device_status.upsert({
where: {
device_id: data.device_id
},
create: data,
update: {
status: data.status
}
})
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
}
async resetAllDeviceStatus(): Promise<CommonTypes.IResData> {
Logger.debug('===重置所有设备状态===')
await this.prisma.device_status.updateMany({
data: {
status: WsStatus.Offline
}
})
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
}
async addAll(devices: Array<any>): Promise<CommonTypes.IResponseBase> {
for (let index = 0; index < devices.length; index++) {
const el = devices[index]
await this.prisma.$transaction(async prisma => {
const { id } = await prisma.device.create({ data: { sn: el.设备编号 }, select: { id: true } })
await prisma.device_info.create({ data: { device_id: id, mobile: el.手机号, merchant_name: el.最近使用人所在门店 || '', user: el.保管人, created_at: new Date(), updated_at: new Date() } })
await prisma.device_status.create({ data: { device_id: id, status: WsStatus.Offline } })
const { id: cfgid } = await prisma.log_config.create({ data: { device_id: id, log_saved_days: 7 }, select: { id: true } })
await prisma.log_config_userfield_relation.createMany({
data: [
{ config_id: cfgid, user_field_id: 1 },
{ config_id: cfgid, user_field_id: 2 },
{ config_id: cfgid, user_field_id: 3 }
]
})
})
}
return { code: RESPONSE_CODE.SUCCESS, message: '添加成功' }
}
async removeFilesTask(): Promise<CommonTypes.IResData> {
const results: (CommonTypes.IDeviceId & Pick<DeviceTypes.IDeviceInfoBase, 'log_saved_days'>)[] = await this.prisma.$queryRaw<(CommonTypes.IDeviceId & Pick<DeviceTypes.IDeviceInfoBase, 'log_saved_days'>)[]>`
SELECT d.device_id, c.log_saved_days
FROM device_info d
JOIN log_config c ON c.device_id = d.device_id
WHERE c.log_saved_days >= TIMESTAMPDIFF(DAY, d.last_log_remove_time, NOW());`
for (const { device_id, log_saved_days } of results) {
await this.wsGateway.send({ event: WsMessageType.Private, device_id, data: { command: Command.File, payload: { command: FileCommand.Remove, days: log_saved_days } } })
}
return { code: RESPONSE_CODE.SUCCESS, message: '每日日志删除任务完成' }
}
}
import { Controller, Get } from '@nestjs/common';
import { EmailService } from './email.service';
@Controller('email')
export class EmailController {
constructor(private readonly emailService: EmailService) {}
@Get()
sendEmail(): string {
this.emailService.sendEmail();
return 'Message sent';
}
}
import { Module } from '@nestjs/common';
import { EmailController } from './email.controller';
import { EmailService } from './email.service';
@Module({
imports: [],
controllers: [EmailController],
providers: [EmailService],
})
export class EmailModule {}
import { Injectable } from '@nestjs/common';
import { MailerService } from '@nest-modules/mailer';
@Injectable()
export class EmailService {
constructor(private readonly mailerService: MailerService) {}
sendEmail() {
this.mailerService.sendMail({
to: 'flana_zhong@163.com',
from: '1255968521@qq.com',
// subject: 'Testing Nest MailerModule ✔',
subject: 'Walker Lee Love You ✔',
// html: '<b>Welcome Frost!</b>',
template: './welcome',
context: {
// Data to be sent to template engine.
code: 'cf1a3f828287',
username: 'walker lee',
},
});
}
}
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity("device", { schema: "app_admin" })
export class Device {
@PrimaryGeneratedColumn({ type: "int", name: "id" })
id: number;
@Column("datetime", { name: "create_time" })
createTime: Date;
@Column("varchar", { name: "sn", length: 20 })
sn: string;
}
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity("device_info", { schema: "app_admin" })
export class DeviceInfo {
@PrimaryGeneratedColumn({ type: "int", name: "id", comment: "主键,自增" })
id: number;
@Column("varchar", { name: "device_sn", length: 20 })
deviceSn: string;
@Column("varchar", {
name: "user",
nullable: true,
comment: "使用者(员工)",
length: 20,
})
user: string | null;
@Column("tinyint", {
name: "status",
nullable: true,
comment: "0:废弃;1:离线;2:在线",
})
status: number | null;
@Column("datetime", {
name: "last_log_upload_time",
nullable: true,
comment: "最后一次日志上传时间",
})
lastLogUploadTime: Date | null;
@Column("date", {
name: "last_log_remove_time",
nullable: true,
comment: "最后一次清除日志日期",
})
lastLogRemoveTime: string | null;
}
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import { LogUserField } from "./LogUserField";
@Entity("log_config", { schema: "app_admin" })
export class LogConfig {
@PrimaryGeneratedColumn({ type: "int", name: "id" })
id: number;
@Column("varchar", {
name: "device_sn",
comment: "设备ID,device表sn",
length: 50,
})
deviceSn: string;
@Column("tinyint", {
name: "log_saved_days",
nullable: true,
comment: "日志保留天数",
default: () => "'7'",
})
logSavedDays: number | null;
@OneToMany(() => LogUserField, (logUserField) => logUserField.config)
logUserFields: LogUserField[];
}
import {
Column,
Entity,
Index,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
} from "typeorm";
import { LogConfig } from "./LogConfig";
@Index("FK_log_user_field_log_config", ["configId"], {})
@Entity("log_user_field", { schema: "app_admin" })
export class LogUserField {
@PrimaryGeneratedColumn({ type: "int", name: "id", comment: "主键,自增" })
id: number;
@Column("varchar", { name: "name", comment: "字段名", length: 20 })
name: string;
@Column("int", { name: "config_id", nullable: true })
configId: number | null;
@ManyToOne(() => LogConfig, (logConfig) => logConfig.logUserFields, {
onDelete: "NO ACTION",
onUpdate: "NO ACTION",
})
@JoinColumn([{ name: "config_id", referencedColumnName: "id" }])
config: LogConfig;
}
import { Controller, Get, Post, Patch, Query, Delete, Body, Param, Headers, UseFilters, HttpException, HttpStatus, ParseIntPipe } from '@nestjs/common'
import { ApiTags, ApiBearerAuth, ApiBody, ApiParam } from '@nestjs/swagger'
import { ExceptionService } from './exception.service'
import { HttpExceptionFilter } from '../../common/filters/http-exception.filter'
@ApiBearerAuth()
@ApiTags('exception')
// @UseFilters(new HttpExceptionFilter())
@Controller('/exception')
export class ExceptionController {
constructor(private readonly exceptionService: ExceptionService) {}
// 查询
@Get()
fetch(@Query() { id }, @Headers('token') token): string {
if (!id) {
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: '请求参数id 必传', error: 'id is required' }, HttpStatus.BAD_REQUEST)
}
return this.exceptionService.fetch(id)
}
// 创建
@Post()
@ApiBody({ description: '填写更新内容' })
save(@Body() { message, id }): string {
return this.exceptionService.save(message)
}
// 更新
@Patch(':id')
@ApiParam({ name: 'id' })
@ApiBody({ description: '请输入message' })
// 有时,我们希望参数的类型为数字,则可以通过管道进行转换
// !现nest自带部分管道
update(@Param('id', new ParseIntPipe()) id, @Body() { message }): string {
console.log(typeof id)
return this.exceptionService.update(id, message)
}
// 删除
@Delete()
remove(@Query() { id }): string {
return this.exceptionService.remove(id)
}
}
import { Module } from '@nestjs/common';
import { ExceptionController } from './exception.controller';
import { ExceptionService } from './exception.service';
@Module({
imports: [],
controllers: [ExceptionController],
providers: [ExceptionService],
})
export class ExceptionModule {}
import { Injectable } from '@nestjs/common';
@Injectable()
export class ExceptionService {
fetch(id): string {
return `Hello World! ${id}`;
}
save(message): string {
return `Set Hello Done.${message}`;
}
update(id: string, message: string): string {
return `Update Hello Done. ${id}:${message}`;
}
remove(id: number): string {
return `${id} Record Was Removed.`;
}
}
import { Controller, Post, UploadedFile, UseInterceptors, Get, Res, Req, Body, Query, UsePipes, ValidationPipe } from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import { FileService } from './file.service'
import { Response, Request } from 'express'
import { FileMimeTypeFilter } from '../../common/filters'
import { UploadFile } from '../../common/decorators'
import { DocTypes } from '../../common/enums'
import { FileDeleteDto, FileQueryDto } from '../../dto'
import { ApiOperation, ApiTags } from '@nestjs/swagger'
import { FilePathPipe, PagesPipe, ParseDeviceIdPipe, ParseIdPipe } from '../../common/pipes'
@ApiTags('文件管理')
@UsePipes(new ValidationPipe())
@Controller('file')
export class FileController {
/**
* 文件服务的构造函数。
*
* @param fileService - 文件服务的实例,用于处理文件相关操作。
*/
constructor(private readonly fileService: FileService) {}
/**
* 上传文件的方法
* 该方法接收一个文件对象和一个请求对象,并将文件信息保存到数据库中
* @param file - 包含文件信息的Express.Multer.File对象
* @param req - 包含请求信息的Request对象
* @returns 返回上传的文件对象
*/
@Post('upload')
@UsePipes(new FilePathPipe())
@ApiOperation({ summary: '文件上传' })
@UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain'), limits: { fileSize: 1024 * 1024 * 100 } })
upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request): FileTypes.FileUpload<DocTypes> {
const { fieldname, encoding, destination, stream, buffer, path, ...o } = file
const bodyData: Pick<FileTypes.FileUpload<DocTypes>, 'device_id' | 'type'> = { device_id: Number(req.body.deviceId), type: req.body.type }
const f: FileTypes.FileUpload<DocTypes> = Object.assign({ created_at: new Date(), path: `${req.protocol}://${req.get('Host')}${path}` }, bodyData, o)
this.fileService.save(f)
return f
}
/**
* 获取所有文件的方法
* 该方法接收一个文件类型和一个设备ID和文件名,并返回该设备下所有指定类型的文件
* @param params - 包含文件类型和设备ID的对象
* @returns 返回该设备下所有指定类型的文件
*/
@Get('list')
@UsePipes(new PagesPipe())
@UsePipes(new ParseDeviceIdPipe())
@ApiOperation({ summary: '获取文件列表' })
async findAll(@Query() params: FileQueryDto): Promise<CommonTypes.IResData<FileTypes.IFile<DocTypes | string>[]>> {
return await this.fileService.findAll(params)
}
/**
* 删除文件的方法
* 该方法接收一个文件ID,并将文件从数据库中删除
* @param id - 要删除的文件ID
* @returns 返回删除结果
*/
@Get('delete')
@UsePipes(new ParseIdPipe())
@ApiOperation({ summary: '根据ID删除文件' })
async remove(@Query() { id }: FileDeleteDto): Promise<CommonTypes.IResData> {
return await this.fileService.remove(id as number)
}
/**
* 导出所有文件的方法
* 该方法将所有文件打包成一个tar文件并返回给客户端
* @param res - 包含响应信息的Response对象
* @returns 返回打包后的tar文件
*/
// @Get('export')
// async downloadAll(@Res() res: Response) {
// const { filename, tarStream } = await this.fileService.downloadAll()
// res.setHeader('Content-Type', 'application/octet-stream')
// res.setHeader('Content-Disposition', `attachment; filename=${filename}`)
// tarStream.pipe(res)
// }
}
import { Module } from '@nestjs/common';
import { MulterModule } from '@nestjs/platform-express';
import { ConfigService } from 'nestjs-config';
import { FileController } from './file.controller';
import { FileService } from './file.service';
import { PrismaService } from 'nestjs-prisma';
@Module({
imports: [
MulterModule.registerAsync({
useFactory: (config: ConfigService) => config.get('file'),
inject: [ConfigService],
}),
],
controllers: [FileController],
providers: [FileService,PrismaService],
})
export class FileModule {}
import { Inject, Injectable } from '@nestjs/common'
import { tar } from 'compressing'
import { ConfigService } from 'nestjs-config'
import * as fs from 'fs'
import * as path from 'path'
import { DocTypes, RESPONSE_CODE } from '../../common/enums'
import { PrismaService } from 'nestjs-prisma'
import { Doc } from 'prettier'
@Injectable()
export class FileService {
/**
* 文件服务的构造函数。
*
* @param configService - 配置服务的实例,用于获取配置信息。
* @param prisma - PrismaService的实例,用于数据库操作。
*/
constructor(
private readonly configService: ConfigService,
@Inject(PrismaService)
private readonly prisma: PrismaService // private connection: Connection,
) {}
/**
* 获取所有文件的方法。
*
* @returns 一个 Promise,成功时解析为包含所有文件的 CommonTypes.IResData 对象。
*/
async findAll({ device_id, type, filename, skip, take }: FileTypes.FindeFiles<DocTypes>): Promise<CommonTypes.IResData<FileTypes.IFile<DocTypes | string>[]>> {
const where = {
device_id,
type,
originalname: {
contains: filename
},
filename: {
contains: filename
}
}
const files: FileTypes.IFile<DocTypes | string>[] = await this.prisma.file.findMany({ skip, take, where })
const total: number = await this.prisma.file.count({
where
})
return { total, data: files }
}
/**
* 保存文件到数据库的方法。
*
* @param file - 要保存的文件对象,包含文件名、路径、创建时间等信息。
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/
async save(file: FileTypes.FileUpload<DocTypes>): Promise<CommonTypes.IResData> {
const { filename, path, created_at, ...where } = file
this.prisma.$transaction(async prisma => {
const { id, path: origin_path } = (await prisma.file.findFirst({ where, select: { id: true, path: true } })) || {}
if (id) {
fs.unlinkSync(origin_path)
await prisma.file.update({ where: { id }, data: { filename, path, created_at } })
} else {
await prisma.file.create({ data: file })
}
await prisma.device_info.update({ where: { device_id: file.device_id }, data: { last_log_upload_time: created_at } })
})
return { code: RESPONSE_CODE.SUCCESS, message: '文件保存成功' }
}
/**
* 从数据库中移除文件。
*
* @param id - 要移除的文件的唯一标识符。
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/
async remove(id: number): Promise<CommonTypes.IResData> {
await this.prisma.$transaction(async prisma => {
const { path } = (await prisma.file.findFirst({ where: { id }, select: { path: true } })) || {}
await prisma.file.delete({ where: { id } })
fs.unlinkSync(path)
})
return { code: RESPONSE_CODE.SUCCESS, message: '删除成功' }
}
async downloadAll() {
const uploadDir = this.configService.get('file').root
const tarStream = new tar.Stream()
await tarStream.addEntry(uploadDir)
return { filename: 'hello-world.tar', tarStream }
}
moveFile(sourcePath: string, destinationPath: string): Promise<void> {
return new Promise((resolve, reject) => {
const rs = fs.createReadStream(sourcePath)
const ws = fs.createWriteStream(destinationPath)
rs.on('error', reject)
ws.on('error', reject)
ws.on('finish', resolve)
rs.pipe(ws)
})
}
removeFileTask() {}
}
import { ApiProperty } from '@nestjs/swagger';
export enum UserRole {
Admin = 'Admin',
User = 'User',
}
export class Hello {
@ApiProperty({ example: 'Kitty', description: 'The name of the Cat' })
name: string;
@ApiProperty({ example: 1, description: 'The age of the Cat' })
age: number;
@ApiProperty({
example: 'Maine Coon',
description: 'The breed of the Cat',
})
breed: string;
@ApiProperty({ enum: UserRole })
role: UserRole;
}
import { IsInt, IsString } from 'class-validator';
export class CreateCatDto {
@IsString()
readonly name: string;
@IsInt()
readonly age: number;
@IsString()
readonly breed: string;
}
import { Test, TestingModule } from '@nestjs/testing';
import { HelloController } from './hello.controller';
import { HelloService } from './hello.service';
describe('AppController', () => {
let appController: HelloService;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [HelloController],
providers: [HelloService],
}).compile();
appController = app.get<HelloController>(HelloController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
import {
Controller,
Get,
Post,
Patch,
Query,
Delete,
Body,
Param,
Headers,
} from '@nestjs/common';
import {
ApiResponse,
ApiTags,
ApiQuery,
ApiBearerAuth,
ApiBody,
ApiParam,
} from '@nestjs/swagger';
import { HelloService } from './hello.service';
import { Hello, UserRole } from './classes/hello';
@ApiBearerAuth()
@ApiTags('hello')
@Controller('/hello')
export class HelloController {
constructor(private readonly helloService: HelloService) {}
// 查询
@Get()
@ApiQuery({ name: 'name', required: false })
@ApiQuery({ name: 'role', enum: UserRole })
@ApiResponse({
status: 200,
description: 'get ...',
type: Hello,
})
fetch(@Query() { id }, @Headers('token') token): string {
// console.log(url);
return this.helloService.fetch(id);
}
// 创建
@Post()
@ApiBody({ description: '填写更新内容' })
save(@Body() { message }): string {
return this.helloService.save(message);
}
// 更新
@Patch(':id')
@ApiParam({ name: 'id' })
@ApiBody({ description: '请输入message' })
update(@Param() { id }, @Body() { message }): string {
return this.helloService.update(id, message);
}
// 删除
@Delete()
remove(@Query() { id }): string {
return this.helloService.remove(id);
}
}
import { Module } from '@nestjs/common';
import { HelloController } from './hello.controller';
import { HelloService } from './hello.service';
@Module({
imports: [],
controllers: [HelloController],
providers: [HelloService],
})
export class HelloModule {}
import { Injectable } from '@nestjs/common';
@Injectable()
export class HelloService {
fetch(id): string {
return `Hello World!! ${id}`;
}
save(message): string {
return `Set Hello Done.${message}`;
}
update(id: string, message: string): string {
return `Update Hello Done. ${id}:${message}`;
}
remove(id: number): string {
return `${id} Record Was Removed.`;
}
}
import { Entity, PrimaryGeneratedColumn, ManyToOne, Column } from 'typeorm';
import { UsersEntity } from '../users/users.entity';
@Entity({ name: 'photo' })
export class PhotoEntity {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(
() => UsersEntity,
user => user.photos,
)
user: UsersEntity;
@Column({ type: 'varchar', length: 80 })
url: string;
}
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { RolesGuard } from '../../common/guards/roles.guard';
import { Roles } from '../../common/decorators/roles.decorator';
import { RoleGuardService } from './role-guard.service';
@ApiBearerAuth()
@ApiTags('role-guard')
@UseGuards(RolesGuard)
@Controller('/role-guard')
export class RoleGuardController {
constructor(private readonly roleGuardService: RoleGuardService) {}
// 查询
@Get()
@Roles('admin')
fetch(@Query() { id }): string {
return this.roleGuardService.fetch(id);
}
}
import { Module } from '@nestjs/common';
import { RoleGuardController } from './role-guard.controller';
import { RoleGuardService } from './role-guard.service';
@Module({
imports: [],
controllers: [RoleGuardController],
providers: [RoleGuardService],
})
export class RoleGuardModule {}
import { Injectable } from '@nestjs/common';
@Injectable()
export class RoleGuardService {
fetch(id): string {
return `Hello World! ${id}`;
}
save(message): string {
return `Set Hello Done.${message}`;
}
update(id: string, message: string): string {
return `Update Hello Done. ${id}:${message}`;
}
remove(id: number): string {
return `${id} Record Was Removed.`;
}
}
import { Controller } from '@nestjs/common'
import { SseService } from './sse.service'
import { Sse } from '@nestjs/common'
import { Observable,interval } from 'rxjs'
import { map } from 'rxjs/operators'
@Controller('sse')
export class SseController {
constructor(private readonly sseService: SseService) {}
@Sse('event')
sse(): Observable<any> {
console.log('hello world')
return interval(1000).pipe(map((_) => ({ data:'hello world' } )));
}
// sse(): Observable<MessageEvent> {
// return new Observable<any>(observer => {
// // 监听事件
// // this.eventEmitter.on(EVENTBUS_TYPE.MESSAGE_CREATE, (data: Message) => {
// // observer.next({ a: 111 })
// // })
// console.log('hello world1111111111')
// observer.next({ data: 'hello world2' });
// })
// }
}
import { Module } from '@nestjs/common'
import { SseController } from './sse.controller'
import { SseService } from './sse.service'
@Module({
imports: [],
controllers: [SseController],
providers: [SseService]
})
export class SseModule {}
import { Injectable, HttpException, HttpStatus } from '@nestjs/common'
@Injectable()
export class SseService {}
import { Controller, Get, Post, Body } from '@nestjs/common';
import { UsersService } from './users.service';
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
findAll() {
return this.usersService.findAll();
}
@Post()
async create(@Body() param) {
const newParam = { ...param, status: true };
await this.usersService.create(newParam);
return true;
}
@Post('/many')
async createMany(@Body() users) {
const newUsers = users.map(user => ({ ...user, status: true }));
await this.usersService.createMany(newUsers);
return true
}
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!