Commit ce33cdb0 by yixinjj

完善一些功能

1 parent 31ca4c8e
......@@ -4,4 +4,5 @@
# 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://user_limin:LmotGSOY@192.168.3.113:3306/app_admin?schema=public"
\ No newline at end of file
DATABASE_URL="mysql://limin:limin1018@192.168.1.129:3306/app_admin?schema=public"
SOCKET_PORT=8080
\ No newline at end of file
......@@ -12,15 +12,33 @@ CREATE TABLE `device_info` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`device_id` INTEGER NOT NULL DEFAULT 0,
`user` VARCHAR(20) NULL,
`status` TINYINT NULL,
`last_log_upload_time` VARCHAR(30) NULL,
`last_log_remove_time` VARCHAR(30) 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_id`(`device_id`),
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;
......@@ -32,7 +50,7 @@ CREATE TABLE `log_config` (
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
UNIQUE INDEX `device_id`(`device_id`),
UNIQUE INDEX `log_config_device_id_key`(`device_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
......@@ -41,8 +59,6 @@ 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,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
INDEX `FK_log_config_userfield_relation_log_config`(`config_id`),
INDEX `FK_log_config_userfield_relation_log_user_field`(`user_field_id`),
......@@ -63,6 +79,18 @@ CREATE TABLE `log_user_field` (
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
......
/*
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`);
......@@ -9,30 +9,54 @@ datasource db {
model device {
id Int @id @default(autoincrement())
sn String @db.VarChar(20)
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(map: "device_id") @default(0)
device_id Int @unique @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)
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(map: "device_id") @default(0)
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)
......@@ -45,8 +69,6 @@ model log_config_userfield_relation {
id Int @id @default(autoincrement())
config_id Int @default(0)
user_field_id Int @default(0)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(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")
......@@ -59,5 +81,5 @@ model log_user_field {
name String @db.VarChar(20)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
config_ids log_config_userfield_relation[]
log_config_userfield_relation log_config_userfield_relation[]
}
......@@ -6,7 +6,7 @@ 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 { 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'
......@@ -37,7 +37,7 @@ import { EventEmitterModule } from '@nestjs/event-emitter'
}),
ScheduleModule.forRoot(),
EventEmitterModule.forRoot(),
// TasksModule,
TasksModule,
// AudioModule,
// AuthModule,
// HelloModule,
......
......@@ -41,9 +41,20 @@ export enum WsAccess {
InValidToken = '无效token',
InvalidDeviceId = '无效设备id',
IsOnline = '通过验证,设备上线',
IsOffline = '设备下线'
IsOffline = '设备下线',
ConnFailure = '设备连接失败,请检查设备号是否正确'
}
export enum WsConnEvents {
Connection = 'connection'
OnConnected = 'device.connected',
OnConnectError = 'device.connect.error'
}
export enum FileUploadEvents {
OnLogFileUploaded = 'log.file.uploaded'
}
export enum DocTypes {
Log = 'log',
Image = 'image',
Video = 'video',
Other = 'other'
}
......@@ -5,7 +5,7 @@ import { BodyResponse } from '../utils'
// @Catch() 装饰器绑定所需的元数据到异常过滤器上。它告诉 Nest这个特定的过滤器正在寻找
@Catch()
export class ExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
catch(exception: any, host: ArgumentsHost) {
// 获取上下文
const ctx = host.switchToHttp()
// 获取响应体
......@@ -13,11 +13,10 @@ export class ExceptionsFilter implements ExceptionFilter {
const request = ctx.getRequest<Request>()
Logger.error(exception)
console.log(exception)
// 获取状态码,判断是HTTP异常还是服务器异常
const statusCode = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR
const msg = exception instanceof HttpException? exception.message : '服务器异常'
const msg = exception.meta?.cause || exception.message || '服务器异常'
// 自定义异常返回体
response.status(statusCode).json(BodyResponse(null, msg, statusCode,exception, request.url))
response.status(statusCode).json(BodyResponse(null, msg, statusCode, exception, request.url))
}
}
......@@ -8,8 +8,8 @@ export const getCurrentTimestamp = (): number => {
/**
* @description: 统一返回体
*/
export const BodyResponse: CommonTypes.TBodyResponse = (result, msg, code,error, url) => {
if(msg instanceof Array){
export const BodyResponse: CommonTypes.TBodyResponse = (result, msg, code, error, url) => {
if (msg instanceof Array) {
msg = msg.join(';')
}
const { total, data } = result || {}
......@@ -18,8 +18,8 @@ export const BodyResponse: CommonTypes.TBodyResponse = (result, msg, code,error,
data,
total,
error,
'timestamp': getCurrentTimestamp(),
'msg': msg || RESPONSE_MSG.SUCCESS,
'code': code || RESPONSE_CODE.SUCCESS
timestamp: getCurrentTimestamp(),
msg: data?.msg || msg || RESPONSE_MSG.SUCCESS,
code: data?.code || code || RESPONSE_CODE.SUCCESS
}
}
......@@ -75,14 +75,14 @@ export class AddDeviceInfoDto {
description: '创建时间',
default: ''
})
created_at: Date | string
created_at: Date
@ApiProperty({
type: Date,
description: '更新时间',
default: ''
})
updated_at: Date | string
updated_at: Date
@IsMobilePhone('zh-CN',{},{ message: '手机号格式不正确'})
@IsOptional()
......
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, } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger'
import { Transform } from 'class-transformer'
export class FileDto {
@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
}
......@@ -2,3 +2,5 @@ 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
......@@ -4,16 +4,23 @@ import { TransformInterceptor } from '../../common/interceptors'
import { WsGateway } from '../ws/ws.gateway'
import { BroadcastDto } from '../../dto'
import { ValidationPipe } from '../../common/pipes'
@Controller('broadcast')
@UseInterceptors(TransformInterceptor)
@UsePipes(new ValidationPipe()) // 使用管道验证
export class BroadcastController {
constructor(
private readonly broadcastService: BroadcastService,
private readonly wsGateway: WsGateway
) {}
/**
* 构造函数,注入BroadcastService和WsGateway
* @param broadcastService - BroadcastService实例
* @param wsGateway - WsGateway实例
*/
constructor(private readonly wsGateway: WsGateway) {}
//写一个message方法 接收params参数 然后调用broadcastService的message方法
/**
* 发送广播消息
* @param params - 包含广播消息的对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@Post('/message')
async message(@Body() params: BroadcastDto): Promise<any> {
return this.wsGateway.send(params)
......
......@@ -45,7 +45,7 @@ export class ConfigService {
return resBody
}
async addConfig(config: ConfigTypes.LogConfigAdd):Promise<CommonTypes.IResData<boolean>> {
async addConfig(config: ConfigTypes.LogConfigAdd): Promise<CommonTypes.IResData<boolean>> {
const { user_fields, ...data } = config
let config_id: number = 0
await this.prisma.$transaction(async prisma => {
......@@ -61,12 +61,10 @@ export class ConfigService {
const { id } = await prisma.log_config.create({ data, select: { id: true } })
config_id = id
}
const relations: ConfigTypes.LogConfigResult[] = user_fields.map((ufid: number) => {
const relations: RelationsTypes.LogConfigUserFieldsRel[] = user_fields.map((ufid: number) => {
return {
config_id,
user_field_id: ufid,
created_at: date,
updated_at: date
user_field_id: ufid
}
})
await prisma.log_config_userfield_relation.createMany({ data: relations, skipDuplicates: true })
......
import { Controller, Get, Post, Body, UseInterceptors, Query, UsePipes } from '@nestjs/common'
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 } from '../../dto'
import { AddDeviceDto, AddDeviceInfoDto, DeviceStatusDto } from '../../dto'
import { PagesPipe, ValidationPipe } from '../../common/pipes'
import { OnEvent } from '@nestjs/event-emitter'
import { WsConnEvents } from '../../common/enums'
import { OnEvent, EventEmitter2 } from '@nestjs/event-emitter'
import { WsAccess, WsConnEvents } from '../../common/enums'
@Controller('device')
@UseInterceptors(TransformInterceptor)
// @UsePipes(new ValidationPipe({transform: true}))
@UsePipes(new ValidationPipe()) // 使用管道验证
export class DeviceController {
constructor(private readonly deviceService: DeviceService) {}
/**
* 构造函数,注入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())
findAll(@Query() params: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData> {
return this.deviceService.findAll(params)
}
/**
* 添加设备的方法
* 该方法接收一个包含设备信息的DTO对象,并返回添加后的设备信息
* @param param - 包含设备信息的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@Post('/add')
addDevice(@Body() param: AddDeviceDto) {
addDevice(@Body() param: AddDeviceDto): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
// console.log(param)
return this.deviceService.addDevice(param)
}
/**
* 添加设备信息的方法
* 该方法接收一个包含设备信息的DTO对象,并返回添加后的设备信息
* @param param - 包含设备信息的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@Post('/addInfo')
addDeviceInfo(@Body() param: AddDeviceInfoDto) {
addDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
// console.log(param)
return this.deviceService.addDeviceInfo(param)
}
@OnEvent(WsConnEvents.Connection)
/**
* 更新设备信息的方法
* 该方法接收一个包含设备信息的DTO对象,并返回更新后的设备信息
* @param param - 包含设备信息的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@Post('/updateInfo')
updateDeviceInfo(param: AddDeviceInfoDto) {
updateDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
return this.deviceService.updateDeviceInfo(param)
}
/**
* 更新设备状态的方法
* 该方法接收一个包含设备状态的DTO对象,并返回更新后的设备状态
* @param param - 包含设备状态的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@OnEvent(WsConnEvents.OnConnected)
@Post('/upsertStatus')
async upsertDeviceStatus(@Body() param: DeviceStatusDto): Promise<void | CommonTypes.IResData<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(WsConnEvents.OnConnectError, out)
})
}
}
......@@ -3,17 +3,14 @@ import { Inject, Injectable, HttpException, HttpStatus } from '@nestjs/common'
// import { InjectRepository } from '@nestjs/typeorm';
// import { Device as DeviceEntity } from '../entities/Device'
import { PrismaService } from 'nestjs-prisma'
import { AddDeviceInfoDto } from '../../dto/device.dto'
import { WsConnEvents, WsStatus } from '../../common/enums'
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'
import { RESPONSE_CODE, WsConnEvents, WsStatus } from '../../common/enums'
@Injectable()
export class DeviceService {
constructor(
@Inject(PrismaService)
private readonly prisma: PrismaService // private connection: Connection,
) {
}
) {}
async findAll({ user, mobile, sn, skip, take }: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData<DeviceTypes.IDeviceInfo[]>> {
const where = {
......@@ -39,7 +36,6 @@ export class DeviceService {
device_info: {
select: {
user: true,
status: true,
mobile: true,
merchant_name: true,
log_config: {
......@@ -55,6 +51,9 @@ export class DeviceService {
}
}
}
},
device_status: {
select: { status: true }
}
}
}
......@@ -69,7 +68,7 @@ export class DeviceService {
sn: cur.sn,
user: cur.device_info?.user,
mobile: cur.device_info?.mobile,
status: cur.device_info?.status,
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)
......@@ -80,25 +79,47 @@ export class DeviceService {
return resBody
}
async addDevice(device: Omit<DeviceTypes.IDevice,'id'|'create_time'>) {
return await this.prisma.device.create({ data: device })
async addDevice(device: Omit<DeviceTypes.IDevice, 'id' | 'create_time'>): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
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 { data: { code: RESPONSE_CODE.SUCCESS, msg: '添加设备成功' } }
}
async addDeviceInfo(deviceInfo: AddDeviceInfoDto) {
async addDeviceInfo(deviceInfo: DeviceTypes.IDeviceInfoInput): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
deviceInfo.created_at = new Date()
deviceInfo.updated_at = new Date()
deviceInfo.status = WsStatus.Offline
return await this.prisma.device_info.create({ data: deviceInfo })
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 { data: { code: RESPONSE_CODE.SUCCESS, msg: '添加设备信息成功' } }
}
async updateDeviceInfo(deviceInfo: AddDeviceInfoDto) {
const {device_id,...data} = deviceInfo
async updateDeviceInfo(deviceInfo: DeviceTypes.IDeviceInfoInput): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
const { device_id, ...data } = deviceInfo
data.updated_at = new Date()
return await this.prisma.device_info.update({
await this.prisma.device_info.update({
where: {
device_id: deviceInfo.device_id
},
data,
data
})
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '设备信息更新成功' } }
}
async upsertDeviceStatus(data: DeviceStatus.IDeviceStatus): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
await this.prisma.device_status.upsert({
where: {
device_id: data.device_id
},
create: data,
update: {
status: data.status
}
})
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '设备状态更新成功' } }
}
}
import { Controller, Post, UploadedFile, UseInterceptors, Get, Res, Req } from '@nestjs/common'
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 'src/common/enums'
import { FileDto } from '../../dto'
@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')
@UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain'), limits: { fileSize: 1024 * 1024 * 100 } })
upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request) {
console.log(req.body.deviceId)
this.fileService.upload(file)
return file
upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request): FileTypes.IFile<DocTypes> {
const { fieldname, encoding, destination, stream, buffer, ...o } = file
const bodyData: Pick<FileTypes.IFile<DocTypes>, 'device_id' | 'type'> = { device_id: Number(req.body.deviceId), type: req.body.type }
const fi: FileTypes.IFile<DocTypes> = Object.assign({ created_at: new Date() }, bodyData, o)
this.fileService.save(fi)
return fi
}
/**
* 删除文件的方法
* 该方法接收一个文件ID,并将文件从数据库中删除
* @param id - 要删除的文件ID
* @returns 返回删除结果
*/
@Get('delete')
async remove(@Query() { id }: FileDto): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
return await this.fileService.remove(+id)
}
/**
* 导出所有文件的方法
* 该方法将所有文件打包成一个tar文件并返回给客户端
* @param res - 包含响应信息的Response对象
* @returns 返回打包后的tar文件
*/
@Get('export')
async downloadAll(@Res() res: Response) {
const { filename, tarStream } = await this.fileService.downloadAll()
......
......@@ -3,6 +3,7 @@ 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: [
......@@ -12,6 +13,6 @@ import { FileService } from './file.service';
}),
],
controllers: [FileController],
providers: [FileService],
providers: [FileService,PrismaService],
})
export class FileModule {}
import { Injectable } from '@nestjs/common';
import { tar } from 'compressing';
import { ConfigService } from 'nestjs-config';
import * as fs from 'fs';
import * as path from 'path';
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'
@Injectable()
export class FileService {
constructor(private readonly configService: ConfigService) {}
/**
* 文件服务的构造函数。
*
* @param configService - 配置服务的实例,用于获取配置信息。
* @param prisma - PrismaService的实例,用于数据库操作。
*/
constructor(
private readonly configService: ConfigService,
@Inject(PrismaService)
private readonly prisma: PrismaService // private connection: Connection,
) {}
upload(file) {
console.log(file);
/**
* 保存文件到数据库的方法。
*
* @param file - 要保存的文件对象,包含文件名、路径、创建时间等信息。
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/
async save(file: FileTypes.IFile<DocTypes>): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
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)
return await prisma.file.update({ where: { id }, data: { filename, path, created_at } })
} else {
return await prisma.file.create({ data: file })
}
})
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '文件保存成功' } }
}
/**
* 从数据库中移除文件。
*
* @param id - 要移除的文件的唯一标识符。
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/
async remove(id: number): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
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 { data: { code: RESPONSE_CODE.SUCCESS, msg: '删除成功' } }
}
async downloadAll() {
const uploadDir = this.configService.get('file').root;
const tarStream = new tar.Stream();
await tarStream.addEntry(uploadDir);
return { filename: 'hello-world.tar', tarStream };
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);
});
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)
})
}
}
import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone,IsOptional } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger'
export class WsDto {
@ApiProperty({
type: String,
description: '设备SN',
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: String,
description: '创建时间',
default: ''
})
created_at: string
@ApiProperty({
type: String,
description: '更新时间',
default: ''
})
updated_at: string
@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: {}
}
......@@ -91,9 +91,10 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
}
/**
* 用户断开
* 用户断开连接
* @param client client
*/
handleDisconnect(client: Socket) {
// 移除数据 socketID
this.wsService.logout(client)
......@@ -110,7 +111,11 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
this.wsService.resetClients()
}
public send(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>,WsMessageType>): Promise<any> {
/**
* 发送消息
* @param payload
*/
public send(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>, WsMessageType>): Promise<any> {
if (payload.event === WsMessageType.Private) {
return this.wsService.sendPrivateMessage(payload)
} else {
......
......@@ -5,8 +5,8 @@ import { Logger } from '@nestjs/common'
// import { validateToken } from '@/utils/helper';
// import { Message } from '@/entities/message.entity';
// import { User } from '@/entities/user.entity';
import { WsAccess, WsConnEvents, WsMessageType, WsStatus } from '../../common/enums'
import { EventEmitter2 } from '@nestjs/event-emitter'
import { RESPONSE_CODE, WsAccess, WsConnEvents, WsMessageType, WsStatus } from '../../common/enums'
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'
@Injectable()
export class WsService {
......@@ -26,42 +26,59 @@ export class WsService {
* @returns
*/
login(client: Socket, token: string, deviceId: number): WsTypes.IWsResponse<WsStatus, WsAccess> {
const clients: Map<string, Socket> = this.server.sockets.sockets
const clientIsOnline: Socket = clients.get(this.clientIds.get(deviceId))
const clientIsOnline: Socket = this.findClientByDeviceId(deviceId)
// 处理同一工号在多处登录
clientIsOnline?.emit(WsMessageType.System, `设备 ${deviceId} 已在别处上线, 此客户端下线处理`)
clientIsOnline?.disconnect()
// 保存工号
this.clientIds.set(deviceId, client.id)
Logger.log(`${deviceId} connected, onLine: ${clients.size}`)
this.server.emit(WsMessageType.System, `${deviceId} connected, onLine: ${clients.size}`)
Logger.log(`${deviceId} connected, onLine: ${this.allClients.size}`)
this.server.emit(WsMessageType.System, `${deviceId} connected, onLine: ${this.allClients.size}`)
const resData: WsTypes.IWsResponse<WsStatus, WsAccess> = {
device_id: deviceId,
status: WsStatus.Online,
message: WsAccess.IsOnline
}
this.emit(resData)
this.emit(WsConnEvents.OnConnected, resData)
return resData
}
private findClientByDeviceId(deviceId: number): Socket {
return this.allClients?.get(this.clientIds.get(deviceId))
}
private get allClients(): Map<string, Socket> {
return this.server?.sockets?.sockets
}
/**
* 登出
* @param client client
*/
async logout({ id }: Socket) {
async logout({ id }: Socket): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
// 移除在线 client
for (let [deviceId, clientId] of this.clientIds) {
if (clientId === id) {
this.clientIds.delete(deviceId)
Logger.log(`${deviceId} disconnected, onLine: ${this.clientIds.size}`)
this.emit({ device_id: deviceId, status: WsStatus.Offline, message: WsAccess.IsOffline })
this.emit(WsConnEvents.OnConnected, { status: WsStatus.Offline, message: WsAccess.IsOffline, device_id: deviceId })
break
}
}
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '登出成功' } }
}
@OnEvent(WsConnEvents.OnConnectError)
async onConnError(out: WsTypes.WsConnError): Promise<void> {
const { device_id, message } = out
const client: Socket = this.findClientByDeviceId(device_id)
if (client) {
client.emit(WsMessageType.Private, message)
client.disconnect()
}
}
private emit(data: WsTypes.IWsResponse<WsStatus, WsAccess>) {
private emit(event: WsConnEvents, data: WsTypes.IWsResponse<WsStatus, WsAccess>) {
const { message, ...rest } = data
this.eventEmitter.emit(WsConnEvents.Connection, rest)
this.eventEmitter.emit(event, rest)
}
/**
......@@ -76,13 +93,14 @@ export class WsService {
* @param messagePath 发布地址
* @param response 响应数据
*/
async sendPublicMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>) {
async sendPublicMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
console.log('websocket send', payload)
const res = this.server?.emit(WsMessageType.System, payload.data)
if (!res) {
Logger.log('websocket send error', payload)
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败`, error: 'send error' }, HttpStatus.BAD_REQUEST)
}
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '发送成功' } }
}
/**
......@@ -91,14 +109,15 @@ export class WsService {
* @param response 响应数据
* @param deviceId 接收者设备号
*/
async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>) {
async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> {
console.log('websocket send', payload)
if (!payload.device_id) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: '请求参数employeeId 必传', error: 'deviceId is required' }, HttpStatus.BAD_REQUEST)
const client = this.server.sockets.sockets.get(this.clientIds.get(payload.device_id))
const client = this.allClients?.get(this.clientIds.get(payload.device_id))
const res = client?.emit(WsMessageType.Private, payload.data)
if (!res) {
Logger.log('websocket send error', payload)
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败,客户端:(设备号->${payload.device_id}) 不在线`, error: 'send error' }, HttpStatus.BAD_REQUEST)
}
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '发送成功' } }
}
}
......@@ -10,13 +10,13 @@ export class TasksService {
this.logger.debug('Called when the second is 45');
}
@Interval(10000)
handleInterval() {
this.logger.debug('Called every 10 seconds');
}
// @Interval(10000)
// handleInterval() {
// this.logger.debug('Called every 10 seconds');
// }
@Timeout(5000)
handleTimeout() {
this.logger.debug('Called once after 5 seconds');
}
// @Timeout(5000)
// handleTimeout() {
// this.logger.debug('Called once after 5 seconds');
// }
}
/**
* 公共命名空间声明
*/
declare module CommonTypes {
declare namespace CommonTypes {
/**
* 定义一个基本的响应对象接口
*/
......
......@@ -19,10 +19,9 @@ declare module ConfigTypes {
updated_at: Date | string
user_fields: DeviceTypes.ILogUserFields[]
}
type LogConfigQuery = Pick<Partial<ILogConfig>,'device_id'> & CommonTypes.IQueryBase
type LogConfigAdd = Omit<Partial<ILogConfig>,'id'|'user_fields'> & {user_fields: number[]}
type LogConfigQuery = Pick<Partial<ILogConfig>, 'device_id'> & CommonTypes.IQueryBase
type LogConfigAdd = Omit<Partial<ILogConfig>, 'id' | 'user_fields'> & { user_fields: number[] }
type LogConfigResult = Partial<ILogConfig>
type LogConfigResponse = Omit<LogConfigResult,'user_fields'> & {user_fields: string[]}
type LogConfigUpdate = CommonTypes.Optional<ILogConfig,'device_id'>
type LogConfigResponse = Omit<LogConfigResult, 'user_fields'> & { user_fields: string[] }
type LogConfigUpdate = CommonTypes.Optional<ILogConfig, 'device_id'>
}
......@@ -27,10 +27,6 @@ declare module DeviceTypes {
*/
merchant_name?: string
/**
* 状态
*/
status?: number
/**
* 日志保存天数
*/
log_saved_days?: number
......@@ -38,7 +34,7 @@ declare module DeviceTypes {
/**
* 设备信息接口
*/
interface IDeviceInfo extends IDeviceInfoBase, IDevice {
interface IDeviceInfo extends IDeviceInfoBase, IDevice, DeviceStatus.Status {
/**
* 日志用户字段
*/
......@@ -65,11 +61,11 @@ declare module DeviceTypes {
last_log_upload_time?: string
last_log_remove_time?: string
device_id: number
created_at?: number
updated_at?: number
created_at?: Date
updated_at?: Date
}
type UpdateDeviceInfo = CommonTypes.Optional<IDeviceInfoInput,"device_id">
type UpdateDeviceInfo = CommonTypes.Optional<IDeviceInfoInput, 'device_id'>
/**
* 表示设备结果的接口
*/
......@@ -127,8 +123,9 @@ declare module DeviceTypes {
* 与设备关联的日志配置信息
*/
log_config: Partial<ConfigTypes.ILogConfig>
}
device_status: DeviceStatus.Status
}
/**
* 表示日志配置的接口
*/
......@@ -150,20 +147,6 @@ declare module DeviceTypes {
/**
* 日志用户字段的详细信息
*/
log_user_field?: ILogUserField
}
/**
* 表示日志用户字段的详细信息的接口
*/
interface ILogUserField {
/**
* 日志用户字段的唯一标识符
*/
id?: number
/**
* 日志用户字段的名称
*/
name: string
log_user_field?: CommonTypes.Optional<Partial<UserFieldTypes.ILogUserFields>, 'name'>
}
}
declare module DeviceStatus {
interface IDeviceStatus {
device_id: number
status: number
}
type Status = Omit<IDeviceStatus,'device_id'>
}
declare namespace FileTypes {
interface IFile<T> {
originalname: string
mimetype: string
filename: string
path: string
size: number,
device_id: number,
created_at: Date,
type: T
}
}
declare module RelationsTypes {
interface IRelation {
id: number
config_id: number
user_field_id: number
}
type LogConfigUserFieldsRel = Omit<IRelation, 'id'>
}
declare module UserFieldTypes {
interface ILogUserFields {
id: number
name: string
}
}
......@@ -6,7 +6,7 @@ declare module WsTypes {
}
type WsMsgType = 'private' | 'system'
type MessageBody<U,T = WsMsgType> = {
type MessageBody<U, T = WsMsgType> = {
event: T
data: U
} & (T extends 'private' ? IPrivateData : Partial<IPrivateData>)
......@@ -32,4 +32,6 @@ declare module WsTypes {
}
type WsMessageData<T> = MessageData<T>
type WsConnError = IPrivateData & { message: string }
}
# http://localhost:3000/device?pageIndex=2&pageSize=5
# http://localhost:3000/device?pageIndex=1&pageSize=5
# POST http://localhost:3000/device/add HTTP/1.1
# content-type: application/json
# {
# "sn":"sn1111211212122"
# "sn":"sn11112112121235"
# }
# POST http://localhost:3000/device/addInfo HTTP/1.1
# content-type: application/json
# {
# "device_id":13,
# "device_id":16,
# "mobile":"13800138000",
# "user":"老六",
# "merchant_name":"老登"
# }
# POST http://localhost:3000/device/updateInfo HTTP/1.1
# content-type: application/json
# {
# "device_id":5,
# "mobile":"13800138000",
# "user":"王老七",
# "merchant_name":"老点"
# "merchant_name":"老登"
# }
# http://localhost:3000/sse/event
......@@ -26,7 +36,7 @@ POST http://localhost:3000/broadcast/message HTTP/1.1
{
"event":"private",
"device_id":12,
"device_id":1,
"data":{
"order":"logs",
"payload":{
......@@ -34,6 +44,9 @@ POST http://localhost:3000/broadcast/message HTTP/1.1
}
}
}
# http://localhost:3000/file/delete?id=16
# http://localhost:3000/config?device_id=2
# POST http://localhost:3000/config/add HTTP/1.1
......
......@@ -850,7 +850,7 @@
"@prisma/client@^5.19.1":
version "5.19.1"
resolved "https://registry.npmjs.org/@prisma/client/-/client-5.19.1.tgz#d73f2b17b08628b6450c1c2dd20924d7a993aadf"
resolved "https://registry.npmmirror.com/@prisma/client/-/client-5.19.1.tgz#d73f2b17b08628b6450c1c2dd20924d7a993aadf"
integrity sha512-x30GFguInsgt+4z5I4WbkZP2CGpotJMUXy+Gl/aaUjHn2o1DnLYNTA+q9XdYmAQZM8fIIkvUiA2NpgosM3fneg==
"@prisma/debug@5.0.0":
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!