Commit dd9322cc by yixinjj

添加日志模块

1 parent f470f75d
...@@ -52,12 +52,15 @@ ...@@ -52,12 +52,15 @@
"@socket.io/redis-adapter": "^8.3.0", "@socket.io/redis-adapter": "^8.3.0",
"axios": "^1.7.7", "axios": "^1.7.7",
"bull": "^3.14.0", "bull": "^3.14.0",
"chalk": "4",
"class-transformer": "^0.3.1", "class-transformer": "^0.3.1",
"class-validator": "^0.12.2", "class-validator": "^0.12.2",
"compressing": "^1.5.1", "compressing": "^1.5.1",
"dayjs": "^1.11.13",
"global": "^4.4.0", "global": "^4.4.0",
"mysql": "^2.18.1", "mysql": "^2.18.1",
"nest-status-monitor": "^0.1.3", "nest-status-monitor": "^0.1.3",
"nest-winston": "^1.9.7",
"nestjs-config": "^1.4.6", "nestjs-config": "^1.4.6",
"nestjs-prisma": "^0.23.0", "nestjs-prisma": "^0.23.0",
"nodemailer": "^6.4.16", "nodemailer": "^6.4.16",
...@@ -70,7 +73,9 @@ ...@@ -70,7 +73,9 @@
"rxjs": "^7.8.1", "rxjs": "^7.8.1",
"socket.io": "4.7.4", "socket.io": "4.7.4",
"swagger-ui-express": "^5.0.1", "swagger-ui-express": "^5.0.1",
"typeorm": "0.2.25" "typeorm": "0.2.25",
"winston": "^3.14.2",
"winston-daily-rotate-file": "^5.0.0"
}, },
"devDependencies": { "devDependencies": {
"@nestjs/cli": "^10.4.5", "@nestjs/cli": "^10.4.5",
......
-- CreateTable
CREATE TABLE `device` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`sn` VARCHAR(20) NOT NULL,
`create_time` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `device_info` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`device_id` INTEGER NOT NULL DEFAULT 0,
`user` VARCHAR(20) NULL,
`last_log_upload_time` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`last_log_remove_time` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`mobile` VARCHAR(20) NULL,
`merchant_name` VARCHAR(50) NULL,
UNIQUE INDEX `device_info_device_id_key`(`device_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `device_status` (
`device_id` INTEGER NOT NULL,
`status` TINYINT NOT NULL DEFAULT 0,
PRIMARY KEY (`device_id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `log` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`device_id` INTEGER NOT NULL DEFAULT 0,
`path` VARCHAR(255) NOT NULL,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
UNIQUE INDEX `log_device_id_key`(`device_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `log_config` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`device_id` INTEGER NOT NULL DEFAULT 0,
`log_saved_days` TINYINT NULL DEFAULT 7,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
UNIQUE INDEX `log_config_device_id_key`(`device_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `log_config_userfield_relation` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`config_id` INTEGER NOT NULL DEFAULT 0,
`user_field_id` INTEGER NOT NULL DEFAULT 0,
INDEX `FK_log_config_userfield_relation_log_config`(`config_id`),
INDEX `FK_log_config_userfield_relation_log_user_field`(`user_field_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `log_user_field` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(20) NOT NULL,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- AddForeignKey
ALTER TABLE `device_info` ADD CONSTRAINT `FK_device_info_device` FOREIGN KEY (`device_id`) REFERENCES `device`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `device_status` ADD CONSTRAINT `FK__device` FOREIGN KEY (`device_id`) REFERENCES `device`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `device_status` ADD CONSTRAINT `FK__device_info` FOREIGN KEY (`device_id`) REFERENCES `device_info`(`device_id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log` ADD CONSTRAINT `FK_log_device` FOREIGN KEY (`device_id`) REFERENCES `device`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log` ADD CONSTRAINT `FK_log_device_info` FOREIGN KEY (`device_id`) REFERENCES `device_info`(`device_id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log_config` ADD CONSTRAINT `FK_log_config_device` FOREIGN KEY (`device_id`) REFERENCES `device`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log_config` ADD CONSTRAINT `FK_log_config_device_info` FOREIGN KEY (`device_id`) REFERENCES `device_info`(`device_id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log_config_userfield_relation` ADD CONSTRAINT `FK_log_config_userfield_relation_log_config` FOREIGN KEY (`config_id`) REFERENCES `log_config`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log_config_userfield_relation` ADD CONSTRAINT `FK_log_config_userfield_relation_log_user_field` FOREIGN KEY (`user_field_id`) REFERENCES `log_user_field`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
/*
Warnings:
- A unique constraint covering the columns `[sn]` on the table `device` will be added. If there are existing duplicate values, this will fail.
*/
-- AlterTable
ALTER TABLE `device_info` MODIFY `last_log_upload_time` TIMESTAMP(0) NULL,
MODIFY `last_log_remove_time` TIMESTAMP(0) NULL;
-- CreateIndex
CREATE UNIQUE INDEX `device_sn_key` ON `device`(`sn`);
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "mysql"
\ No newline at end of file \ No newline at end of file
...@@ -10,7 +10,7 @@ datasource db { ...@@ -10,7 +10,7 @@ datasource db {
model device { model device {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
sn String @unique @db.VarChar(20) sn String @unique @db.VarChar(20)
create_time DateTime @default(now()) @db.Timestamp(0) created_at DateTime @default(dbgenerated("(now())")) @db.Timestamp(0)
device_info device_info? device_info device_info?
device_status device_status? device_status device_status?
logs file[] logs file[]
...@@ -52,6 +52,8 @@ model file { ...@@ -52,6 +52,8 @@ model file {
type String @default("other") @db.VarChar(10) type String @default("other") @db.VarChar(10)
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_device") 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") device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_device_info")
@@index([device_id], map: "FK_log_device_info")
} }
model log_config { model log_config {
...@@ -60,26 +62,27 @@ model log_config { ...@@ -60,26 +62,27 @@ model log_config {
log_saved_days Int? @default(7) @db.TinyInt log_saved_days Int? @default(7) @db.TinyInt
created_at DateTime @default(now()) @db.Timestamp(0) created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0) updated_at DateTime @default(now()) @db.Timestamp(0)
fields config_field_relation[]
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device") device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device")
device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device_info") device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device_info")
user_fields log_config_userfield_relation[]
} }
model log_config_userfield_relation { model config_field_relation {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
config_id Int @default(0) config_id Int @default(0)
user_field_id Int @default(0) field_id Int @default(0)
log_config log_config @relation(fields: [config_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_userfield_relation_log_config") log_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") field field @relation(fields: [field_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_userfield_relation_log_user_field")
@@index([config_id], map: "FK_log_config_userfield_relation_log_config") @@index([config_id], map: "FK_log_config_userfield_relation_log_config")
@@index([user_field_id], map: "FK_log_config_userfield_relation_log_user_field") @@index([field_id], map: "FK_log_config_userfield_relation_log_user_field")
} }
model log_user_field { model field {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
name String @db.VarChar(20) name String @db.VarChar(20)
created_at DateTime @default(now()) @db.Timestamp(0) created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0) updated_at DateTime @default(now()) @db.Timestamp(0)
log_config_userfield_relation log_config_userfield_relation[] type String @default("user") @db.VarChar(10)
config_field_relation config_field_relation[]
} }
...@@ -23,6 +23,11 @@ import { LogConfigModule } from './modules/config/config.module' ...@@ -23,6 +23,11 @@ import { LogConfigModule } from './modules/config/config.module'
import { BroadcastModule } from './modules/broadcast/broadcast.module' import { BroadcastModule } from './modules/broadcast/broadcast.module'
import { EventEmitterModule } from '@nestjs/event-emitter' import { EventEmitterModule } from '@nestjs/event-emitter'
import { HttpModule } from '@nestjs/axios' import { HttpModule } from '@nestjs/axios'
import { FieldsModule } from './modules/fields/fields.module'
import { WinstonModule } from 'nest-winston'
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}')),
...@@ -34,14 +39,26 @@ import { HttpModule } from '@nestjs/axios' ...@@ -34,14 +39,26 @@ import { HttpModule } from '@nestjs/axios'
useFactory: async (config: ConfigService) => config.get('http'), useFactory: async (config: ConfigService) => config.get('http'),
inject: [ConfigService] inject: [ConfigService]
}), }),
WinstonModule.forRoot({
transports: winstonLogger.transports,
format: winstonLogger.format,
defaultMeta: winstonLogger.defaultMeta,
exitOnError: false, // 防止意外退出
}),
// TODO @nestjs/terminus almost the same // TODO @nestjs/terminus almost the same
StatusMonitorModule.setUp(statusMonitorConfig), // StatusMonitorModule.setUp(statusMonitorConfig),
// MailerModule.forRootAsync({ // MailerModule.forRootAsync({
// useFactory: (config: ConfigService) => config.get('email'), // useFactory: (config: ConfigService) => config.get('email'),
// inject: [ConfigService] // inject: [ConfigService]
// }), // }),
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,
...@@ -55,7 +72,8 @@ import { HttpModule } from '@nestjs/axios' ...@@ -55,7 +72,8 @@ import { HttpModule } from '@nestjs/axios'
WsModule, WsModule,
DeviceModule, DeviceModule,
BroadcastModule, BroadcastModule,
LogConfigModule LogConfigModule,
FieldsModule
] ]
}) })
export class AppModule { export class AppModule {
......
...@@ -71,3 +71,7 @@ export enum FileCommand{ ...@@ -71,3 +71,7 @@ export enum FileCommand{
GetList='getList', GetList='getList',
Remove='remove' Remove='remove'
} }
export enum LogFieldTypes{
User='user'
}
import { Injectable, Logger, NestMiddleware } from '@nestjs/common'; import { Injectable, NestMiddleware,Logger, RequestMethod } from '@nestjs/common'
import { Request, Response } from 'express'; import { NextFunction, Request, Response } from 'express'
// import { Logger } from '../../logger/log4js';
@Injectable() @Injectable()
export class LoggerMiddleware implements NestMiddleware { export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: () => void) { use(req: Request, res: Response, next: NextFunction): void {
const { method, path , url,params,query } = req; const { method, url, originalUrl, baseUrl } = req
Logger.debug(`method -> ${method} url -> ${url} params -> ${JSON.stringify(params)} query -> ${JSON.stringify(query)}`); const methodUpper = method.toUpperCase()
next(); 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()
} }
} }
...@@ -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.debug('返回结果:', result) Logger.warn('返回结果:', result)
return result return result
} }
import { ApiProperty } from '@nestjs/swagger'
import { IsEnum, IsNotEmpty, IsOptional } from 'class-validator'
import { LogFieldTypes } from '../common/enums'
export class CreateFieldDto {
@ApiProperty({
description: '字段名称',
required: true
})
@IsNotEmpty({ message: '字段名称不能为空' })
name: string
@ApiProperty({
description: '字段类型,枚举,目前只有"user"',
required: true
})
@IsEnum(LogFieldTypes, { message: '字段类型错误,目前只有user' })
@IsNotEmpty({ message: '字段类型不能为空' })
type: LogFieldTypes
}
export class QueryFieldDto {
@ApiProperty({
description: '字段名称',
required: false
})
name?: string
@ApiProperty({
description: '字段类型,枚举,目前只有"user"',
required: false
})
@IsOptional()
@IsEnum(LogFieldTypes, { message: '字段类型错误,目前只有user' })
type?: LogFieldTypes
}
...@@ -4,3 +4,4 @@ export * from './device.dto' ...@@ -4,3 +4,4 @@ export * from './device.dto'
export * from './response.dto' export * from './response.dto'
export * from './device.status.dto' export * from './device.status.dto'
export * from './file.dto' export * from './file.dto'
export * from './field.dto'
...@@ -5,6 +5,7 @@ import { ExceptionsFilter, HttpExceptionFilter } from '../common/filters' ...@@ -5,6 +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'
export default class Initializer { export default class Initializer {
static async use(app) { static async use(app) {
app.useGlobalFilters(new ExceptionsFilter()) app.useGlobalFilters(new ExceptionsFilter())
...@@ -15,6 +16,7 @@ export default class Initializer { ...@@ -15,6 +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.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 { createLogger, format, transports } from 'winston'
import * as DailyRotateFile from 'winston-daily-rotate-file'
// 定义日志级别颜色
const levelsColors = {
error: 'red',
warn: 'yellow',
info: 'green',
debug: 'blue',
verbose: 'cyan'
}
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 值。
datePattern: 'YYYY-MM-DD', // 日志轮换的频率,此处表示每天。
zippedArchive: true, // 是否通过压缩的方式归档被轮换的日志文件。
maxSize: '20m', // 设置日志文件的最大大小,m 表示 mb 。
maxFiles: '14d', // 保留日志文件的最大天数,此处表示自动删除超过 14 天的日志文件。
level: 'error' // 日志类型,此处表示只记录错误日志。
}),
new DailyRotateFile({
filename: 'logs/warnings/warning-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d',
level: 'warn'
}),
new DailyRotateFile({
filename: 'logs/app/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
}),
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
})
),
level: 'debug'
})
]
})
...@@ -2,9 +2,11 @@ import { NestFactory } from '@nestjs/core' ...@@ -2,9 +2,11 @@ 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()
...@@ -33,7 +33,7 @@ export class BroadcastController { ...@@ -33,7 +33,7 @@ export class BroadcastController {
} }
@OnEvent(Events.OnMessage) @OnEvent(Events.OnMessage)
onMessage(@Body() params: any): Promise<CommonTypes.IResData> { onMessage(@Body() params: any): Promise<CommonTypes.IResData> {
Logger.debug('收到私有订阅消息:', params) Logger.warn('收到私有订阅消息:', params)
return this.broadcastService.onMessage(params) return this.broadcastService.onMessage(params)
} }
} }
...@@ -18,11 +18,12 @@ export class ConfigService { ...@@ -18,11 +18,12 @@ export class ConfigService {
id: true, id: true,
device_id: true, device_id: true,
log_saved_days: true, log_saved_days: true,
user_fields: { fields: {
select: { select: {
log_user_field: { field: {
select: { select: {
name: true name: true,
type:true
} }
} }
} }
...@@ -35,13 +36,13 @@ export class ConfigService { ...@@ -35,13 +36,13 @@ export class ConfigService {
id: item.id, id: item.id,
device_id: item.device_id, device_id: item.device_id,
log_saved_days: item.log_saved_days, log_saved_days: item.log_saved_days,
user_fields: item.user_fields.map(item => item.log_user_field.name) fields: item.fields.map(item => ({name:item.field.name,type:item.field.type}))
} }
}) })
const total = await this.prisma.log_config.count({ const total = await this.prisma.log_config.count({
where where
}) })
const resBody: CommonTypes.IResData<ConfigTypes.LogConfigResponse[]> = { total, data } const resBody: CommonTypes.IResData<ConfigTypes.LogConfigResponse[]> = { total, data,code: RESPONSE_CODE.SUCCESS, message: '查询成功' }
return resBody return resBody
} }
...@@ -55,7 +56,7 @@ export class ConfigService { ...@@ -55,7 +56,7 @@ export class ConfigService {
if (id) { if (id) {
config_id = id config_id = id
await prisma.log_config.update({ where: { device_id: data.device_id }, data }) await prisma.log_config.update({ where: { device_id: data.device_id }, data })
await prisma.log_config_userfield_relation.deleteMany({ where: { config_id: id } }) await prisma.config_field_relation.deleteMany({ where: { config_id: id } })
} else { } else {
config.created_at = date config.created_at = date
const { id } = await prisma.log_config.create({ data, select: { id: true } }) const { id } = await prisma.log_config.create({ data, select: { id: true } })
...@@ -64,10 +65,10 @@ export class ConfigService { ...@@ -64,10 +65,10 @@ export class ConfigService {
const relations: RelationsTypes.LogConfigUserFieldsRel[] = user_fields.map((ufid: number) => { const relations: RelationsTypes.LogConfigUserFieldsRel[] = user_fields.map((ufid: number) => {
return { return {
config_id, config_id,
user_field_id: ufid field_id: ufid
} }
}) })
await prisma.log_config_userfield_relation.createMany({ data: relations, skipDuplicates: true }) await prisma.config_field_relation.createMany({ data: relations, skipDuplicates: true })
}) })
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' } return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
} }
......
...@@ -33,10 +33,11 @@ export class DeviceService implements OnModuleInit { ...@@ -33,10 +33,11 @@ export class DeviceService implements OnModuleInit {
} }
} }
} }
const result: Omit<DeviceTypes.IDeviceResult, 'id'>[] = await this.prisma.device.findMany({ const result: DeviceTypes.IDeviceResult[] = await this.prisma.device.findMany({
skip, skip,
take, take,
select: { select: {
id:true,
sn: true, sn: true,
device_info: { device_info: {
select: { select: {
...@@ -46,11 +47,12 @@ export class DeviceService implements OnModuleInit { ...@@ -46,11 +47,12 @@ export class DeviceService implements OnModuleInit {
log_config: { log_config: {
select: { select: {
log_saved_days: true, log_saved_days: true,
user_fields: { fields: {
select: { select: {
log_user_field: { field: {
select: { select: {
name: true name: true,
type:true
} }
} }
} }
...@@ -70,13 +72,14 @@ export class DeviceService implements OnModuleInit { ...@@ -70,13 +72,14 @@ export class DeviceService implements OnModuleInit {
}) })
const data: DeviceTypes.IDeviceInfo[] = result.reduce((pre: DeviceTypes.IDeviceInfo[], cur: DeviceTypes.IDeviceResult) => { const data: DeviceTypes.IDeviceInfo[] = result.reduce((pre: DeviceTypes.IDeviceInfo[], cur: DeviceTypes.IDeviceResult) => {
pre.push({ pre.push({
id:cur.id,
sn: cur.sn, sn: cur.sn,
user: cur.device_info?.user, user: cur.device_info?.user,
mobile: cur.device_info?.mobile, mobile: cur.device_info?.mobile,
status: cur.device_info?.device_status?.status, status: cur.device_info?.device_status?.status,
merchant_name: cur.device_info?.merchant_name, merchant_name: cur.device_info?.merchant_name,
log_saved_days: cur.device_info?.log_config?.log_saved_days, 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) fields: cur.device_info?.log_config?.fields?.map((item: DeviceTypes.IFields) => ({name:item.field.name,type:item.field.type}))
}) })
return pre return pre
}, []) }, [])
...@@ -84,7 +87,7 @@ export class DeviceService implements OnModuleInit { ...@@ -84,7 +87,7 @@ export class DeviceService implements OnModuleInit {
return resBody return resBody
} }
async addDevice(device: Omit<DeviceTypes.IDevice, 'id' | 'create_time'>): Promise<CommonTypes.IResData> { async addDevice(device: Omit<DeviceTypes.TDevice, 'id'>): Promise<CommonTypes.IResData> {
await this.prisma.$transaction(async prisma => { await this.prisma.$transaction(async prisma => {
const { id } = await prisma.device.create({ data: device, select: { id: true } }) const { id } = await prisma.device.create({ data: device, select: { id: true } })
// await this.addDeviceInfo({device_id:id}) // await this.addDeviceInfo({device_id:id})
...@@ -128,7 +131,7 @@ export class DeviceService implements OnModuleInit { ...@@ -128,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.debug('===重置所有设备状态===') Logger.warn('===重置所有设备状态===')
await this.prisma.device_status.updateMany({ await this.prisma.device_status.updateMany({
data: { data: {
status: WsStatus.Offline status: WsStatus.Offline
...@@ -145,11 +148,11 @@ export class DeviceService implements OnModuleInit { ...@@ -145,11 +148,11 @@ export class DeviceService implements OnModuleInit {
await prisma.device_info.create({ data: { device_id: id, mobile: el.手机号, merchant_name: el.最近使用人所在门店 || '', user: el.保管人, created_at: new Date(), updated_at: new Date() } }) await prisma.device_info.create({ data: { device_id: id, mobile: el.手机号, merchant_name: el.最近使用人所在门店 || '', user: el.保管人, created_at: new Date(), updated_at: new Date() } })
await prisma.device_status.create({ data: { device_id: id, status: WsStatus.Offline } }) await prisma.device_status.create({ data: { device_id: id, status: WsStatus.Offline } })
const { id: cfgid } = await prisma.log_config.create({ data: { device_id: id, log_saved_days: 7 }, select: { id: true } }) const { id: cfgid } = await prisma.log_config.create({ data: { device_id: id, log_saved_days: 7 }, select: { id: true } })
await prisma.log_config_userfield_relation.createMany({ await prisma.config_field_relation.createMany({
data: [ data: [
{ config_id: cfgid, user_field_id: 1 }, { config_id: cfgid, field_id: 1 },
{ config_id: cfgid, user_field_id: 2 }, { config_id: cfgid, field_id: 2 },
{ config_id: cfgid, user_field_id: 3 } { config_id: cfgid, field_id: 3 }
] ]
}) })
}) })
......
import { Controller, Get, Post, Body, Patch, Param, Delete, Query, UseInterceptors, UsePipes, ValidationPipe } from '@nestjs/common'
import { FieldsService } from './fields.service'
import { CreateFieldDto, QueryFieldDto } from '../../dto'
import { ApiOperation, ApiProperty, ApiTags } from '@nestjs/swagger'
import { TransformInterceptor } from '../../common/interceptors'
import { PagesPipe } from '../../common/pipes'
@ApiTags('字段管理')
@Controller('fields')
@UseInterceptors(TransformInterceptor)
@UsePipes(new ValidationPipe())
export class FieldsController {
constructor(private readonly fieldsService: FieldsService) {}
@Post('user/add')
@ApiOperation({ summary: '创建字段' })
async create(@Body() dto: CreateFieldDto): Promise<CommonTypes.IResData> {
return await this.fieldsService.create(dto)
}
@Get('user/list')
@UsePipes(new PagesPipe())
@ApiOperation({ summary: '获取所有字段列表' })
async findAll(@Query() dto: QueryFieldDto): Promise<CommonTypes.IResData<FieldTypes.IFiled[]>> {
return await this.fieldsService.findAll(dto)
}
}
import { Module } from '@nestjs/common';
import { FieldsService } from './fields.service';
import { FieldsController } from './fields.controller';
import { PrismaService } from 'nestjs-prisma';
@Module({
controllers: [FieldsController],
providers: [FieldsService,PrismaService],
})
export class FieldsModule {}
import { Injectable } from '@nestjs/common'
import { PrismaService } from 'nestjs-prisma'
import { RESPONSE_CODE } from '../../common/enums'
@Injectable()
export class FieldsService {
constructor(private readonly prismaService: PrismaService) {}
async create(createFieldDto: FieldTypes.TFieldAdd): Promise<CommonTypes.IResData> {
const now = new Date()
await this.prismaService.field.create({
data: {
name: createFieldDto.name,
type: createFieldDto.type,
created_at: now,
updated_at: now
}
})
return { code: RESPONSE_CODE.SUCCESS, message: '创建字段成功' }
}
async findAll({ skip, take, name, type }: FieldTypes.TFieldQuery): Promise<CommonTypes.IResData<FieldTypes.IFiled[]>> {
const where = {
name: {
contains: name
},
type
}
const result: FieldTypes.IFiled[] = await this.prismaService.field.findMany({ skip, take, where })
const total = await this.prismaService.field.count({ where })
return { code: RESPONSE_CODE.SUCCESS, message: '查询成功', total, data: result }
}
}
import { Inject, Injectable } from '@nestjs/common' import { Inject, Injectable, Logger } from '@nestjs/common'
import { tar } from 'compressing' import { tar } from 'compressing'
import { ConfigService } from 'nestjs-config' import { ConfigService } from 'nestjs-config'
import * as fs from 'fs' import * as fs from 'fs'
...@@ -55,7 +55,11 @@ export class FileService { ...@@ -55,7 +55,11 @@ export class FileService {
this.prisma.$transaction(async prisma => { this.prisma.$transaction(async prisma => {
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 {
fs.unlinkSync(origin_path) fs.unlinkSync(origin_path)
} catch (err) {
Logger.error('删除文件失败', err)
}
await prisma.file.update({ where: { id }, data: { filename, path, created_at } }) await prisma.file.update({ where: { id }, data: { filename, path, created_at } })
} else { } else {
await prisma.file.create({ data: file }) await prisma.file.create({ data: file })
......
...@@ -39,7 +39,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws ...@@ -39,7 +39,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
@SubscribeMessage(WsMessageType.Private) @SubscribeMessage(WsMessageType.Private)
subPrivate(@MessageBody() data: any): Observable<WsResponse<string>> { subPrivate(@MessageBody() data: any): Observable<WsResponse<string>> {
this.wsService.onMessage(data) this.wsService.onMessage(data)
return from<string>('ok').pipe(map(item => ({ event: WsMessageType.Private, data: item }))) return from<string>('o').pipe(map(item => ({ event: WsMessageType.Private, data: item })))
} }
/** /**
...@@ -103,7 +103,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws ...@@ -103,7 +103,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* @param server * @param server
*/ */
afterInit(server: Server) { afterInit(server: Server) {
Logger.debug('Websocket init... Port: ' + process.env.SOCKET_PORT) Logger.warn('Websocket init... Port: ' + process.env.SOCKET_PORT)
this.wsService.server = server this.wsService.server = server
// 重置 socketIds // 重置 socketIds
this.wsService.resetClients() this.wsService.resetClients()
......
...@@ -28,12 +28,12 @@ export class WsService { ...@@ -28,12 +28,12 @@ export class WsService {
if (clientIsOnline) { if (clientIsOnline) {
clientIsOnline.emit(WsMessageType.System, `设备-> ${deviceId} 已在别处上线, 此客户端 [${clientIsOnline.id}] 下线处理`) clientIsOnline.emit(WsMessageType.System, `设备-> ${deviceId} 已在别处上线, 此客户端 [${clientIsOnline.id}] 下线处理`)
clientIsOnline?.disconnect() clientIsOnline?.disconnect()
Logger.debug(`设备-> ${deviceId} 重复登录, [${clientIsOnline.id}] 先登录的设备下线处理`) Logger.warn(`设备-> ${deviceId} 重复登录, [${clientIsOnline.id}] 先登录的设备下线处理`)
} }
// 保存工号 // 保存工号
this.clientIds.set(deviceId, client.id) this.clientIds.set(deviceId, client.id)
const message = `Device-> ${deviceId} [${client.id}] Has Connected, OnLine Number: ${this.allClients.size}` const message = `Device-> ${deviceId} [${client.id}] Has Connected, OnLine Number: ${this.allClients.size}`
Logger.debug(message) Logger.warn(message)
this.server.emit(WsMessageType.System, message) this.server.emit(WsMessageType.System, message)
const resData: WsTypes.IWsResponse<WsStatus, WsAccess> = { const resData: WsTypes.IWsResponse<WsStatus, WsAccess> = {
device_id: deviceId, device_id: deviceId,
...@@ -61,7 +61,7 @@ export class WsService { ...@@ -61,7 +61,7 @@ export class WsService {
for (let [deviceId, clientId] of this.clientIds) { for (let [deviceId, clientId] of this.clientIds) {
if (clientId === id) { if (clientId === id) {
this.clientIds.delete(deviceId) this.clientIds.delete(deviceId)
Logger.debug(`Device-> ${deviceId} [${id}] Logout, OnLine Number: ${this.clientIds.size}`) Logger.warn(`Device-> ${deviceId} [${id}] Logout, OnLine Number: ${this.clientIds.size}`)
this.emit(Events.OnConnected, { status: WsStatus.Offline, message: WsAccess.IsOffline, device_id: deviceId }) this.emit(Events.OnConnected, { status: WsStatus.Offline, message: WsAccess.IsOffline, device_id: deviceId })
break break
} }
...@@ -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.debug('===WebSocket初始化成功!重置所有客户端连接数据===') Logger.warn('===WebSocket初始化成功!重置所有客户端连接数据===')
} }
/** /**
......
...@@ -13,7 +13,7 @@ export class TasksService { ...@@ -13,7 +13,7 @@ export class TasksService {
@Cron('0 10 * * * *') @Cron('0 10 * * * *')
handleCron() { handleCron() {
this.eventEmitter.emit(Events.OnTaskStart) this.eventEmitter.emit(Events.OnTaskStart)
Logger.debug('============开始定时任务============='); Logger.warn('============开始定时任务=============');
} }
// @Interval(5000) // @Interval(5000)
...@@ -23,7 +23,7 @@ export class TasksService { ...@@ -23,7 +23,7 @@ export class TasksService {
// @Timeout(5000) // @Timeout(5000)
// handleTimeout() { // handleTimeout() {
// this.logger.debug('Called once after 5 seconds'); // this.Logger.debug('Called once after 5 seconds');
// this.deviceService.removeFilesTask() // this.deviceService.removeFilesTask()
// } // }
} }
...@@ -104,6 +104,7 @@ declare namespace CommonTypes { ...@@ -104,6 +104,7 @@ declare namespace CommonTypes {
updated_at: Date | string updated_at: Date | string
} }
interface ISn { interface ISn {
sn: string sn: string
} }
......
...@@ -13,11 +13,11 @@ model log_config { ...@@ -13,11 +13,11 @@ model log_config {
declare namespace ConfigTypes { declare namespace ConfigTypes {
interface ILogConfig extends CommonTypes.IId, CommonTypes.IDeviceId, CommonTypes.ITime { interface ILogConfig extends CommonTypes.IId, CommonTypes.IDeviceId, CommonTypes.ITime {
log_saved_days: number log_saved_days: number
user_fields: DeviceTypes.ILogUserFields[] fields: DeviceTypes.IFields[]
} }
type LogConfigQuery = Pick<Partial<ILogConfig>, 'device_id'> & CommonTypes.IQueryBase type LogConfigQuery = Pick<Partial<ILogConfig>, 'device_id'> & CommonTypes.IQueryBase
type LogConfigAdd = Omit<Partial<ILogConfig>, 'id' | 'user_fields'> & { user_fields: number[] } type LogConfigAdd = Omit<Partial<ILogConfig>, 'id' | 'fields'> & { user_fields: number[] }
type LogConfigResult = Partial<ILogConfig> type LogConfigResult = Partial<ILogConfig>
type LogConfigResponse = Omit<LogConfigResult, 'user_fields'> & { user_fields: string[] } type LogConfigResponse = Omit<LogConfigResult, 'fields'> & { fields:CommonTypes.Optional<Partial<FieldTypes.IFiled>, 'name'|'type'>[] }
type LogConfigUpdate = CommonTypes.Optional<ILogConfig, 'device_id'> type LogConfigUpdate = CommonTypes.Optional<ILogConfig, 'device_id'>
} }
...@@ -19,11 +19,11 @@ declare namespace DeviceTypes { ...@@ -19,11 +19,11 @@ declare namespace DeviceTypes {
/** /**
* 设备信息接口 * 设备信息接口
*/ */
interface IDeviceInfo extends Omit<IDeviceInfoBase,'device_id'>, CommonTypes.PartialOne<IDevice, 'id'>, DeviceStatus.Status { interface IDeviceInfo extends Omit<IDeviceInfoBase, 'device_id'>, CommonTypes.PartialOne<TDevice, 'id'>, DeviceStatus.Status {
/** /**
* 日志用户字段 * 日志用户字段
*/ */
log_user_fields?: string[] fields?: FieldTypes.TFieldRequird[]
} }
/** /**
...@@ -50,25 +50,18 @@ declare namespace DeviceTypes { ...@@ -50,25 +50,18 @@ declare namespace DeviceTypes {
/** /**
* 表示设备结果的接口 * 表示设备结果的接口
*/ */
interface IDeviceResult extends IDevice { interface IDeviceResult extends TDevice {
/** /**
* 与设备关联的详细信息 * 与设备关联的详细信息
*/ */
device_info: IDeviceInfoRes device_info: IDeviceInfoRes
} }
interface IDevice extends CommonTypes.IId,CommonTypes.ISn { type TDevice = CommonTypes.IId & CommonTypes.ISn & Partial<Pick<CommonTypes.ITime, 'created_at'>>
/**
* 设备创建的时间戳
*/
create_time?: number
}
/** /**
* 表示设备详细信息的接口 * 表示设备详细信息的接口
*/ */
interface IDeviceInfoRes extends CommonTypes.PartialOne<Omit<IDeviceInfoBase,'device_id'>,'sn'>, CommonTypes.PartialOne<IDeviceInfoInput, 'created_at' | 'updated_at' | 'id' | 'device_id'|'sn'> { interface IDeviceInfoRes extends CommonTypes.PartialOne<Omit<IDeviceInfoBase, 'device_id'>, 'sn'>, CommonTypes.PartialOne<IDeviceInfoInput, 'created_at' | 'updated_at' | 'id' | 'device_id' | 'sn'> {
/** /**
* 与设备关联的日志配置信息 * 与设备关联的日志配置信息
*/ */
...@@ -87,16 +80,15 @@ declare namespace DeviceTypes { ...@@ -87,16 +80,15 @@ declare namespace DeviceTypes {
/** /**
* 日志用户字段的配置信息 * 日志用户字段的配置信息
*/ */
user_fields: ILogUserFields[] fields: IFields[]
} }
/** /**
* 表示日志用户字段的接口 * 表示日志用户字段的接口
*/ */
interface ILogUserFields { interface IFields {
/** /**
* 日志用户字段的详细信息 * 日志用户字段的详细信息
*/ */
log_user_field?: CommonTypes.Optional<Partial<UserFieldTypes.ILogUserFields>, 'name'> field?: FieldTypes.TFieldRequird
} }
} }
declare namespace FieldTypes {
interface IFiled extends CommonTypes.IId, CommonTypes.ITime {
name: string
type: string
}
type TFieldRequird = Pick<IFiled, 'name' | 'type'>
type TFieldAdd = TFieldRequird & Partial<Omit<IFiled, 'name' | 'type'>>
type TFieldQuery = Partial<Pick<IFiled, 'name' | 'type'>> & CommonTypes.IQueryBase
}
declare namespace RelationsTypes { declare namespace RelationsTypes {
interface IRelation extends CommonTypes.IId { interface IRelation extends CommonTypes.IId {
config_id: number config_id: number
user_field_id: number field_id: number
} }
type LogConfigUserFieldsRel = Omit<IRelation, 'id'> type LogConfigUserFieldsRel = Omit<IRelation, 'id'>
} }
...@@ -34,19 +34,19 @@ ...@@ -34,19 +34,19 @@
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":"getStorage", # "command":"getLog",
"payload":{ # "payload":{
"key":"recordList" # "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
...@@ -59,3 +59,13 @@ POST http://localhost:3000/broadcast/cmd HTTP/1.1 ...@@ -59,3 +59,13 @@ POST http://localhost:3000/broadcast/cmd HTTP/1.1
# "log_saved_days":7, # "log_saved_days":7,
# "user_fields":[1,2,3] # "user_fields":[1,2,3]
# } # }
# POST http://localhost:3000/fields/user/add HTTP/1.1
# content-type: application/json
# {
# "name":"userType",
# "type":"user"
# }
http://localhost:3000/fields/user/list?name=name
\ No newline at end of file \ No newline at end of file
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!