Commit 36572713 by yixinjj

添加一些指令处理

1 parent dd9322cc
...@@ -27,14 +27,9 @@ import { FieldsModule } from './modules/fields/fields.module' ...@@ -27,14 +27,9 @@ import { FieldsModule } from './modules/fields/fields.module'
import { WinstonModule } from 'nest-winston' import { WinstonModule } from 'nest-winston'
import winstonLogger from './initor/winstion.config' import winstonLogger from './initor/winstion.config'
@Module({ @Module({
imports: [ imports: [
ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')), ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')),
// TypeOrmModule.forRootAsync({
// useFactory: (config: ConfigService) => config.get('database'),
// inject: [ConfigService]
// }),
HttpModule.registerAsync({ HttpModule.registerAsync({
useFactory: async (config: ConfigService) => config.get('http'), useFactory: async (config: ConfigService) => config.get('http'),
inject: [ConfigService] inject: [ConfigService]
...@@ -42,8 +37,8 @@ import winstonLogger from './initor/winstion.config' ...@@ -42,8 +37,8 @@ import winstonLogger from './initor/winstion.config'
WinstonModule.forRoot({ WinstonModule.forRoot({
transports: winstonLogger.transports, transports: winstonLogger.transports,
format: winstonLogger.format, format: winstonLogger.format,
defaultMeta: winstonLogger.defaultMeta, // defaultMeta: winstonLogger.defaultMeta,
exitOnError: false, // 防止意外退出 exitOnError: false // 防止意外退出
}), }),
// TODO @nestjs/terminus almost the same // TODO @nestjs/terminus almost the same
// StatusMonitorModule.setUp(statusMonitorConfig), // StatusMonitorModule.setUp(statusMonitorConfig),
...@@ -53,12 +48,6 @@ import winstonLogger from './initor/winstion.config' ...@@ -53,12 +48,6 @@ import winstonLogger from './initor/winstion.config'
// }), // }),
ScheduleModule.forRoot(), ScheduleModule.forRoot(),
EventEmitterModule.forRoot(), EventEmitterModule.forRoot(),
// WinstonModule.forRoot({
// transports: winstonLogger.transports,
// format: winstonLogger.format,
// defaultMeta: winstonLogger.defaultMeta,
// exitOnError: false, // 防止意外退出
// }),
TasksModule, TasksModule,
// AudioModule, // AudioModule,
// AuthModule, // AuthModule,
......
...@@ -64,12 +64,12 @@ export enum Command{ ...@@ -64,12 +64,12 @@ export enum Command{
GetLog='getLog', GetLog='getLog',
GetStorage='getStorage', GetStorage='getStorage',
Message='message', Message='message',
File='file' GetLogList='getLogList',
} RemoveLog='removeLog',
RemoveRecord='removeRecord',
export enum FileCommand{ StopPolling='stopPolling',
GetList='getList', StartPolling='startPolling',
Remove='remove' SetPollingInterval='setPollingInterval'
} }
export enum LogFieldTypes{ export enum LogFieldTypes{
......
import { Injectable, NestMiddleware,Logger, RequestMethod } from '@nestjs/common' import { Injectable, NestMiddleware, Logger, RequestMethod } from '@nestjs/common'
import { NextFunction, Request, Response } from 'express' import { NextFunction, Request, Response } from 'express'
// import { Logger } from '../../logger/log4js'; // import { Logger } from '../../logger/log4js';
@Injectable() @Injectable()
export class LoggerMiddleware implements NestMiddleware { export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction): void { use(req: Request, res: Response, next: NextFunction): void {
const { method, url, originalUrl, baseUrl } = req const { method, url, originalUrl, baseUrl, query, body } = req
const methodUpper = method.toUpperCase() Logger.warn({ method, url, originalUrl, baseUrl, query, body })
let params = req.query
// 对于 POST、PUT 等请求,参数通常在请求体中
if (methodUpper === 'POST' || req.method === 'PUT') {
params = req.body
}
Logger.warn({ method, url, originalUrl, baseUrl, params })
// Logger.warn(`method -> ${method} url -> ${url} params -> ${JSON.stringify(params)}}`)
next() next()
} }
} }
...@@ -14,6 +14,6 @@ export const BodyResponse: CommonTypes.TBodyResponse = ({ message = RESPONSE_MSG ...@@ -14,6 +14,6 @@ export const BodyResponse: CommonTypes.TBodyResponse = ({ message = RESPONSE_MSG
message = message.join(';') message = message.join(';')
} }
const result = { url, data, total, error, message, code, timestamp: getCurrentTimestamp() } const result = { url, data, total, error, message, code, timestamp: getCurrentTimestamp() }
Logger.warn('返回结果:', result) Logger.warn(result)
return result return result
} }
...@@ -13,7 +13,8 @@ export function IsNumberOrNumberString(validationOptions?: ValidationOptions) { ...@@ -13,7 +13,8 @@ export function IsNumberOrNumberString(validationOptions?: ValidationOptions) {
validator: { validator: {
validate(value: any, args: ValidationArguments) { validate(value: any, args: ValidationArguments) {
// 如果值为空(null, undefined, ''),则验证通过 // 如果值为空(null, undefined, ''),则验证通过
if (value === null || value === undefined || value === '') { if(value === '') return false
if (value === null || value === undefined) {
return true return true
} }
......
import { ApiProperty } from '@nestjs/swagger' import { ApiProperty } from '@nestjs/swagger'
import { Command, WsMessageType } from '../common/enums' import { Command, WsMessageType } from '../common/enums'
import { IsDefined, IsEnum, IsNotEmpty, IsNumber, IsString, ValidateIf, ValidateNested } from 'class-validator' import { IsDefined, IsEnum, IsNotEmpty, IsNumber, IsOptional, IsString, registerDecorator, ValidateIf, ValidateNested, ValidationArguments, ValidationOptions } from 'class-validator'
import { Type } from 'class-transformer' import { Type } from 'class-transformer'
import { IsNumberOrNumberString } from './base.dto'
class DataDto { class DataDto {
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: '指令类型' description: '指令类型 '
}) })
@IsEnum(Command, { message: '指令类型错误' }) @IsEnum(Command, { message: '指令类型错误 目前支持 ' })
@IsString({ message: '指令为必填参数' }) @IsString({ message: '指令为必填参数' })
@IsNotEmpty({ message: '指令不能为空' }) @IsNotEmpty({ message: '指令不能为空' })
readonly command: Command readonly command: Command
@ApiProperty({ @ApiProperty({
description: '下发的参数' description: '删除日志传入的天数,非必填,但是如果有值,必须为数字,且当指令为删除日志时,days为必填'
})
@IsOptional()
@IsDefined({ message: '当指令为删除日志时,days为必填' })
@IsNumberOrNumberString()
@ValidateIf(o => o.command === Command.RemoveLog)
readonly days?: number | string
@ApiProperty({
description: '删除接待记录时,为接待记录的ID,且当指令为删除接待记录时,id为必填'
})
@IsOptional()
@ValidateIf(o => o.command === Command.RemoveRecord)
@IsDefined({ message: '当指令为删除接待记录时,id为必填' })
readonly id?: string
@ApiProperty({
description: '设置文件上传轮询间隔时间时,当指令为设置文件上传轮询间隔时间时,interval为必填'
}) })
readonly payload: unknown @ValidateIf(o => o.command === Command.SetPollingInterval)
@IsDefined({ message: '当指令设置文件上传轮询间隔时间,interval为必填 且必须为数字' })
@IsNumberOrNumberString()
readonly interval: number | string
} }
export class BroadcastDto { export class BroadcastDto {
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: '事件类型: private-私有消息,system-系统消息', description: '事件类型: private-私有消息,system-系统消息'
}) })
@IsEnum(WsMessageType, { message: '事件类型错误' }) @IsEnum(WsMessageType, { message: '事件类型错误' })
@IsNotEmpty({ message: '事件类型不能为空' }) @IsNotEmpty({ message: '事件类型不能为空' })
...@@ -32,7 +52,7 @@ export class BroadcastDto { ...@@ -32,7 +52,7 @@ export class BroadcastDto {
@IsDefined({ message: '发送私有消息时,device_id是必填的' }) @IsDefined({ message: '发送私有消息时,device_id是必填的' })
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '设备号,私发信息必填', description: '设备号,私发信息必填'
}) })
readonly device_id: number readonly device_id: number
......
...@@ -5,7 +5,7 @@ import { ExceptionsFilter, HttpExceptionFilter } from '../common/filters' ...@@ -5,7 +5,7 @@ import { ExceptionsFilter, HttpExceptionFilter } from '../common/filters'
import { docBuilder } from './doc' import { docBuilder } from './doc'
import { wsRedisAdapter } from './ws' import { wsRedisAdapter } from './ws'
import { join } from 'path' import { join } from 'path'
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston'
export default class Initializer { export default class Initializer {
static async use(app) { static async use(app) {
app.useGlobalFilters(new ExceptionsFilter()) app.useGlobalFilters(new ExceptionsFilter())
...@@ -16,7 +16,7 @@ export default class Initializer { ...@@ -16,7 +16,7 @@ export default class Initializer {
// app.useGlobalFilters(new ValidateExceptionFilter()) // app.useGlobalFilters(new ValidateExceptionFilter())
// 全局管道 // 全局管道
app.useGlobalPipes(new ValidationPipe()) app.useGlobalPipes(new ValidationPipe())
// app.uselogger(app.get(WINSTON_MODULE_NEST_PROVIDER)) app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER))
// 全局拦截器 // 全局拦截器
// app.useGlobalInterceptors(new LoggingInterceptor()) // app.useGlobalInterceptors(new LoggingInterceptor())
app.useStaticAssets(join(__dirname, '..', '..', process.env.STATIC_PATH)) app.useStaticAssets(join(__dirname, '..', '..', process.env.STATIC_PATH))
......
import * as chalk from 'chalk' // 用于颜色化输出 import * as chalk from 'chalk' // 用于颜色化输出
import { utilities } from 'nest-winston'
import { join } from 'path'
import { createLogger, format, transports } from 'winston' import { createLogger, format, transports } from 'winston'
import winston = require('winston')
import * as DailyRotateFile from 'winston-daily-rotate-file' import * as DailyRotateFile from 'winston-daily-rotate-file'
// 定义日志级别颜色 const formaters = [format.timestamp(), format.errors({ stack: true }), format.splat(), format.json(), winston.format.ms()]
const levelsColors = {
error: 'red',
warn: 'yellow',
info: 'green',
debug: 'blue',
verbose: 'cyan'
}
export default createLogger({ const cfgRotage = {
format: format.combine(format.timestamp(), format.errors({ stack: true }), format.splat(), format.json()), dirname: join(__dirname, '..', '..', 'logs'),
defaultMeta: { service: 'log-service' },
transports: [
new DailyRotateFile({
filename: 'logs/errors/error-%DATE%.log', // 日志名称,占位符 %DATE% 取值为 datePattern 值。
datePattern: 'YYYY-MM-DD', // 日志轮换的频率,此处表示每天。 datePattern: 'YYYY-MM-DD', // 日志轮换的频率,此处表示每天。
zippedArchive: true, // 是否通过压缩的方式归档被轮换的日志文件。 zippedArchive: true, // 是否通过压缩的方式归档被轮换的日志文件。
maxSize: '20m', // 设置日志文件的最大大小,m 表示 mb 。 maxSize: '20m', // 设置日志文件的最大大小,m 表示 mb 。
maxFiles: '14d', // 保留日志文件的最大天数,此处表示自动删除超过 14 天的日志文件。 maxFiles: '14d' // 保留日志文件的最大天数,此处表示自动删除超过 14 天的日志文件。
level: 'error' // 日志类型,此处表示只记录错误日志。 }
}),
export default createLogger({
format: format.combine(
...formaters,
utilities.format.nestLike('', {
colors: false,
prettyPrint: true
})
),
defaultMeta: { service: 'Winstion-Logger-Service' },
transports: [
// new DailyRotateFile({
// filename: 'logs/errors/error-%DATE%.log', // 日志名称,占位符 %DATE% 取值为 datePattern 值。
// level: 'error', // 日志类型,此处表示只记录错误日志。
// ...cfgRotage
// }),
new DailyRotateFile({ new DailyRotateFile({
filename: 'logs/warnings/warning-%DATE%.log', filename: 'logs/warnings/warning-%DATE%.log',
datePattern: 'YYYY-MM-DD', level: 'warn',
zippedArchive: true, ...cfgRotage
maxSize: '20m',
maxFiles: '14d',
level: 'warn'
}), }),
new DailyRotateFile({ new DailyRotateFile({
filename: 'logs/app/app-%DATE%.log', filename: 'logs/app/app-%DATE%.log',
datePattern: 'YYYY-MM-DD', ...cfgRotage
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
}), }),
new transports.Console({ new transports.Console({
format: format.combine( format: format.combine(
format.colorize({ ...formaters,
colors: levelsColors utilities.format.nestLike('', {
}), colors: true,
format.simple(), prettyPrint: true
format.printf(info => {
// 获取 Info Symbols key
const symbols = Object.getOwnPropertySymbols(info)
const color = levelsColors[info[symbols[0]]] // 获取日志级别的颜色
const chalkColor = chalk[color]
const message = `${chalkColor(info.timestamp)} ${chalkColor(info[symbols[2]])}`
return message
}) })
), ),
level: 'debug' level: 'debug'
......
...@@ -2,11 +2,9 @@ import { NestFactory } from '@nestjs/core' ...@@ -2,11 +2,9 @@ import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module' import { AppModule } from './app.module'
import { NestExpressApplication } from '@nestjs/platform-express' import { NestExpressApplication } from '@nestjs/platform-express'
import Initializer from './initor' import Initializer from './initor'
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston'
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule) const app = await NestFactory.create<NestExpressApplication>(AppModule)
await Initializer.use(app) await Initializer.use(app)
app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
await app.listen(process.env.APP_PORT) await app.listen(process.env.APP_PORT)
} }
bootstrap() bootstrap()
...@@ -3,7 +3,7 @@ import { BroadcastService } from './broadcast.service' ...@@ -3,7 +3,7 @@ import { BroadcastService } from './broadcast.service'
import { TransformInterceptor } from '../../common/interceptors' import { TransformInterceptor } from '../../common/interceptors'
import { WsGateway } from '../ws/ws.gateway' import { WsGateway } from '../ws/ws.gateway'
import { BroadcastDto } from '../../dto' import { BroadcastDto } from '../../dto'
import { ValidationPipe } from '../../common/pipes' import { ParseDeviceIdPipe, ValidationPipe } from '../../common/pipes'
import { ApiOperation, ApiTags } from '@nestjs/swagger' import { ApiOperation, ApiTags } from '@nestjs/swagger'
import { OnEvent } from '@nestjs/event-emitter' import { OnEvent } from '@nestjs/event-emitter'
import { Events } from '../../common/enums' import { Events } from '../../common/enums'
...@@ -28,12 +28,13 @@ export class BroadcastController { ...@@ -28,12 +28,13 @@ export class BroadcastController {
*/ */
@Post('/cmd') @Post('/cmd')
@ApiOperation({ summary: '给设备发送指令' }) @ApiOperation({ summary: '给设备发送指令' })
@UsePipes(new ParseDeviceIdPipe())
async message(@Body() params: BroadcastDto): Promise<CommonTypes.IResData> { async message(@Body() params: BroadcastDto): Promise<CommonTypes.IResData> {
return this.wsGateway.send(params) return this.wsGateway.send(params)
} }
@OnEvent(Events.OnMessage) @OnEvent(Events.OnMessage)
onMessage(@Body() params: any): Promise<CommonTypes.IResData> { onMessage(@Body() params: any): Promise<CommonTypes.IResData> {
Logger.warn('收到私有订阅消息:', params) Logger.warn(params)
return this.broadcastService.onMessage(params) return this.broadcastService.onMessage(params)
} }
} }
...@@ -2,7 +2,7 @@ import { HttpService } from '@nestjs/axios' ...@@ -2,7 +2,7 @@ import { HttpService } from '@nestjs/axios'
import { Inject, Injectable } from '@nestjs/common' import { Inject, Injectable } from '@nestjs/common'
import { AxiosResponse } from 'axios' import { AxiosResponse } from 'axios'
import { ConfigService } from 'nestjs-config' import { ConfigService } from 'nestjs-config'
import { Command, Events, FileCommand, RESPONSE_CODE } from '../../common/enums' import { Command, Events, RESPONSE_CODE } from '../../common/enums'
import { EventEmitter2 } from '@nestjs/event-emitter' import { EventEmitter2 } from '@nestjs/event-emitter'
@Injectable() @Injectable()
export class BroadcastService { export class BroadcastService {
...@@ -17,7 +17,7 @@ export class BroadcastService { ...@@ -17,7 +17,7 @@ export class BroadcastService {
} }
// // 广播消息 // // 广播消息
async onMessage(param: any): Promise<CommonTypes.IResData> { async onMessage(param: any): Promise<CommonTypes.IResData> {
if (param?.code === RESPONSE_CODE.SUCCESS && param?.data?.command === Command.File && param?.data?.payload?.command === FileCommand.Remove) { if (param?.code === RESPONSE_CODE.SUCCESS && param?.data?.command === Command.RemoveLog) {
this.eventEmitter.emit(Events.OnLogFileRemoved, { device_id: param.device_id, last_log_remove_time: new Date() }) this.eventEmitter.emit(Events.OnLogFileRemoved, { device_id: param.device_id, last_log_remove_time: new Date() })
return return
} }
......
...@@ -4,7 +4,7 @@ import { TransformInterceptor } from '../../common/interceptors' ...@@ -4,7 +4,7 @@ import { TransformInterceptor } from '../../common/interceptors'
import { AddDeviceDto, AddDeviceInfoDto, DeviceQueryDto, DeviceStatusDto } from '../../dto' import { AddDeviceDto, AddDeviceInfoDto, DeviceQueryDto, DeviceStatusDto } from '../../dto'
import { PagesPipe, ValidationPipe } from '../../common/pipes' import { PagesPipe, ValidationPipe } from '../../common/pipes'
import { OnEvent, EventEmitter2 } from '@nestjs/event-emitter' import { OnEvent, EventEmitter2 } from '@nestjs/event-emitter'
import { WsAccess, Events, WsMessageType, Command, RESPONSE_CODE, FileCommand } from '../../common/enums' import { WsAccess, Events, WsMessageType, Command, RESPONSE_CODE } from '../../common/enums'
import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger' import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'
@ApiTags('设备管理') @ApiTags('设备管理')
......
...@@ -3,7 +3,7 @@ import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } f ...@@ -3,7 +3,7 @@ import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } f
// import { InjectRepository } from '@nestjs/typeorm'; // import { InjectRepository } from '@nestjs/typeorm';
// import { Device as DeviceEntity } from '../entities/Device' // import { Device as DeviceEntity } from '../entities/Device'
import { PrismaService } from 'nestjs-prisma' import { PrismaService } from 'nestjs-prisma'
import { Command, FileCommand, RESPONSE_CODE, WsMessageType, WsStatus } from '../../common/enums' import { Command, RESPONSE_CODE, WsMessageType, WsStatus } from '../../common/enums'
import { WsGateway } from '../ws/ws.gateway' import { WsGateway } from '../ws/ws.gateway'
@Injectable() @Injectable()
...@@ -131,7 +131,7 @@ export class DeviceService implements OnModuleInit { ...@@ -131,7 +131,7 @@ export class DeviceService implements OnModuleInit {
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' } return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
} }
async resetAllDeviceStatus(): Promise<CommonTypes.IResData> { async resetAllDeviceStatus(): Promise<CommonTypes.IResData> {
Logger.warn('===重置所有设备状态===') Logger.warn('========重置所有设备状态========')
await this.prisma.device_status.updateMany({ await this.prisma.device_status.updateMany({
data: { data: {
status: WsStatus.Offline status: WsStatus.Offline
...@@ -167,7 +167,7 @@ export class DeviceService implements OnModuleInit { ...@@ -167,7 +167,7 @@ export class DeviceService implements OnModuleInit {
JOIN log_config c ON c.device_id = d.device_id JOIN log_config c ON c.device_id = d.device_id
WHERE c.log_saved_days >= TIMESTAMPDIFF(DAY, d.last_log_remove_time, NOW());` WHERE c.log_saved_days >= TIMESTAMPDIFF(DAY, d.last_log_remove_time, NOW());`
for (const { device_id, log_saved_days } of results) { 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 } } }) await this.wsGateway.send({ event: WsMessageType.Private, device_id, data: { command: Command.RemoveLog, payload: { days: log_saved_days } } })
} }
return { code: RESPONSE_CODE.SUCCESS, message: '每日日志删除任务完成' } return { code: RESPONSE_CODE.SUCCESS, message: '每日日志删除任务完成' }
} }
......
...@@ -56,7 +56,7 @@ export class FileService { ...@@ -56,7 +56,7 @@ export class FileService {
const { id, path: origin_path } = (await prisma.file.findFirst({ where, select: { id: true, path: true } })) || {} const { id, path: origin_path } = (await prisma.file.findFirst({ where, select: { id: true, path: true } })) || {}
if (id) { if (id) {
try { try {
fs.unlinkSync(origin_path) fs.existsSync(origin_path) && fs.unlinkSync(origin_path)
} catch (err) { } catch (err) {
Logger.error('删除文件失败', err) Logger.error('删除文件失败', err)
} }
......
...@@ -88,7 +88,7 @@ export class WsService { ...@@ -88,7 +88,7 @@ export class WsService {
*/ */
resetClients(): void { resetClients(): void {
this.clientIds.clear() this.clientIds.clear()
Logger.warn('===WebSocket初始化成功!重置所有客户端连接数据===') Logger.warn('========WebSocket初始化成功!重置所有客户端连接数据========')
} }
/** /**
...@@ -102,7 +102,7 @@ export class WsService { ...@@ -102,7 +102,7 @@ export class WsService {
Logger.log('Websocket Send Private Error->', payload) Logger.log('Websocket Send Private Error->', payload)
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败`, error: 'send error' }, HttpStatus.BAD_REQUEST) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败`, error: 'send error' }, HttpStatus.BAD_REQUEST)
} }
Logger.log('发送系统消息成功->', payload) Logger.log( payload)
return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' } return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' }
} }
...@@ -113,14 +113,14 @@ export class WsService { ...@@ -113,14 +113,14 @@ export class WsService {
* @param deviceId 接收者设备号 * @param deviceId 接收者设备号
*/ */
async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResData> { async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResData> {
if (!payload.device_id) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: '请求参数employeeId 必传', error: 'deviceId is required' }, HttpStatus.BAD_REQUEST) if (!payload.device_id) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: '请求参数device_id 必传', error: 'deviceId is required' }, HttpStatus.BAD_REQUEST)
const client = this.allClients?.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) const res = client?.emit(WsMessageType.Private, payload.data)
if (!res) { if (!res) {
Logger.error('Websocket Send Private Error->', payload) Logger.error('Websocket Send Private Error->', payload)
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败,客户端:(设备号->${payload.device_id}) 不在线`, error: 'send error' }, HttpStatus.BAD_REQUEST) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败,客户端:(设备号->${payload.device_id}) 不在线`, error: 'send error' }, HttpStatus.BAD_REQUEST)
} }
Logger.log('发送私有消息成功->', payload) Logger.log(payload)
return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' } return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' }
} }
onMessage(message:any){ onMessage(message:any){
......
...@@ -34,19 +34,17 @@ ...@@ -34,19 +34,17 @@
# POST http://localhost:3000/broadcast/cmd HTTP/1.1 POST http://localhost:3000/broadcast/cmd HTTP/1.1
# content-type: application/json content-type: application/json
# { {
# "event":"private", "event":"private",
# "device_id":1000000, "device_id":"1000000",
# "data":{ "data":{
# "command":"getLog", "command":"startPolling",
# "payload":{ "force":true
# "key":"recordList" }
# } }
# }
# }
# http://localhost:3000/file/list?device_id=1000000 # http://localhost:3000/file/list?device_id=1000000
# http://localhost:3000/config?device_id=1000000 # http://localhost:3000/config?device_id=1000000
...@@ -68,4 +66,4 @@ ...@@ -68,4 +66,4 @@
# "type":"user" # "type":"user"
# } # }
http://localhost:3000/fields/user/list?name=name
\ No newline at end of file \ No newline at end of file
# http://localhost:3000/fields/user/list?name=name
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!