Commit 36572713 by yixinjj

添加一些指令处理

1 parent dd9322cc
......@@ -27,14 +27,9 @@ import { FieldsModule } from './modules/fields/fields.module'
import { WinstonModule } from 'nest-winston'
import winstonLogger from './initor/winstion.config'
@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]
......@@ -42,8 +37,8 @@ import winstonLogger from './initor/winstion.config'
WinstonModule.forRoot({
transports: winstonLogger.transports,
format: winstonLogger.format,
defaultMeta: winstonLogger.defaultMeta,
exitOnError: false, // 防止意外退出
// defaultMeta: winstonLogger.defaultMeta,
exitOnError: false // 防止意外退出
}),
// TODO @nestjs/terminus almost the same
// StatusMonitorModule.setUp(statusMonitorConfig),
......@@ -53,12 +48,6 @@ import winstonLogger from './initor/winstion.config'
// }),
ScheduleModule.forRoot(),
EventEmitterModule.forRoot(),
// WinstonModule.forRoot({
// transports: winstonLogger.transports,
// format: winstonLogger.format,
// defaultMeta: winstonLogger.defaultMeta,
// exitOnError: false, // 防止意外退出
// }),
TasksModule,
// AudioModule,
// AuthModule,
......
......@@ -64,12 +64,12 @@ export enum Command{
GetLog='getLog',
GetStorage='getStorage',
Message='message',
File='file'
}
export enum FileCommand{
GetList='getList',
Remove='remove'
GetLogList='getLogList',
RemoveLog='removeLog',
RemoveRecord='removeRecord',
StopPolling='stopPolling',
StartPolling='startPolling',
SetPollingInterval='setPollingInterval'
}
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 { Logger } from '../../logger/log4js';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction): void {
const { method, url, originalUrl, baseUrl } = req
const methodUpper = method.toUpperCase()
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)}}`)
const { method, url, originalUrl, baseUrl, query, body } = req
Logger.warn({ method, url, originalUrl, baseUrl, query, body })
next()
}
}
......@@ -14,6 +14,6 @@ export const BodyResponse: CommonTypes.TBodyResponse = ({ message = RESPONSE_MSG
message = message.join(';')
}
const result = { url, data, total, error, message, code, timestamp: getCurrentTimestamp() }
Logger.warn('返回结果:', result)
Logger.warn(result)
return result
}
......@@ -13,7 +13,8 @@ export function IsNumberOrNumberString(validationOptions?: ValidationOptions) {
validator: {
validate(value: any, args: ValidationArguments) {
// 如果值为空(null, undefined, ''),则验证通过
if (value === null || value === undefined || value === '') {
if(value === '') return false
if (value === null || value === undefined) {
return true
}
......
import { ApiProperty } from '@nestjs/swagger'
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 { IsNumberOrNumberString } from './base.dto'
class DataDto {
@ApiProperty({
type: String,
description: '指令类型'
description: '指令类型 '
})
@IsEnum(Command, { message: '指令类型错误' })
@IsEnum(Command, { message: '指令类型错误 目前支持 ' })
@IsString({ message: '指令为必填参数' })
@IsNotEmpty({ message: '指令不能为空' })
readonly command: Command
@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 {
@ApiProperty({
type: String,
description: '事件类型: private-私有消息,system-系统消息',
description: '事件类型: private-私有消息,system-系统消息'
})
@IsEnum(WsMessageType, { message: '事件类型错误' })
@IsNotEmpty({ message: '事件类型不能为空' })
......@@ -32,7 +52,7 @@ export class BroadcastDto {
@IsDefined({ message: '发送私有消息时,device_id是必填的' })
@ApiProperty({
type: Number,
description: '设备号,私发信息必填',
description: '设备号,私发信息必填'
})
readonly device_id: number
......
......@@ -5,7 +5,7 @@ import { ExceptionsFilter, HttpExceptionFilter } from '../common/filters'
import { docBuilder } from './doc'
import { wsRedisAdapter } from './ws'
import { join } from 'path'
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston'
export default class Initializer {
static async use(app) {
app.useGlobalFilters(new ExceptionsFilter())
......@@ -16,7 +16,7 @@ export default class Initializer {
// app.useGlobalFilters(new ValidateExceptionFilter())
// 全局管道
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.useStaticAssets(join(__dirname, '..', '..', process.env.STATIC_PATH))
......
import * as chalk from 'chalk' // 用于颜色化输出
import { utilities } from 'nest-winston'
import { join } from 'path'
import { createLogger, format, transports } from 'winston'
import winston = require('winston')
import * as DailyRotateFile from 'winston-daily-rotate-file'
// 定义日志级别颜色
const levelsColors = {
error: 'red',
warn: 'yellow',
info: 'green',
debug: 'blue',
verbose: 'cyan'
}
const formaters = [format.timestamp(), format.errors({ stack: true }), format.splat(), format.json(), winston.format.ms()]
export default createLogger({
format: format.combine(format.timestamp(), format.errors({ stack: true }), format.splat(), format.json()),
defaultMeta: { service: 'log-service' },
transports: [
new DailyRotateFile({
filename: 'logs/errors/error-%DATE%.log', // 日志名称,占位符 %DATE% 取值为 datePattern 值。
const cfgRotage = {
dirname: join(__dirname, '..', '..', 'logs'),
datePattern: 'YYYY-MM-DD', // 日志轮换的频率,此处表示每天。
zippedArchive: true, // 是否通过压缩的方式归档被轮换的日志文件。
maxSize: '20m', // 设置日志文件的最大大小,m 表示 mb 。
maxFiles: '14d', // 保留日志文件的最大天数,此处表示自动删除超过 14 天的日志文件。
level: 'error' // 日志类型,此处表示只记录错误日志。
}),
maxFiles: '14d' // 保留日志文件的最大天数,此处表示自动删除超过 14 天的日志文件。
}
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({
filename: 'logs/warnings/warning-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d',
level: 'warn'
level: 'warn',
...cfgRotage
}),
new DailyRotateFile({
filename: 'logs/app/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
...cfgRotage
}),
new transports.Console({
format: format.combine(
format.colorize({
colors: levelsColors
}),
format.simple(),
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
...formaters,
utilities.format.nestLike('', {
colors: true,
prettyPrint: true
})
),
level: 'debug'
......
......@@ -2,11 +2,9 @@ import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { NestExpressApplication } from '@nestjs/platform-express'
import Initializer from './initor'
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston'
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule)
await Initializer.use(app)
app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
await app.listen(process.env.APP_PORT)
}
bootstrap()
......@@ -3,7 +3,7 @@ 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 { ParseDeviceIdPipe, ValidationPipe } from '../../common/pipes'
import { ApiOperation, ApiTags } from '@nestjs/swagger'
import { OnEvent } from '@nestjs/event-emitter'
import { Events } from '../../common/enums'
......@@ -28,12 +28,13 @@ export class BroadcastController {
*/
@Post('/cmd')
@ApiOperation({ summary: '给设备发送指令' })
@UsePipes(new ParseDeviceIdPipe())
async message(@Body() params: BroadcastDto): Promise<CommonTypes.IResData> {
return this.wsGateway.send(params)
}
@OnEvent(Events.OnMessage)
onMessage(@Body() params: any): Promise<CommonTypes.IResData> {
Logger.warn('收到私有订阅消息:', params)
Logger.warn(params)
return this.broadcastService.onMessage(params)
}
}
......@@ -2,7 +2,7 @@ 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 { Command, Events, RESPONSE_CODE } from '../../common/enums'
import { EventEmitter2 } from '@nestjs/event-emitter'
@Injectable()
export class BroadcastService {
......@@ -17,7 +17,7 @@ export class BroadcastService {
}
// // 广播消息
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() })
return
}
......
......@@ -4,7 +4,7 @@ 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 { WsAccess, Events, WsMessageType, Command, RESPONSE_CODE } from '../../common/enums'
import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'
@ApiTags('设备管理')
......
......@@ -3,7 +3,7 @@ import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } f
// 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 { Command, RESPONSE_CODE, WsMessageType, WsStatus } from '../../common/enums'
import { WsGateway } from '../ws/ws.gateway'
@Injectable()
......@@ -131,7 +131,7 @@ export class DeviceService implements OnModuleInit {
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
}
async resetAllDeviceStatus(): Promise<CommonTypes.IResData> {
Logger.warn('===重置所有设备状态===')
Logger.warn('========重置所有设备状态========')
await this.prisma.device_status.updateMany({
data: {
status: WsStatus.Offline
......@@ -167,7 +167,7 @@ export class DeviceService implements OnModuleInit {
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 } } })
await this.wsGateway.send({ event: WsMessageType.Private, device_id, data: { command: Command.RemoveLog, payload: { days: log_saved_days } } })
}
return { code: RESPONSE_CODE.SUCCESS, message: '每日日志删除任务完成' }
}
......
......@@ -56,7 +56,7 @@ export class FileService {
const { id, path: origin_path } = (await prisma.file.findFirst({ where, select: { id: true, path: true } })) || {}
if (id) {
try {
fs.unlinkSync(origin_path)
fs.existsSync(origin_path) && fs.unlinkSync(origin_path)
} catch (err) {
Logger.error('删除文件失败', err)
}
......
......@@ -88,7 +88,7 @@ export class WsService {
*/
resetClients(): void {
this.clientIds.clear()
Logger.warn('===WebSocket初始化成功!重置所有客户端连接数据===')
Logger.warn('========WebSocket初始化成功!重置所有客户端连接数据========')
}
/**
......@@ -102,7 +102,7 @@ export class WsService {
Logger.log('Websocket Send Private Error->', payload)
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: '发送成功' }
}
......@@ -113,14 +113,14 @@ export class WsService {
* @param deviceId 接收者设备号
*/
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 res = client?.emit(WsMessageType.Private, payload.data)
if (!res) {
Logger.error('Websocket Send Private Error->', payload)
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: '发送成功' }
}
onMessage(message:any){
......
......@@ -34,19 +34,17 @@
# POST http://localhost:3000/broadcast/cmd HTTP/1.1
# content-type: application/json
# {
# "event":"private",
# "device_id":1000000,
# "data":{
# "command":"getLog",
# "payload":{
# "key":"recordList"
# }
# }
# }
POST http://localhost:3000/broadcast/cmd HTTP/1.1
content-type: application/json
{
"event":"private",
"device_id":"1000000",
"data":{
"command":"startPolling",
"force":true
}
}
# http://localhost:3000/file/list?device_id=1000000
# http://localhost:3000/config?device_id=1000000
......@@ -68,4 +66,4 @@
# "type":"user"
# }
http://localhost:3000/fields/user/list?name=name
\ No newline at end of file
# http://localhost:3000/fields/user/list?name=name
\ 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!