Commit a14c7f51 by 前端

Merge branch 'dev' into 'master'

上线合并

See merge request !2
2 parents a54baa38 45fb0783
Showing 60 changed files with 755 additions and 721 deletions
......@@ -4,8 +4,9 @@
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
DATABASE_URL="mysql://limin:limin1018@192.168.1.129:3306/app_admin?schema=public"
QIWEI_WEBHOOK='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=8541005c-5f60-416b-821e-64b4d872cd77'
DATABASE_URL="mysql://biz_app_admin:JLOVdxXk@192.168.3.222:3306/app_admin?schema=public"
QIWEI_WEBHOOK='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=16eaf975-65bc-4a7c-b744-a81f6236acc2'
SOCKET_PORT= 8080
APP_PORT= 3000
STATIC_PATH= "public"
\ No newline at end of file
STATIC_PATH = "public"
JWT_SECRET = 'secretKey'
\ No newline at end of file
......@@ -52,12 +52,15 @@
"@socket.io/redis-adapter": "^8.3.0",
"axios": "^1.7.7",
"bull": "^3.14.0",
"chalk": "4",
"class-transformer": "^0.3.1",
"class-validator": "^0.12.2",
"compressing": "^1.5.1",
"dayjs": "^1.11.13",
"global": "^4.4.0",
"mysql": "^2.18.1",
"nest-status-monitor": "^0.1.3",
"nest-winston": "^1.9.7",
"nestjs-config": "^1.4.6",
"nestjs-prisma": "^0.23.0",
"nodemailer": "^6.4.16",
......@@ -70,7 +73,9 @@
"rxjs": "^7.8.1",
"socket.io": "4.7.4",
"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": {
"@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
......@@ -8,38 +8,37 @@ datasource db {
}
model device {
id Int @id @default(autoincrement())
id Int @id @unique(map: "id") @default(autoincrement())
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_status device_status?
fields field_relation[]
logs file[]
log_config log_config?
}
model device_info {
id Int @id @default(autoincrement())
device_id Int @unique @default(0)
device_id Int @id @unique(map: "device_id") @default(0)
user String? @db.VarChar(20)
last_log_upload_time DateTime? @db.Timestamp(0)
last_log_remove_time DateTime? @db.Timestamp(0)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
mobile String? @db.VarChar(20)
merchant_name String? @db.VarChar(50)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_device_info_device")
device_status device_status?
logs file[]
log_config log_config?
}
model device_status {
device_id Int @id
device_id Int @id @unique(map: "device_id")
status Int @default(0) @db.TinyInt
last_login_time DateTime? @db.Timestamp(0)
last_offline_time DateTime? @db.Timestamp(0)
last_log_upload_time DateTime? @db.Timestamp(0)
last_log_remove_time DateTime? @db.Timestamp(0)
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK__device")
device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK__device_info")
}
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.
model file {
id Int @id @default(autoincrement())
device_id Int @default(0)
......@@ -48,38 +47,39 @@ model file {
filename String? @db.VarChar(100)
originalname String? @db.VarChar(255)
size Int? @default(0)
destination String? @db.VarChar(500)
created_at DateTime @default(now()) @db.Timestamp(0)
type String @default("other") @db.VarChar(10)
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_device")
device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_device_info")
@@index([device_id], map: "FK_file_device")
}
model log_config {
id Int @id @default(autoincrement())
device_id Int @unique @default(0)
device_id Int @id @unique(map: "device_id") @default(0)
log_saved_days Int? @default(7) @db.TinyInt
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
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")
user_fields log_config_userfield_relation[]
}
model log_config_userfield_relation {
id Int @id @default(autoincrement())
config_id Int @default(0)
user_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_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")
@@index([config_id], map: "FK_log_config_userfield_relation_log_config")
@@index([user_field_id], map: "FK_log_config_userfield_relation_log_user_field")
}
model log_user_field {
id Int @id @default(autoincrement())
model field {
id Int @id @unique(map: "id") @default(autoincrement())
name String @db.VarChar(20)
type String @default("user") @db.VarChar(10)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
log_config_userfield_relation log_config_userfield_relation[]
fields field_relation[]
}
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.
model field_relation {
id Int @id @default(autoincrement())
device_id Int?
field_id Int?
device device? @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK__field_relation_device")
field field? @relation(fields: [field_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK__field_relation_field")
@@index([device_id], map: "FK__field_relation_device")
@@index([field_id], map: "FK__field_relation_field")
}
......@@ -8,7 +8,7 @@ import statusMonitorConfig from './config/statusMonitor'
import { LoggerMiddleware } from './common/middleware/logger.middleware'
import { TasksModule } from './tasks/tasks.module'
// import { AudioModule } from './jobs/audio/audio.module'
// import { AuthModule } from './modules/auth/auth.module'
import { AuthModule } from './modules/auth/auth.module'
// import { HelloModule } from './modules/hello/hello.module'
import { DeviceModule } from './modules/device/device.module'
// import { ExceptionModule } from './modules/exception/exception.module'
......@@ -23,28 +23,35 @@ import { LogConfigModule } from './modules/config/config.module'
import { BroadcastModule } from './modules/broadcast/broadcast.module'
import { EventEmitterModule } from '@nestjs/event-emitter'
import { HttpModule } from '@nestjs/axios'
import { FieldsModule } from './modules/fields/fields.module'
import { WinstonModule } from 'nest-winston'
import winstonLogger from './initor/winstion.config'
import { JwtModule } from '@nestjs/jwt'
@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]
}),
WinstonModule.forRoot({
transports: winstonLogger.transports,
format: winstonLogger.format,
// defaultMeta: winstonLogger.defaultMeta,
exitOnError: false // 防止意外退出
}),
// TODO @nestjs/terminus almost the same
StatusMonitorModule.setUp(statusMonitorConfig),
// StatusMonitorModule.setUp(statusMonitorConfig),
// MailerModule.forRootAsync({
// useFactory: (config: ConfigService) => config.get('email'),
// inject: [ConfigService]
// }),
ScheduleModule.forRoot(),
EventEmitterModule.forRoot(),
DeviceModule,
TasksModule,
// AudioModule,
// AuthModule,
// HelloModule,
// ExceptionModule,
// RoleGuardModule,
......@@ -52,10 +59,11 @@ import { HttpModule } from '@nestjs/axios'
// UsersModule,
FileModule,
// SseModule,
AuthModule,
WsModule,
DeviceModule,
BroadcastModule,
LogConfigModule
LogConfigModule,
FieldsModule
]
})
export class AppModule {
......
......@@ -42,17 +42,29 @@ export enum WsAccess {
InvalidDeviceId = '无效设备id',
IsOnline = '通过验证,设备上线',
IsOffline = '设备下线',
ConnFailure = '设备连接失败,请检查设备号是否正确'
ConnFailure = '设备连接失败,请检查设备号是否正确',
TokenExpired = 'token已过期,请重新登录'
}
export enum WsAccessCode {
NotAllowed = 901,
InValidToken = 902,
InvalidDeviceId = 903,
IsOnline = 904,
IsOffline = 905,
ConnFailure = 906,
TokenExpired = 907
}
export enum Events {
OnConnected = 'device.connected',
OnConnectError = 'device.connect.error',
OnOfflineAll='device.offline.all',
OnMessage='client.mesage.received',
OnOfflineAll = 'device.offline.all',
OnMessage = 'client.mesage.received',
OnLogFileUploaded = 'log.file.uploaded',
OnLogFileRemoved='log.file.removed',
OnTaskStart='task.start'
OnLogFileRemoved = 'log.file.removed',
OnDailyTaskStart = 'task.daily.start',
OnSendMessage = 'client.message.send',
OnMessageToSendClient = 'message.send.to.client'
}
export enum DocTypes {
Log = 'log',
......@@ -60,14 +72,18 @@ export enum DocTypes {
Video = 'video',
Other = 'other'
}
export enum Command{
GetLog='getLog',
GetStorage='getStorage',
Message='message',
File='file'
export enum Command {
GetLog = 'getLog',
GetStorage = 'getStorage',
Message = 'message',
GetLogList = 'getLogList',
RemoveLog = 'removeLog',
RemoveRecord = 'removeRecord',
StopPolling = 'stopPolling',
StartPolling = 'startPolling',
SetPollingInterval = 'setPollingInterval'
}
export enum FileCommand{
GetList='getList',
Remove='remove'
export enum LogFieldTypes {
User = 'user'
}
import { WsAccess, WsAccessCode } from '../enums'
export class WsAccessException extends Error {
constructor(
public errMsg: WsAccess,
public errorCode: WsAccessCode
) {
super(errMsg)
}
}
import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
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: () => void) {
const { method, path , url,params,query } = req;
Logger.debug(`method -> ${method} url -> ${url} params -> ${JSON.stringify(params)} query -> ${JSON.stringify(query)}`);
next();
use(req: Request, res: Response, next: NextFunction): void {
const { method, url, originalUrl, baseUrl, query, body } = req
Logger.warn({ method, url, originalUrl, baseUrl, query, body })
next()
}
}
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'
import { Socket } from 'socket.io'
@Injectable()
export class PagesPipe implements PipeTransform<CommonTypes.IPageIn> {
......@@ -56,3 +57,4 @@ export class ParseIdPipe implements PipeTransform<any, any> {
return transformedValue
}
}
import { ArgumentMetadata, Injectable, PipeTransform } from "@nestjs/common"
import { Socket } from "socket.io"
import { WsAccess, WsAccessCode } from "../enums"
import { TokenExpiredError } from "@nestjs/jwt"
@Injectable()
export class WsConnParamPipe implements PipeTransform<any, any> {
transform(client: Socket, metadata: ArgumentMetadata): any {
// 创建一个新对象,以避免直接修改原始值
const transformedValue = { ...client }
const auth = client.handshake?.auth ?? client.handshake?.headers
const ValidateData: WsTypes.LoginValidate<WsAccess> = { isValidate: true, errMsg: WsAccess.IsOnline, errorCode: WsAccessCode.IsOnline }
if (!auth) {
ValidateData.isValidate = false
ValidateData.errMsg = WsAccess.NotAllowed
ValidateData.errorCode = WsAccessCode.NotAllowed
}
const { token, deviceId } = auth
// 注册用户
if (!token) {
ValidateData.isValidate = false
ValidateData.errMsg = WsAccess.InValidToken
ValidateData.errorCode = WsAccessCode.InValidToken
}
if (!deviceId) {
ValidateData.isValidate = false
ValidateData.errMsg = WsAccess.InvalidDeviceId
ValidateData.errorCode = WsAccessCode.InvalidDeviceId
}
return {transformedValue,ValidateData}
}
}
\ No newline at end of file
......@@ -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.debug('返回结果:', result)
Logger.warn(result)
return result
}
import { join,extname } from 'path';
import { diskStorage } from 'multer';
export default {
root: join(__dirname,'..','..',process.env.STATIC_PATH),
storage: diskStorage({
......
export default {
host: 'localhost',
host: '192.168.3.209',//测试环境
port: 6379,
}
\ No newline at end of file
import { ApiProperty } from '@nestjs/swagger'
import { Transform } from 'class-transformer'
import { IsOptional, isString, Matches, registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'
import { IsMobilePhone, IsOptional, isString, Matches, registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'
// 自定义验证装饰器
export function IsNumberOrNumberString(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
......@@ -13,10 +13,10 @@ 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
}
// 尝试将值转换为数字,如果转换成功或原本就是数字,则验证通过
// 注意:这里使用了 Number.isNaN 来检查转换结果是否为 NaN,从而排除非数字字符串
return !Number.isNaN(Number(value))
......@@ -60,3 +60,59 @@ export class BaseDto {
@IsNumberOrNumberString()
pageIndex?: number
}
export class TimeDto {
@ApiProperty({
type: Number,
description: '创建时间',
default: ''
})
created_at: Date
@ApiProperty({
type: Date,
description: '更新时间',
default: ''
})
updated_at: Date
}
export class UserBaseDto {
@ApiProperty({
type: String,
description: '设备用户',
default: ''
})
user: string
@IsMobilePhone('zh-CN', {}, { message: '手机号格式不正确' })
@IsOptional()
@ApiProperty({
type: String,
description: '使用者手机号',
default: ''
})
mobile: string
@ApiProperty({
type: String,
description: '使用者商户名称',
default: ''
})
merchant_name: string
}
export class SnDto {
@ApiProperty({
type: String,
description: '设备SN',
})
sn: string
}
export class DeviceIdDto {
@ApiProperty({
type: Number,
description: '设备ID',
})
device_id: number
}
\ No newline at end of file
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
......
import { ApiProperty } from "@nestjs/swagger"
import { Transform } from "class-transformer"
import { IsNotEmpty, IsNumber, isString, Matches } from "class-validator"
import { ApiProperty, IntersectionType, PartialType, PickType } from '@nestjs/swagger'
import { Transform } from 'class-transformer'
import { IsNotEmpty, IsNumber, isString, Matches } from 'class-validator'
import { DeviceIdDto, TimeDto } from './base.dto'
/*
model log_config {
......@@ -13,54 +14,13 @@ model log_config {
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[]
}*/
export class LogConfigDto {
@ApiProperty({
type: Number,
description: '设备信息ID',
required: false,
default: 0
})
id: number
@ApiProperty({
type: Number,
description: '设备ID',
required: true,
default: 0
})
@IsNotEmpty({ message: '设备ID不能为空' })
device_id: number
export class LogConfigDto extends IntersectionType(DeviceIdDto, PartialType(TimeDto)) {
@ApiProperty({
type: Number,
description: '日志保存天数',
required: false,
default: ''
})
log_saved_days: number
@ApiProperty({
type: Number,
description: '创建时间',
required: false,
default: ''
})
created_at: Date | string
@ApiProperty({
type: Date,
description: '更新时间',
required: false,
default: ''
})
updated_at: Date | string
@ApiProperty({
type: Array,
description: '需要上传的用户字段',
required: false,
default: []
})
user_fields: []
}
log_saved_days?: number
}
export class LogConfigUpdateDto extends PickType(LogConfigDto, ['log_saved_days']) {}
import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone, IsOptional } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger'
import { BaseDto } from './base.dto'
export class DeviceQueryDto extends BaseDto {
@ApiProperty({
type: String,
description: '设备SN',
required: false,
default: ''
})
sn?: string
@ApiProperty({
type: String,
description: '设备用户',
required: false,
default: ''
})
user?: string
@ApiProperty({
type: String,
description: '使用者手机号',
required: false,
default: ''
})
mobile?: string
}
export class AddDeviceDto {
@ApiProperty({
type: String,
description: '设备SN',
required: true,
default: ''
})
@MaxLength(20, { message: '设备SN不能超过20个字符' })
@IsNotEmpty({ message: '设备SN不能为空' })
sn: string
}
/**
* model device_info {
id Int @id @default(autoincrement())
device_id Int @unique(map: "device_id") @default(0)
user String? @db.VarChar(20)
status Int? @db.TinyInt
last_log_upload_time String? @db.VarChar(30)
last_log_remove_time String? @db.VarChar(30)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
mobile String? @db.VarChar(20)
merchant_name String? @db.VarChar(50)
log_config log_config?
}
*/
export class AddDeviceInfoDto {
@ApiProperty({
type: Number,
description: '设备信息ID',
default: 0
})
id: number
@ApiProperty({
type: Number,
description: '设备ID',
default: 0
})
@IsNumber({}, { message: '设备ID必须是数字' })
@IsNotEmpty({ message: '设备ID不能为空' })
device_id: number
@ApiProperty({
type: String,
description: '设备用户',
default: ''
})
user: string
import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone, IsOptional, isNotEmpty } from 'class-validator'
import { ApiProperty, IntersectionType, PartialType, PickType } from '@nestjs/swagger'
import { BaseDto, DeviceIdDto, SnDto, TimeDto, UserBaseDto } from './base.dto'
import { LogConfigUpdateDto } from './config.dto'
export class DeviceQueryDto extends PartialType(UserBaseDto) {
@ApiProperty({
type: Number,
description: '设备状态',
default: 0
description: '在线状态 1:在线,2:离线,0:弃用',
required: false
})
status: number
@ApiProperty({
type: String,
description: '最后一次上传日志的时间',
default: ''
})
last_log_upload_time: string
@ApiProperty({
type: String,
description: '最后一次移除日志的时间',
default: ''
})
last_log_remove_time: string
status?: number
}
@ApiProperty({
type: Number,
description: '创建时间',
default: ''
})
created_at: Date
export class DeviceFindOneDto extends PickType(UserBaseDto, ['user', 'mobile']) {}
@ApiProperty({
type: Date,
description: '更新时间',
default: ''
})
updated_at: Date
export class AddDeviceInfoDto extends IntersectionType(PartialType(SnDto),TimeDto) {
@IsMobilePhone('zh-CN', {}, { message: '手机号格式不正确' })
@IsOptional()
@ApiProperty({
type: String,
description: '使用者手机号',
default: ''
description: '设备信息 包括 user mobile merchant_name'
})
mobile: string
device_info?: UserBaseDto
@ApiProperty({
type: String,
description: '使用者商户名称',
default: ''
description: '设备配置信息 包括 log_saved_days'
})
merchant_name: string
log_config?: LogConfigUpdateDto
@ApiProperty({
type: Object,
description: '日志配置',
default: {}
description: '设备对应的日志字段集合 '
})
log_config: {}
user_fields?: Array<Number>
}
export class UpdateDeviceInfoDto extends IntersectionType(PartialType(AddDeviceInfoDto), DeviceIdDto) {}
......@@ -5,26 +5,44 @@ export class DeviceStatusDto {
@ApiProperty({
type: Number,
description: '设备ID',
default: 0
required: true,
})
@IsNumber({}, { message: '设备ID必须是数字' })
@IsNotEmpty({ message: '设备ID不能为空' })
device_id: number
@IsNumber({}, { message: '设备状态必须是数字' })
@IsNotEmpty({ message: '设备状态不能为空' })
@ApiProperty({
type: Number,
description: '设备状态',
default: 0
required: false,
})
status: number
status?: number
@IsNotEmpty({ message: 'SocketID不能为空' })
@ApiProperty({
type: String,
description: 'SocketID',
default: ''
description: '最后一次上传日志的时间',
required: false,
})
socket_id: string
last_log_upload_time?: string
@ApiProperty({
type: String,
description: '最后一次移除日志的时间',
required: false,
})
last_log_remove_time?: string
@ApiProperty({
type: String,
description: '最后一次登录时间',
required: false,
})
last_login_time?: string
@ApiProperty({
type: String,
description: '最后一次离线时间',
required: false,
})
last_offline_time?: string
}
import { ApiProperty, PartialType } 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 extends PartialType(CreateFieldDto) {}
......@@ -4,3 +4,4 @@ export * from './device.dto'
export * from './response.dto'
export * from './device.status.dto'
export * from './file.dto'
export * from './field.dto'
......@@ -5,6 +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())
......@@ -15,6 +16,7 @@ export default class Initializer {
// app.useGlobalFilters(new ValidateExceptionFilter())
// 全局管道
app.useGlobalPipes(new ValidationPipe())
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 formaters = [format.timestamp(), format.errors({ stack: true }), format.splat(), format.json(), winston.format.ms()]
const cfgRotage = {
dirname: join(__dirname, '..', '..', 'logs'),
datePattern: 'YYYY-MM-DD', // 日志轮换的频率,此处表示每天。
zippedArchive: true, // 是否通过压缩的方式归档被轮换的日志文件。
maxSize: '20m', // 设置日志文件的最大大小,m 表示 mb 。
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',
level: 'warn',
...cfgRotage
}),
new DailyRotateFile({
filename: 'logs/app/app-%DATE%.log',
...cfgRotage
}),
new transports.Console({
format: format.combine(
...formaters,
utilities.format.nestLike('', {
colors: true,
prettyPrint: true
})
),
level: 'debug'
})
]
})
import { Controller, Get, Post, Request, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { Body, Controller, Get, Post, Request, UseGuards, UseInterceptors, UsePipes, ValidationPipe } from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'
import { AuthService } from './auth.service'
import { RESPONSE_CODE } from '../../common/enums'
import { ApiTags } from '@nestjs/swagger'
import { TransformInterceptor } from '../../common/interceptors'
import { DeviceFindOneDto } from 'src/dto'
import { SnDto } from 'src/dto/base.dto'
@Controller()
@ApiTags('权限管理')
@Controller('device')
@UseInterceptors(TransformInterceptor)
@UsePipes(new ValidationPipe())
export class AuthController {
constructor(private readonly authService: AuthService) {}
// 登录测试
@UseGuards(AuthGuard('local'))
@Post('/auth/login')
async login(@Request() req) {
return this.authService.login(req.user);
// @UseGuards(AuthGuard('local'))
@Post('login')
async login(@Body() {sn}: SnDto): Promise<CommonTypes.IResData> {
const result: CommonTypes.IResData = await this.authService.validateSn(sn)
if (result.code === RESPONSE_CODE.SUCCESS) {
const token = this.authService.getTokenBySn({sn})
result.data.token = token
}
return result
}
// 测试登录后才可访问的接口,在需要的地方使用守卫,可保证必须携带token才能访问
@UseGuards(AuthGuard('jwt'))
@Get('me')
getProfile(@Request() req) {
return req.user;
return req.user
}
}
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { Module } from '@nestjs/common'
import { AuthService } from './auth.service'
import { PassportModule } from '@nestjs/passport'
import { JwtModule, JwtService } from '@nestjs/jwt'
// import { UsersModule } from '../users/users.module';
import { AuthController } from './auth.controller';
import { LocalStrategy } from './local.strategy';
import { JwtStrategy } from './jwt.strategy';
import { jwtConstants } from './constants';
import { AuthController } from './auth.controller'
import { LocalStrategy } from './local.strategy'
import { JwtStrategy } from './jwt.strategy'
import { jwtConstants } from './constants'
import { PrismaModule, PrismaService } from 'nestjs-prisma'
import { DeviceModule } from '../device/device.module'
@Module({
imports: [
// UsersModule,
PassportModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: jwtConstants.secret,
signOptions: { expiresIn: '60s' },
global: true,
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '24h' }
}),
PrismaModule,
DeviceModule
],
controllers: [AuthController],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService],
exports: [AuthService]
})
export class AuthModule {}
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Inject, Injectable } from '@nestjs/common'
import { JwtService, TokenExpiredError } from '@nestjs/jwt'
import { DeviceService } from '../device/device.service'
import { DeviceFindOneDto } from 'src/dto'
import { SnDto } from 'src/dto/base.dto'
@Injectable()
export class AuthService {
constructor(
// private readonly usersService: UsersService,
private readonly jwtService: JwtService,
private readonly deviceService: DeviceService,
@Inject(JwtService)
private readonly jwtService: JwtService
) {}
async validateUser(username: string, pass: string): Promise<any> {
// const user = await this.usersService.find(username);
const user = { name: 'walker123', password: '123321' };
if (user && user.password) {
const { password, ...result } = user;
return result;
async validateUser(user: DeviceFindOneDto): Promise<CommonTypes.IResData> {
return await this.deviceService.findOne(user)
}
return null;
async validateSn(sn:string): Promise<CommonTypes.IResData<CommonTypes.IId&CommonTypes.ISn>> {
return await this.deviceService.findOneBySn(sn)
}
async login(user: any): Promise<any> {
const payload = {username: user.username, sub: user.userId};
return {
access_token: this.jwtService.sign(payload),
};
getToken({ user, mobile }: DeviceFindOneDto): string {
return this.jwtService.sign({ user, mobile })
}
getTokenBySn({ sn }: SnDto): string {
return this.jwtService.sign({ sn })
}
verifyToken(token: string) {
let res: { isPass: boolean; error: any; data: any; isExpired: boolean } = { isPass: true, error: null, data: null, isExpired: false }
try {
const verify = this.jwtService.verify(token)
if (verify) {
res.data = verify
}
} catch (error) {
res = { isPass: false, error, data: null, isExpired: false }
if (error instanceof TokenExpiredError) {
res.isExpired = true
}
}
return res
}
}
......@@ -7,7 +7,7 @@ import { jwtConstants } from './constants';
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromHeader('token'),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),//ExtractJwt.fromHeader('token'),
ignoreExpiration: false,
secretOrKey: jwtConstants.secret,
});
......
......@@ -2,6 +2,7 @@ import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { AuthService } from './auth.service';
import { DeviceFindOneDto } from '../../dto';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
......@@ -9,16 +10,13 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
super();
}
async validate(username: string, password: string): Promise<any> {
// tslint:disable-next-line
console.log(username, password)
return {username, password};
const user = await this.authService.validateUser(username, password);
if (!user) {
async validate(user: DeviceFindOneDto): Promise<any> {
const device = await this.authService.validateUser(user);
if (!device) {
throw new HttpException(
{ message: 'authorized failed', error: 'please try again later.' },
HttpStatus.BAD_REQUEST);
}
return user;
return device;
}
}
import { Controller, Post, Body, UseInterceptors, UsePipes, Logger } from '@nestjs/common'
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'
......@@ -14,10 +13,9 @@ import { Events } from '../../common/enums'
@UsePipes(new ValidationPipe()) // 使用管道验证
export class BroadcastController {
/**
* @param wsGateway - WsGateway实例
*
*/
constructor(
private readonly wsGateway: WsGateway,
private readonly broadcastService: BroadcastService
) {}
......@@ -28,12 +26,13 @@ export class BroadcastController {
*/
@Post('/cmd')
@ApiOperation({ summary: '给设备发送指令' })
@UsePipes(new ParseDeviceIdPipe())
async message(@Body() params: BroadcastDto): Promise<CommonTypes.IResData> {
return this.wsGateway.send(params)
return this.broadcastService.send(params)
}
@OnEvent(Events.OnMessage)
onMessage(@Body() params: any): Promise<CommonTypes.IResData> {
Logger.debug('收到私有订阅消息:', params)
Logger.warn(params)
return this.broadcastService.onMessage(params)
}
}
import { Module } from '@nestjs/common'
import { BroadcastController } from './broadcast.controller'
import { BroadcastService } from './broadcast.service'
import { WsModule } from '../ws/ws.module';
import { WsService } from '../ws/ws.service';
import { HttpModule } from '@nestjs/axios';
import { WsModule } from '../ws/ws.module';
@Module({
imports: [WsModule,HttpModule],
imports: [HttpModule,WsModule],
controllers: [BroadcastController],
providers: [BroadcastService,WsService]
providers: [BroadcastService]
})
export class BroadcastModule {}
......@@ -2,8 +2,9 @@ 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, WsMessageType } from '../../common/enums'
import { EventEmitter2 } from '@nestjs/event-emitter'
import { WsGateway } from '../ws/ws.gateway'
@Injectable()
export class BroadcastService {
private webHook: string
......@@ -11,15 +12,23 @@ export class BroadcastService {
private readonly httpService: HttpService,
private readonly config: ConfigService,
@Inject(EventEmitter2)
private readonly eventEmitter: EventEmitter2
private readonly eventEmitter: EventEmitter2,
private readonly wsGateway: WsGateway
) {
this.webHook = this.config.get('env').AppWebhook
}
async send(message: WsTypes.MessageBody<Command, WsMessageType>): Promise<CommonTypes.IResData> {
// const success = await this.eventEmitter.emitAsync(Events.OnMessageToSendClient, message)
return this.wsGateway.send(message)
// return { code: success ? RESPONSE_CODE.SUCCESS : RESPONSE_CODE.NOSUCCESS, data: { success } }
}
// // 广播消息
async onMessage(param: any): Promise<CommonTypes.IResData> {
if (param?.code === RESPONSE_CODE.SUCCESS && param?.data?.command === Command.File && param?.data?.payload?.command === FileCommand.Remove) {
this.eventEmitter.emit(Events.OnLogFileRemoved, { device_id: param.device_id, last_log_remove_time: new Date() })
return
if (param?.code == RESPONSE_CODE.SUCCESS && param?.data?.command === Command.RemoveLog) {
const statusInfo: DeviceStatus.IDeviceStatus = { device_id: param.device_id, last_log_remove_time: new Date() }
this.eventEmitter.emit(Events.OnLogFileRemoved, statusInfo)
}
const res: AxiosResponse<any, any> = await this.httpService
.post(this.webHook, {
......
......@@ -16,12 +16,12 @@ export class ConfigController {
@UsePipes(new PagesPipe())
@UsePipes(new ParseDeviceIdPipe())
@ApiOperation({ summary: '根据设备号获取配置' })
async findAll(@Query() params: LogConfigDto): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> {
async findAll(@Query() params: LogConfigDto): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResult[]>> {
return this.configService.findAll(params)
}
@Post('/add')
@ApiOperation({ summary: '新增设备配置' })
addConfig(@Body() param: LogConfigDto): Promise<CommonTypes.IResData> {
return this.configService.addConfig(param)
@ApiOperation({ summary: '新增或更新设备配置,de' })
upsertConfig(@Body() param: LogConfigDto): Promise<CommonTypes.IResData> {
return this.configService.upsertConfig(param)
}
}
import { Module } from '@nestjs/common'
import { ConfigController } from './config.controller'
import { ConfigService } from './config.service'
import { PrismaService } from 'nestjs-prisma'
import { PrismaModule, PrismaService } from 'nestjs-prisma'
@Module({
imports: [PrismaModule],
controllers: [ConfigController],
providers: [ConfigService,PrismaService]
providers: [ConfigService]
})
export class LogConfigModule {}
......@@ -7,7 +7,7 @@ export class ConfigService {
@Inject(PrismaService)
private readonly prisma: PrismaService // private connection: Connection,
) {}
async findAll({ device_id, skip, take }: ConfigTypes.LogConfigQuery): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> {
async findAll({ device_id, skip, take }: ConfigTypes.LogConfigQuery): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResult[]>> {
const where: any = {
device_id
}
......@@ -15,62 +15,21 @@ export class ConfigService {
skip,
take,
select: {
id: true,
device_id: true,
log_saved_days: true,
user_fields: {
select: {
log_user_field: {
select: {
name: true
}
}
}
}
log_saved_days: true
},
where
})
const data: ConfigTypes.LogConfigResponse[] = result.map(item => {
return {
id: item.id,
device_id: item.device_id,
log_saved_days: item.log_saved_days,
user_fields: item.user_fields.map(item => item.log_user_field.name)
}
})
const total = await this.prisma.log_config.count({
where
})
const resBody: CommonTypes.IResData<ConfigTypes.LogConfigResponse[]> = { total, data }
const resBody: CommonTypes.IResData<ConfigTypes.LogConfigResult[]> = { total, data: result, code: RESPONSE_CODE.SUCCESS, message: '查询成功' }
return resBody
}
async addConfig(config: ConfigTypes.LogConfigAdd): Promise<CommonTypes.IResData> {
const { user_fields, ...data } = config
let config_id: number = 0
await this.prisma.$transaction(async prisma => {
const date = new Date()
const { id } = (await prisma.log_config.findUnique({ where: { device_id: data.device_id }, select: { id: true } })) || {}
config.updated_at = date
if (id) {
config_id = id
await prisma.log_config.update({ where: { device_id: data.device_id }, data })
await prisma.log_config_userfield_relation.deleteMany({ where: { config_id: id } })
} else {
config.created_at = date
const { id } = await prisma.log_config.create({ data, select: { id: true } })
config_id = id
}
const relations: RelationsTypes.LogConfigUserFieldsRel[] = user_fields.map((ufid: number) => {
return {
config_id,
user_field_id: ufid
}
})
await prisma.log_config_userfield_relation.createMany({ data: relations, skipDuplicates: true })
})
async upsertConfig(config: Partial<ConfigTypes.ILogConfig>): Promise<CommonTypes.IResData> {
const now = new Date()
await this.prisma.log_config.upsert({ where: { device_id: config.device_id }, update: { ...config, updated_at: now }, create: { ...config, created_at: now, updated_at: now } })
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
}
}
import { Controller, Get, Post, Body, UseInterceptors, Query, UsePipes, Inject } from '@nestjs/common'
import { DeviceService } from './device.service'
import { TransformInterceptor } from '../../common/interceptors'
import { AddDeviceDto, AddDeviceInfoDto, DeviceQueryDto, DeviceStatusDto } from '../../dto'
import { AddDeviceInfoDto, DeviceFindOneDto, DeviceQueryDto, DeviceStatusDto, UpdateDeviceInfoDto } 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('设备管理')
......@@ -34,10 +34,13 @@ export class DeviceController {
@Get()
@UsePipes(new PagesPipe())
@ApiOperation({ summary: '获取所有设备列表' })
findAll(@Query() params: DeviceQueryDto): Promise<CommonTypes.IResData> {
return this.deviceService.findAll(params)
async findAll(@Query() params: DeviceQueryDto): Promise<CommonTypes.IResData> {
return await this.deviceService.findAll(params)
}
async finOne(@Query() params: DeviceFindOneDto): Promise<CommonTypes.IResData> {
return await this.deviceService.findOne(params)
}
/**
* 添加设备的方法
* 该方法接收一个包含设备信息的DTO对象,并返回添加后的设备信息
......@@ -46,9 +49,8 @@ export class DeviceController {
*/
@Post('/add')
@ApiOperation({ summary: '添加设备' })
addDevice(@Body() param: AddDeviceDto): Promise<CommonTypes.IResponseBase> {
// console.log(param)
return this.deviceService.addDevice(param)
async addDevice(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> {
return await this.deviceService.addDevice(param)
}
/**
* 添加设备信息的方法
......@@ -58,10 +60,10 @@ export class DeviceController {
*/
@Post('/addInfo')
@ApiOperation({ summary: '添加设备信息' })
addDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> {
// console.log(param)
return this.deviceService.addDeviceInfo(param)
async addDeviceInfo(@Body() param: UpdateDeviceInfoDto): Promise<CommonTypes.IResData> {
return await this.deviceService.addDeviceInfo(param)
}
/**
* 更新设备信息的方法
* 该方法接收一个包含设备信息的DTO对象,并返回更新后的设备信息
......@@ -70,9 +72,8 @@ export class DeviceController {
*/
@Post('/updateInfo')
@ApiOperation({ summary: '修改设备信息' })
@OnEvent(Events.OnLogFileRemoved)
updateDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> {
return this.deviceService.updateDeviceInfo(param)
async updateDeviceInfo(@Body() param: UpdateDeviceInfoDto): Promise<CommonTypes.IResData> {
return await this.deviceService.updateDeviceInfo(param)
}
/**
......@@ -81,15 +82,21 @@ export class DeviceController {
* @param param - 包含设备状态的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@OnEvent(Events.OnConnected)
@Post('/upsertStatus')
@OnEvent(Events.OnConnected)
@ApiOperation({ summary: '更新设备状态' })
async upsertDeviceStatus(@Body() param: DeviceStatusDto): Promise<void | CommonTypes.IResponseBase> {
async upsertDeviceStatus(@Body() param: DeviceStatusDto): Promise<void | CommonTypes.IResData> {
return await this.deviceService.upsertDeviceStatus(param).catch(error => {
const out: WsTypes.WsConnError = { message: WsAccess.ConnFailure, device_id: param.device_id }
this.eventEmitter.emit(Events.OnConnectError, out)
})
}
@Post('/upsertFileRemovedTime')
@OnEvent(Events.OnLogFileRemoved)
@ApiOperation({ summary: '更新设备状态' })
async upsertFileRemovedTime(@Body() param: DeviceStatusDto): Promise<void | CommonTypes.IResData> {
return await this.deviceService.upsertFileRemovedTime(param)
}
/**
* 重置所有设备状态的方法
......@@ -100,19 +107,19 @@ export class DeviceController {
@Post('/offlineAll')
@OnEvent(Events.OnOfflineAll)
@ApiOperation({ summary: '修改所有设备状态为离线' })
async resetAllDeviceStatus(): Promise<void | CommonTypes.IResponseBase> {
async resetAllDeviceStatus(): Promise<void | CommonTypes.IResData> {
return await this.deviceService.resetAllDeviceStatus()
}
@Get('/task')
@OnEvent(Events.OnTaskStart)
@ApiOperation({ summary: '日任务' })
@OnEvent(Events.OnDailyTaskStart)
@ApiOperation({ summary: '每日任务' })
async task(): Promise<void | CommonTypes.IResData> {
return await this.deviceService.removeFilesTask()
}
@Get('/addAll')
@ApiOperation({ summary: '批量导入设备,用于初始化数据' })
async addAll(devices: Array<any>): Promise<void | CommonTypes.IResponseBase> {
async addAll(devices: Array<any>): Promise<void | CommonTypes.IResData> {
// return this.deviceService.addAll(devices)
}
}
import { Module } from '@nestjs/common';
import { DeviceController } from './device.controller';
import { DeviceService } from './device.service';
import { PrismaService } from 'nestjs-prisma';
import { WsModule } from '../ws/ws.module';
import { WsService } from '../ws/ws.service';
// import { EventEmitter2 } from '@nestjs/event-emitter';
import { PrismaModule } from 'nestjs-prisma';
@Module({
imports: [WsModule],
imports: [PrismaModule],
controllers: [DeviceController],
providers: [DeviceService,PrismaService,WsService],
providers: [DeviceService],
exports: [DeviceService],
})
export class DeviceModule {}
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 { PrismaModule, PrismaService } from 'nestjs-prisma';
@Module({
imports: [
PrismaModule
],
controllers: [FieldsController],
providers: [FieldsService],
})
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, orderBy: { created_at: 'desc' } })
const total = await this.prismaService.field.count({ where })
return { code: RESPONSE_CODE.SUCCESS, message: '查询成功', total, data: result }
}
}
......@@ -8,6 +8,7 @@ import { DocTypes } from '../../common/enums'
import { FileDeleteDto, FileQueryDto } from '../../dto'
import { ApiOperation, ApiTags } from '@nestjs/swagger'
import { FilePathPipe, PagesPipe, ParseDeviceIdPipe, ParseIdPipe } from '../../common/pipes'
import { join } from 'path'
@ApiTags('文件管理')
@UsePipes(new ValidationPipe())
@Controller('file')
......@@ -29,13 +30,12 @@ export class FileController {
@Post('upload')
@UsePipes(new FilePathPipe())
@ApiOperation({ summary: '文件上传' })
@UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain'), limits: { fileSize: 1024 * 1024 * 100 } })
upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request): FileTypes.FileUpload<DocTypes> {
const { fieldname, encoding, destination, stream, buffer, path, ...o } = file
@UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain') })
async upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request): Promise<CommonTypes.IResData<FileTypes.FileUpload<DocTypes>>> {
const { fieldname, encoding, stream, buffer, path: origin_path, ...o } = file
const bodyData: Pick<FileTypes.FileUpload<DocTypes>, 'device_id' | 'type'> = { device_id: Number(req.body.deviceId), type: req.body.type }
const f: FileTypes.FileUpload<DocTypes> = Object.assign({ created_at: new Date(), path: `${req.protocol}://${req.get('Host')}${path}` }, bodyData, o)
this.fileService.save(f)
return f
const f: FileTypes.FileUpload<DocTypes> = Object.assign({ created_at: new Date(), path: `${req.protocol}://${req.get('Host')}${origin_path}` }, bodyData, o)
return await this.fileService.save(f)
}
/**
......
......@@ -3,7 +3,7 @@ import { MulterModule } from '@nestjs/platform-express';
import { ConfigService } from 'nestjs-config';
import { FileController } from './file.controller';
import { FileService } from './file.service';
import { PrismaService } from 'nestjs-prisma';
import { PrismaModule, PrismaService } from 'nestjs-prisma';
@Module({
imports: [
......@@ -11,8 +11,9 @@ import { PrismaService } from 'nestjs-prisma';
useFactory: (config: ConfigService) => config.get('file'),
inject: [ConfigService],
}),
PrismaModule
],
controllers: [FileController],
providers: [FileService,PrismaService],
providers: [FileService],
})
export class FileModule {}
import { Inject, Injectable } from '@nestjs/common'
import { Inject, Injectable, Logger } from '@nestjs/common'
import { tar } from 'compressing'
import { ConfigService } from 'nestjs-config'
import * as fs from 'fs'
......@@ -6,6 +6,7 @@ import * as path from 'path'
import { DocTypes, RESPONSE_CODE } from '../../common/enums'
import { PrismaService } from 'nestjs-prisma'
import { Doc } from 'prettier'
import { join } from 'path'
@Injectable()
export class FileService {
......@@ -37,7 +38,8 @@ export class FileService {
contains: filename
}
}
const files: FileTypes.IFile<DocTypes | string>[] = await this.prisma.file.findMany({ skip, take, where })
const files: FileTypes.IFile<DocTypes | string>[] = await this.prisma.file.findMany({ skip, take, where, orderBy: { created_at: 'desc' } })
const total: number = await this.prisma.file.count({
where
})
......@@ -51,18 +53,25 @@ export class FileService {
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/
async save(file: FileTypes.FileUpload<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 } })) || {}
if (id) {
fs.unlinkSync(origin_path)
await prisma.file.update({ where: { id }, data: { filename, path, created_at } })
const { filename, path, created_at, destination, size, ...where } = file
await this.prisma.$transaction(async prisma => {
const files: Pick<FileTypes.IFile<DocTypes>, 'id' | 'destination' | 'filename'>[] = await prisma.file.findMany({ where, select: { id: true, destination: true, filename: true } })
if (files?.length) {
files.forEach(async ({ id, destination: dest, filename: fname }) => {
const origin_path = join(dest, fname)
try {
fs.existsSync(origin_path) && fs.unlinkSync(origin_path)
} catch (err) {
Logger.error('删除文件失败', err)
}
await prisma.file.update({ where: { id }, data: { filename, path, created_at, destination } })
})
} else {
await prisma.file.create({ data: file })
}
await prisma.device_info.update({ where: { device_id: file.device_id }, data: { last_log_upload_time: created_at } })
await prisma.device_status.update({ where: { device_id: file.device_id }, data: { last_log_upload_time: created_at } })
})
return { code: RESPONSE_CODE.SUCCESS, message: '文件保存成功' }
return { code: RESPONSE_CODE.SUCCESS, message: '文件保存成功', data: { path: file.path } }
}
/**
......
......@@ -3,9 +3,12 @@ import { from, Observable } from 'rxjs'
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, Command } from '../../common/enums'
import { Inject, Logger, Module, UseInterceptors, UsePipes } from '@nestjs/common'
import { WsMessageType, WsStatus, WsAccess, Command, WsAccessCode, Events } from '../../common/enums'
import { TransformInterceptor } from '../../common/interceptors'
import { JwtService, TokenExpiredError } from '@nestjs/jwt'
import { AuthService } from '../auth/auth.service'
import { OnEvent } from '@nestjs/event-emitter'
/**
* WebSocket 网关
......@@ -25,7 +28,10 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
*
* @param wsService - 注入的 WebSocket 服务实例,用于处理 WebSocket 相关操作。
*/
constructor(public readonly wsService: WsService) {}
constructor(
public readonly wsService: WsService,
private readonly authService: AuthService
) {}
/**
* WebSocket 服务器实例
*/
......@@ -39,7 +45,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
@SubscribeMessage(WsMessageType.Private)
subPrivate(@MessageBody() data: any): Observable<WsResponse<string>> {
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 })))
}
/**
......@@ -56,36 +62,36 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* @param client client
* @param args
*/
handleConnection(client: Socket, ...args: any[]): WsTypes.IWsResponse<WsStatus, WsAccess> {
handleConnection(client: Socket): WsTypes.IWsResponse<WsStatus, WsAccess> {
const auth = client.handshake?.auth ?? client.handshake?.headers
const ValidateData: WsTypes.LoginValidate<WsAccess> = { isValidate: true, errMsg: WsAccess.IsOnline }
if (!auth) {
ValidateData.isValidate = false
ValidateData.errMsg = WsAccess.NotAllowed
return this.handleInvalidAuth(client, WsAccess.NotAllowed, WsAccessCode.NotAllowed)
}
const { token, deviceId } = auth
// 注册用户
if (!token) {
ValidateData.isValidate = false
ValidateData.errMsg = WsAccess.InValidToken
return this.handleInvalidAuth(client, WsAccess.InValidToken, WsAccessCode.InValidToken)
}
if (!deviceId) {
ValidateData.isValidate = false
ValidateData.errMsg = WsAccess.InvalidDeviceId
return this.handleInvalidAuth(client, WsAccess.InvalidDeviceId, WsAccessCode.InvalidDeviceId)
}
if (!ValidateData.isValidate) {
const msg = `${ValidateData.errMsg} token->${token} deviceId->${deviceId}}`
client.emit(WsMessageType.Private, msg)
Logger.error(msg)
const resData: WsTypes.IWsResponse<WsStatus, WsAccess> = {
status: WsStatus.Offline,
message: ValidateData.errMsg,
device_id: deviceId
const verify = this.authService.verifyToken(String(token))
if (!verify.isPass) {
const errorCode = verify.isExpired ? WsAccessCode.TokenExpired : WsAccessCode.InValidToken
return this.handleInvalidAuth(client, WsAccess.TokenExpired, errorCode)
}
return this.wsService.login(client, token, deviceId)
}
private handleInvalidAuth(client: Socket, errMsg: WsAccess, errorCode: WsAccessCode): WsTypes.IWsResponse<WsStatus, WsAccess> {
const msg = `${errMsg} token->${client.handshake.auth?.token} deviceId->${client.handshake.auth?.deviceId}`
Logger.error(msg)
client.emit(WsMessageType.Private, { isValidate: false, errMsg, errorCode })
client.disconnect()
return resData
return {
status: WsStatus.Offline,
message: errMsg,
device_id: client.handshake.auth?.deviceId
}
return this.wsService.login(client, token, deviceId)
}
/**
......@@ -103,7 +109,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* @param 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
// 重置 socketIds
this.wsService.resetClients()
......@@ -113,7 +119,14 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* 发送消息
* @param payload
*/
public send(payload: WsTypes.MessageBody<WsTypes.WsMessageData<Command>, WsMessageType>): Promise<CommonTypes.IResData> {
@OnEvent(Events.OnMessageToSendClient)
public send(payload: WsTypes.MessageBody<Command, WsMessageType>): Promise<CommonTypes.IResData> {
return this.wsService[{ [WsMessageType.Private]: 'sendPrivateMessage', [WsMessageType.System]: 'sendPublicMessage' }[payload.event]](payload)
}
@OnEvent(Events.OnConnectError)
async onConnectError(out: WsTypes.WsConnError): Promise<void> {
return this.wsService.onConnectError(out)
}
}
import { Module } from '@nestjs/common'
import { WsGateway } from './ws.gateway'
import { WsService } from './ws.service'
// import { DeviceService } from '../device/device.service'
import { AuthModule } from '../auth/auth.module'
@Module({
imports: [],
imports: [AuthModule],
providers: [WsGateway, WsService],
exports: [WsGateway]
})
......
import { HttpException, HttpStatus, Injectable, Inject } from '@nestjs/common'
import { HttpException, HttpStatus, Injectable, Inject, OnModuleDestroy, OnApplicationShutdown } from '@nestjs/common'
import { Server, Socket } from 'socket.io'
import { Logger } from '@nestjs/common'
import { RESPONSE_CODE, WsAccess, Events, WsMessageType, WsStatus } from '../../common/enums'
import { RESPONSE_CODE, WsAccess, Events, WsMessageType, WsStatus, Command } from '../../common/enums'
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'
@Injectable()
......@@ -25,15 +25,11 @@ export class WsService {
login(client: Socket, token: string, deviceId: number): WsTypes.IWsResponse<WsStatus, WsAccess> {
const clientIsOnline: Socket = this.findClientByDeviceId(deviceId)
// 处理同一设备号在多处登录
if (clientIsOnline) {
clientIsOnline.emit(WsMessageType.System, `设备-> ${deviceId} 已在别处上线, 此客户端 [${clientIsOnline.id}] 下线处理`)
clientIsOnline?.disconnect()
Logger.debug(`设备-> ${deviceId} 重复登录, [${clientIsOnline.id}] 先登录的设备下线处理`)
}
this.handleDuplicateLogin(clientIsOnline, deviceId)
// 保存工号
this.clientIds.set(deviceId, client.id)
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)
const resData: WsTypes.IWsResponse<WsStatus, WsAccess> = {
device_id: deviceId,
......@@ -44,6 +40,19 @@ export class WsService {
return resData
}
/**
* 处理重复登录
* @param clientIsOnline 已经在线的客户端
* @param deviceId 设备ID
*/
private handleDuplicateLogin(clientIsOnline: Socket, deviceId: number) {
if (clientIsOnline) {
clientIsOnline.emit(WsMessageType.Private, `设备-> ${deviceId} 已在别处上线, 此客户端 [${clientIsOnline.id}] 下线处理`)
clientIsOnline.disconnect()
Logger.warn(`设备-> ${deviceId} 重复登录, [${clientIsOnline.id}] 先登录的设备下线处理`)
}
}
private findClientByDeviceId(deviceId: number): Socket {
return this.allClients?.get(this.clientIds.get(deviceId))
}
......@@ -51,7 +60,6 @@ export class WsService {
private get allClients(): Map<string, Socket> {
return this.server?.sockets?.sockets
}
/**
* 登出
* @param client client
......@@ -61,15 +69,14 @@ export class WsService {
for (let [deviceId, clientId] of this.clientIds) {
if (clientId === id) {
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 })
break
}
}
return { data: { code: RESPONSE_CODE.SUCCESS, message: '登出成功' } }
}
@OnEvent(Events.OnConnectError)
async onConnError(out: WsTypes.WsConnError): Promise<void> {
async onConnectError(out: WsTypes.WsConnError): Promise<void> {
const { device_id, message } = out
const client: Socket = this.findClientByDeviceId(device_id)
if (client) {
......@@ -88,7 +95,7 @@ export class WsService {
*/
resetClients(): void {
this.clientIds.clear()
Logger.debug('===WebSocket初始化成功!重置所有客户端连接数据===')
Logger.warn('========WebSocket初始化成功!重置所有客户端连接数据========')
}
/**
......@@ -96,13 +103,13 @@ export class WsService {
* @param messagePath 发布地址
* @param response 响应数据
*/
async sendPublicMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResData> {
async sendPublicMessage(payload: WsTypes.MessageBody<Command>): Promise<CommonTypes.IResData> {
const res = this.server?.emit(WsMessageType.System, payload.data)
if (!res) {
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: '发送成功' }
}
......@@ -112,18 +119,18 @@ export class WsService {
* @param response 响应数据
* @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)
async sendPrivateMessage(payload: WsTypes.MessageBody<Command>): Promise<CommonTypes.IResData> {
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){
this.emit(Events.OnMessage,message)
onMessage(message: any) {
this.emit(Events.OnMessage, message)
}
}
import { Inject, Injectable, Logger } from '@nestjs/common';
import { Cron, Interval, Timeout } from '@nestjs/schedule';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Events } from '../common/enums';
import { Inject, Injectable, Logger } from '@nestjs/common'
import { Cron, Interval, Timeout } from '@nestjs/schedule'
import { EventEmitter2 } from '@nestjs/event-emitter'
import { Events } from '../common/enums'
@Injectable()
export class TasksService {
private readonly logger = new Logger(TasksService.name);
constructor(
@Inject(EventEmitter2)
private eventEmitter: EventEmitter2
){}
@Cron('0 10 * * * *')
) {}
@Cron('0 10 0 * * *')
handleCron() {
this.eventEmitter.emit(Events.OnTaskStart)
Logger.debug('============开始定时任务=============');
this.eventEmitter.emit(Events.OnDailyTaskStart)
Logger.warn('============开始每日定时任务=============')
}
// @Interval(5000)
......@@ -23,7 +22,7 @@ export class TasksService {
// @Timeout(5000)
// handleTimeout() {
// this.logger.debug('Called once after 5 seconds');
// this.Logger.debug('Called once after 5 seconds');
// this.deviceService.removeFilesTask()
// }
}
declare module Broadcastypes {
import { Command } from '../common/enums'
declare namespace Broadcastypes {
type MessageData<T extends Command> = T extends Command.RemoveLog ? Required<Pick<WsTypes.MessageData<Command.RemoveLog>, 'days'>> & Omit<MessageData<T>, 'days'> : T extends Command.RemoveRecord ? Required<Pick<WsTypes.MessageData<Command.RemoveRecord>, 'id'>> & Omit<MessageData<T>, 'id'> : T extends Command.GetStorage ? Required<Pick<WsTypes.MessageData<Command.GetStorage>, 'key'>> & Omit<MessageData<T>, 'key'> : T extends Command.SetPollingInterval ? Required<Pick<WsTypes.MessageData<Command.SetPollingInterval>, 'interval'>> & Omit<MessageData<T>, 'interval'> : WsTypes.MessageBody<T>
}
......@@ -104,11 +104,12 @@ declare namespace CommonTypes {
updated_at: Date | string
}
interface ISn {
sn: string
}
interface IUser extends IDeviceId, ISn {
interface IUser {
user: string
mobile: string
merchant_name: string
......
......@@ -11,13 +11,11 @@ model log_config {
}*/
declare namespace ConfigTypes {
interface ILogConfig extends CommonTypes.IId, CommonTypes.IDeviceId, CommonTypes.ITime {
interface ILogConfig extends CommonTypes.IDeviceId, CommonTypes.ITime {
log_saved_days: number
user_fields: DeviceTypes.ILogUserFields[]
// fields: DeviceTypes.IFields[]
}
type LogConfigQuery = Pick<Partial<ILogConfig>, 'device_id'> & CommonTypes.IQueryBase
type LogConfigAdd = Omit<Partial<ILogConfig>, 'id' | 'user_fields'> & { user_fields: number[] }
type LogConfigResult = Partial<ILogConfig>
type LogConfigResponse = Omit<LogConfigResult, 'user_fields'> & { user_fields: string[] }
type LogConfigUpdate = CommonTypes.Optional<ILogConfig, 'device_id'>
}
declare namespace DeviceTypes {
/**
* 查询设备信息的查询对象接口
*
* @param user - 用户
* @param mobile - 手机号
* @param sn - 设备号
* @param skip - 可选,跳过的记录数量
* @param take - 可选,获取的记录数量
*/
type IQueryDevices = Partial<CommonTypes.IQueryBase & CommonTypes.ISn & IDeviceInfoBase>
type IQueryDevices = Partial<CommonTypes.IQueryBase & CommonTypes.ISn & CommonTypes.IUser & Pick<DeviceStatus.Status, 'status'>>
interface IDeviceInfoBase extends CommonTypes.IUser {
/**
* 日志保存天数
*/
log_saved_days?: number
}
/**
* 设备信息接口
*/
interface IDeviceInfo extends Omit<IDeviceInfoBase,'device_id'>, CommonTypes.PartialOne<IDevice, 'id'>, DeviceStatus.Status {
/**
* 日志用户字段
*/
log_user_fields?: string[]
}
/**
* model device_info {
id Int @id @default(autoincrement())
device_id Int @unique(map: "device_id") @default(0)
user String? @db.VarChar(20)
status Int? @db.TinyInt
last_log_upload_time String? @db.VarChar(30)
last_log_remove_time String? @db.VarChar(30)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
mobile String? @db.VarChar(20)
merchant_name String? @db.VarChar(50)
log_config log_config?
}
*/
interface IDeviceInfoInput extends IDeviceInfoBase, CommonTypes.IId, CommonTypes.IDeviceId, CommonTypes.ITime {
last_log_upload_time?: string
last_log_remove_time?: string
}
type TDeviceInfo = CommonTypes.ITime & Partial<CommonTypes.IUser>
type UpdateDeviceInfo = CommonTypes.Optional<IDeviceInfoInput, 'device_id'>
/**
* 表示设备结果的接口
*/
interface IDeviceResult extends IDevice {
/**
* 与设备关联的详细信息
*/
device_info: IDeviceInfoRes
}
interface IDevice extends CommonTypes.IId,CommonTypes.ISn {
type TOneDeviceInfo = TDeviceInfo & CommonTypes.IDeviceId
/**
* 设备创建的时间戳
*/
create_time?: number
interface IDevice extends CommonTypes.IId, CommonTypes.ISn, DeviceStatus.Status, Partial<TDeviceInfo>, Partial<ConfigTypes.ILogConfig> {
fields: FieldTypes.TFieldRequird[]
}
/**
* 表示设备详细信息的接口
*/
interface IDeviceInfoRes extends CommonTypes.PartialOne<Omit<IDeviceInfoBase,'device_id'>,'sn'>, CommonTypes.PartialOne<IDeviceInfoInput, 'created_at' | 'updated_at' | 'id' | 'device_id'|'sn'> {
/**
* 与设备关联的日志配置信息
*/
interface IDeviceResult extends CommonTypes.IId, CommonTypes.ISn, Partial<Pick<CommonTypes.ITime, 'created_at'>> {
device_info: Partial<TDeviceInfo>
log_config: Partial<ConfigTypes.ILogConfig>
device_status: DeviceStatus.Status
fields: IFields[]
}
/**
* 表示日志配置的接口
*/
interface ILogConfig {
/**
* 日志保存的天数
*/
log_saved_days: number
/**
* 日志用户字段的配置信息
*/
user_fields: ILogUserFields[]
interface IDeviceSaves extends CommonTypes.IDeviceId, Partial<CommonTypes.ISn> {
device_info?: Partial<TDeviceInfo>
log_config?: Partial<ConfigTypes.ILogConfig>
user_fields?: Array<Number>
}
/**
* 表示日志用户字段的接口
*/
interface ILogUserFields {
/**
* 日志用户字段的详细信息
*/
log_user_field?: CommonTypes.Optional<Partial<UserFieldTypes.ILogUserFields>, 'name'>
interface IFields {
field?: FieldTypes.TFieldRequird
}
type TRemoveLogsResultByTask = (CommonTypes.IDeviceId & Pick<ConfigTypes.ILogConfig, 'log_saved_days'>)
}
declare namespace DeviceStatus {
interface IDeviceStatus extends CommonTypes.IDeviceId{
status: number
status?: number,
last_log_upload_time?: string | Date
last_log_remove_time?: string | Date
last_login_time?: string | Date
last_offline_time?: string | Date
}
type Status = Omit<IDeviceStatus,'device_id'>
}
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
}
......@@ -5,6 +5,7 @@ declare namespace FileTypes {
filename: string
path: string
size: number
destination: string
type: T
}
type FileUpload<T> = Omit<IFile<T>, 'id'>
......
declare namespace RelationsTypes {
interface IRelation extends CommonTypes.IId {
config_id: number
user_field_id: number
interface IRelation extends CommonTypes.IId, CommonTypes.IDeviceId {
field_id: number
}
type LogConfigUserFieldsRel = Omit<IRelation, 'id'>
}
declare namespace UserFieldTypes {
interface ILogUserFields extends CommonTypes.IId {
name: string
}
}
......@@ -8,10 +8,9 @@ declare namespace WsTypes {
type MessageBody<U, T = WsMsgType> = {
event: T
data: U
data: MessageData<U>
} & (T extends 'private' ? CommonTypes.IDeviceId : Partial<CommonTypes.IDeviceId>)
interface IWsResponse<T, U> extends CommonTypes.IDeviceId {
/**
* 状态码
......@@ -19,15 +18,14 @@ declare namespace WsTypes {
status: T
message: U
}
type LoginValidate<T> = { isValidate: boolean; errMsg: T }
type MessageData<T, U = CommonTypes.TObj> = {
command: T | string
payload: U
}
type WsMessageData<T> = MessageData<T>
type LoginValidate<T> = { isValidate: boolean; errMsg: T; errorCode: number }
type MessageData<T> = {
command: T
days?: number
id?: string
interval?: number,
key?: string
}
type WsConnError = CommonTypes.IDeviceId & { message: string }
}
# http://localhost:3000/device?pageIndex=1&pageSize=5
# http://localhost:3000/device/addAll
# http://localhost:3000/device?user=尹
http://localhost:3000/device/addAll
# http://localhost:3000/device/task
......@@ -7,7 +7,7 @@
# content-type: application/json
# {
# "sn":"26DYD24513203857"
# "sn":"test2002"
# }
# POST http://localhost:3000/device/addInfo HTTP/1.1
......@@ -34,19 +34,19 @@
POST http://localhost:3000/broadcast/cmd HTTP/1.1
content-type: application/json
# POST http://localhost:3000/broadcast/cmd HTTP/1.1
# content-type: application/json
{
"event":"private",
"device_id":1000000,
"data":{
"command":"getStorage",
"payload":{
"key":"recordList"
}
}
}
# {
# "event":"private",
# "device_id":"1000068",
# "data":{
# "command":"getLog",
# "days":20,
# "interval":1000,
# "force":true
# }
# }
# http://localhost:3000/file/list?device_id=1000000
# http://localhost:3000/config?device_id=1000000
......@@ -59,3 +59,13 @@ POST http://localhost:3000/broadcast/cmd HTTP/1.1
# "log_saved_days":7,
# "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
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!