Commit 5dc523d9 by yixinjj

优化一些功能和类型定义

1 parent 80f75154
......@@ -44,7 +44,7 @@
"@nestjs/platform-socket.io": "^10.4.1",
"@nestjs/platform-ws": "^10.4.1",
"@nestjs/schedule": "^0.3.1",
"@nestjs/swagger": "4.5.5",
"@nestjs/swagger": "^7.4.2",
"@nestjs/typeorm": "^7.0.0",
"@nestjs/websockets": "^10.4.1",
"@prisma/client": "^5.19.1",
......@@ -68,7 +68,7 @@
"rxjs": "^7.8.1",
"socket.io": "4.7.4",
"swagger-ui-express": "^5.0.1",
"typeorm": "^0.2.25"
"typeorm": "0.2.25"
},
"devDependencies": {
"@nestjs/cli": "^7.0.0",
......@@ -76,6 +76,7 @@
"@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",
......
......@@ -59,3 +59,8 @@ export enum DocTypes {
Video = 'video',
Other = 'other'
}
export enum Command{
GetLog='getLog',
GetStorage='getStorage',
Message='message'
}
......@@ -14,9 +14,9 @@ export class ExceptionsFilter implements ExceptionFilter {
Logger.error(exception)
console.log(exception)
// 获取状态码,判断是HTTP异常还是服务器异常
const statusCode = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR
const msg = exception.meta?.cause || exception.message || '服务器异常'
const code = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR
const message = exception.meta?.cause || exception.message || '服务器异常'
// 自定义异常返回体
response.status(statusCode).json(BodyResponse(null, msg, statusCode, exception, request.url))
response.status(code).json(BodyResponse({ message, code, error: exception, url: request.url }))
}
}
......@@ -21,6 +21,6 @@ export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
// message,
// });
// 自定义异常返回体
response.status(status).json(BodyResponse(null, message, status,exception, request.url))
response.status(status).json(BodyResponse({message, code:status,error:exception, url:request.url}))
}
}
......@@ -4,7 +4,7 @@ import { catchError } from 'rxjs/operators'
@Injectable()
export class ErrorsInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
intercept(context: ExecutionContext, next: CallHandler): Observable<CommonTypes.IResData> {
return next.handle().pipe(catchError(err => throwError(new HttpException('New message', HttpStatus.BAD_GATEWAY))))
}
}
......@@ -8,18 +8,9 @@ export const getCurrentTimestamp = (): number => {
/**
* @description: 统一返回体
*/
export const BodyResponse: CommonTypes.TBodyResponse = (result, message, code, error, url) => {
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 { total, data } = result || {}
return {
url,
data,
total,
error,
timestamp: getCurrentTimestamp(),
message: data?.message || message || RESPONSE_MSG.SUCCESS,
code: data?.code || code || RESPONSE_CODE.SUCCESS
}
return { url, data, total, error, message, code, timestamp: getCurrentTimestamp() }
}
import { ApiProperty } from '@nestjs/swagger'
import { WsMessageType } from '../common/enums'
import { IsDefined, IsNotEmpty, IsNumber, IsString, ValidateIf, ValidateNested } from 'class-validator'
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: '命令类型'
description: '指令类型'
})
@IsString({ message: '命令为必填参数' })
@IsNotEmpty({ message: '命令不能为空' })
readonly order: string
@IsEnum(Command, { message: '指令类型错误' })
@IsString({ message: '指令为必填参数' })
@IsNotEmpty({ message: '指令不能为空' })
readonly command: Command
@ApiProperty({
description: '下发的参数',
description: '下发的参数'
})
readonly payload: any
readonly payload: unknown
}
export class BroadcastDto {
@ApiProperty({
type: WsMessageType,
type: String,
description: '事件类型: private-私有消息,system-系统消息',
default: WsMessageType.Private
})
@IsEnum(WsMessageType, { message: '事件类型错误' })
@IsNotEmpty({ message: '事件类型不能为空' })
readonly event: WsMessageType
@ValidateIf(o => o.event === WsMessageType.Private)
@IsDefined({ message: '发送私有消息时,device_id是必填的' })
@IsNumber({},{ message: 'device_id必须是数字'})
@IsNumber({}, { message: 'device_id必须是数字' })
@ApiProperty({
type: Number,
description: '设备号,私发信息必填',
default: ''
})
readonly device_id: number
......@@ -41,6 +41,5 @@ export class BroadcastDto {
@ApiProperty({ description: '要发送的数据' })
@ValidateNested()
@Type(() => DataDto)
readonly data: DataDto
readonly data: any
}
......@@ -11,8 +11,6 @@ import { ApiTags } from '@nestjs/swagger'
@UsePipes(new ValidationPipe()) // 使用管道验证
export class BroadcastController {
/**
* 构造函数,注入BroadcastService和WsGateway
* @param broadcastService - BroadcastService实例
* @param wsGateway - WsGateway实例
*/
constructor(private readonly wsGateway: WsGateway) {}
......@@ -22,8 +20,8 @@ export class BroadcastController {
* @param params - 包含广播消息的对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@Post('/message')
async message(@Body() params: BroadcastDto): Promise<any> {
@Post('/cmd')
async message(@Body() params: BroadcastDto): Promise<CommonTypes.IResData> {
return this.wsGateway.send(params)
}
}
......@@ -17,7 +17,7 @@ export class ConfigController {
return this.configService.findAll(params)
}
@Post('/add')
addConfig(@Body() param: LogConfigDto): Promise<CommonTypes.IResData<boolean>> {
addConfig(@Body() param: LogConfigDto): Promise<CommonTypes.IResData> {
return this.configService.addConfig(param)
}
}
import { Injectable, Inject } from '@nestjs/common'
import { PrismaService } from 'nestjs-prisma'
import { LogConfigDto } from 'src/dto/config.dto'
import { RESPONSE_CODE } from '../../common/enums'
@Injectable()
export class ConfigService {
constructor(
......@@ -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> {
const { user_fields, ...data } = config
let config_id: number = 0
await this.prisma.$transaction(async prisma => {
......@@ -69,6 +69,6 @@ export class ConfigService {
})
await prisma.log_config_userfield_relation.createMany({ data: relations, skipDuplicates: true })
})
return { data: true }
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
}
}
......@@ -31,7 +31,7 @@ export class DeviceService implements OnModuleInit {
}
}
}
const result: Omit<DeviceTypes.IDeviceResult,'id'>[] = await this.prisma.device.findMany({
const result: Omit<DeviceTypes.IDeviceResult, 'id'>[] = await this.prisma.device.findMany({
skip,
take,
select: {
......@@ -63,7 +63,7 @@ export class DeviceService implements OnModuleInit {
},
where
})
const total:number = await this.prisma.device.count({
const total: number = await this.prisma.device.count({
where
})
const data: DeviceTypes.IDeviceInfo[] = result.reduce((pre: DeviceTypes.IDeviceInfo[], cur: DeviceTypes.IDeviceResult) => {
......@@ -82,7 +82,7 @@ export class DeviceService implements OnModuleInit {
return resBody
}
async addDevice(device: Omit<DeviceTypes.IDevice, 'id' | 'create_time'>): Promise<CommonTypes.IResponseBase> {
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})
......@@ -92,7 +92,7 @@ export class DeviceService implements OnModuleInit {
return { code: RESPONSE_CODE.SUCCESS, message: '添加设备成功' }
}
async addDeviceInfo(deviceInfo: Omit<DeviceTypes.IDeviceInfoInput,'sn'>): Promise<CommonTypes.IResponseBase> {
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 => {
......@@ -102,7 +102,7 @@ export class DeviceService implements OnModuleInit {
return { code: RESPONSE_CODE.SUCCESS, message: '添加设备信息成功' }
}
async updateDeviceInfo(deviceInfo: Omit<DeviceTypes.IDeviceInfoInput,'sn'>): Promise<CommonTypes.IResponseBase> {
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({
......@@ -113,7 +113,7 @@ export class DeviceService implements OnModuleInit {
})
return { code: RESPONSE_CODE.SUCCESS, message: '设备信息更新成功' }
}
async upsertDeviceStatus(data: DeviceStatus.IDeviceStatus): Promise<CommonTypes.IResponseBase> {
async upsertDeviceStatus(data: DeviceStatus.IDeviceStatus): Promise<CommonTypes.IResData> {
await this.prisma.device_status.upsert({
where: {
device_id: data.device_id
......@@ -125,7 +125,7 @@ export class DeviceService implements OnModuleInit {
})
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
}
async resetAllDeviceStatus(): Promise<CommonTypes.IResponseBase> {
async resetAllDeviceStatus(): Promise<CommonTypes.IResData> {
Logger.debug('===重置所有设备状态===')
await this.prisma.device_status.updateMany({
data: {
......
......@@ -42,7 +42,7 @@ export class FileController {
* @returns 返回删除结果
*/
@Get('delete')
async remove(@Query() { id }: FileDto): Promise<CommonTypes.IResponseBase> {
async remove(@Query() { id }: FileDto): Promise<CommonTypes.IResData> {
return await this.fileService.remove(+id)
}
......
......@@ -26,7 +26,7 @@ export class FileService {
* @param file - 要保存的文件对象,包含文件名、路径、创建时间等信息。
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/
async save(file: FileTypes.IFile<DocTypes>): Promise<CommonTypes.IResponseBase> {
async save(file: FileTypes.IFile<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 } })) || {}
......@@ -46,7 +46,7 @@ export class FileService {
* @param id - 要移除的文件的唯一标识符。
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/
async remove(id: number): Promise<CommonTypes.IResponseBase> {
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 } })
......
......@@ -4,7 +4,7 @@ import { map } from 'rxjs/operators'
import { Server, Socket } from 'socket.io'
import { WsService } from './ws.service'
import { Logger, Module, UseInterceptors } from '@nestjs/common'
import { WsMessageType, WsStatus, WsAccess } from '../../common/enums'
import { WsMessageType, WsStatus, WsAccess, Command } from '../../common/enums'
import { TransformInterceptor } from '../../common/interceptors'
/**
......@@ -38,7 +38,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* @param data - 传入的数据
* @returns 包含事件和数据的 Observable 对象
*/
@SubscribeMessage(WsMessageType.Private)
// @SubscribeMessage(WsMessageType.Private)''
subPrivate(@MessageBody() data: any): Observable<WsResponse<string>> {
return from<string>('hello').pipe(map(item => ({ event: 'events', data: item })))
}
......@@ -104,7 +104,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* @param server
*/
afterInit(server: Server) {
Logger.log('websocket init... port: ' + process.env.SOCKET_PORT)
Logger.debug('Websocket init... Port: ' + process.env.SOCKET_PORT)
this.wsService.server = server
// 重置 socketIds
this.wsService.resetClients()
......@@ -114,11 +114,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* 发送消息
* @param payload
*/
public send(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>, WsMessageType>): Promise<any> {
if (payload.event === WsMessageType.Private) {
return this.wsService.sendPrivateMessage(payload)
} else {
return this.wsService.sendPublicMessage(payload)
}
public send(payload: WsTypes.MessageBody<WsTypes.WsMessageData<Command>, WsMessageType>): Promise<CommonTypes.IResData> {
return this.wsService[{ [WsMessageType.Private]: 'sendPrivateMessage', [WsMessageType.System]: 'sendPublicMessage' }[payload.event]](payload)
}
}
......@@ -102,7 +102,7 @@ export class WsService {
* @param messagePath 发布地址
* @param response 响应数据
*/
async sendPublicMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResponseBase> {
async sendPublicMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResData> {
const res = this.server?.emit(WsMessageType.System, payload.data)
if (!res) {
Logger.log('Websocket Send Private Error->', payload)
......@@ -118,7 +118,7 @@ export class WsService {
* @param response 响应数据
* @param deviceId 接收者设备号
*/
async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResponseBase> {
async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResData> {
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.allClients?.get(this.clientIds.get(payload.device_id))
......
......@@ -51,7 +51,7 @@ declare namespace CommonTypes {
/**
* 响应数据接口,继承自分页对象接口,包含业务数据
*/
interface IResData<T = any> extends IPagenation {
interface IResData<T = any> extends IPagenation,IResponseBase {
/**
* 业务数据
*/
......@@ -84,13 +84,10 @@ declare namespace CommonTypes {
/**
* 定义一个响应体生成函数类型
*
* @param result - 响应数据
* @param msg - 消息
* @param code - 状态码
* @param url - 路径
* @returns 返回给前端的响应体
* @param data -接口响应的数据
* @returns 处理后返回给前端的响应体
*/
type TBodyResponse = (result: IResData, message?: string | string[], code?: number, error?: any, url?: string) => IResponse<IResData<any>>
type TBodyResponse = (data: IResData) => IResponse<IResData<unknown>>
type Optional<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>
type PartialOne<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
......
......@@ -21,11 +21,13 @@ declare namespace WsTypes {
}
type LoginValidate<T> = { isValidate: boolean; errMsg: T }
type MessageData<T, U = CommonTypes.TObj> = {
order: T | string
command: T | string
payload: U
}
type WsMessageData<T> = MessageData<T>
type WsConnError = CommonTypes.IDeviceId & { message: string }
}
......@@ -31,14 +31,14 @@
POST http://localhost:3000/broadcast/message HTTP/1.1
POST http://localhost:3000/broadcast/cmd HTTP/1.1
content-type: application/json
{
"event":"private",
"device_id":1,
"data":{
"order":"logs",
"command":"getStorage",
"payload":{
"message":"log message"
}
......
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!