Commit a14c7f51 by 前端

Merge branch 'dev' into 'master'

上线合并

See merge request !2
2 parents a54baa38 45fb0783
Showing 60 changed files with 974 additions and 837 deletions
...@@ -4,8 +4,9 @@ ...@@ -4,8 +4,9 @@
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB. # 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 # 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" 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=8541005c-5f60-416b-821e-64b4d872cd77' QIWEI_WEBHOOK='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=16eaf975-65bc-4a7c-b744-a81f6236acc2'
SOCKET_PORT= 8080 SOCKET_PORT= 8080
APP_PORT= 3000 APP_PORT= 3000
STATIC_PATH= "public"
\ No newline at end of file \ No newline at end of file
STATIC_PATH = "public"
JWT_SECRET = 'secretKey'
\ No newline at end of file \ No newline at end of file
...@@ -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
...@@ -8,78 +8,78 @@ datasource db { ...@@ -8,78 +8,78 @@ datasource db {
} }
model device { model device {
id Int @id @default(autoincrement()) id Int @id @unique(map: "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?
fields field_relation[]
logs file[] logs file[]
log_config log_config? log_config log_config?
} }
model device_info { model device_info {
id Int @id @default(autoincrement()) device_id Int @id @unique(map: "device_id") @default(0)
device_id Int @unique @default(0) user String? @db.VarChar(20)
user String? @db.VarChar(20) mobile String? @db.VarChar(20)
last_log_upload_time DateTime? @db.Timestamp(0) merchant_name String? @db.VarChar(50)
last_log_remove_time DateTime? @db.Timestamp(0) 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) device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_device_info_device")
mobile String? @db.VarChar(20)
merchant_name String? @db.VarChar(50)
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 { model device_status {
device_id Int @id device_id Int @id @unique(map: "device_id")
status Int @default(0) @db.TinyInt status Int @default(0) @db.TinyInt
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK__device") last_login_time DateTime? @db.Timestamp(0)
device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK__device_info") 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")
} }
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.
model file { model file {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
device_id Int @default(0) device_id Int @default(0)
path String @db.VarChar(255) path String @db.VarChar(255)
mimetype String? @db.VarChar(100) mimetype String? @db.VarChar(100)
filename String? @db.VarChar(100) filename String? @db.VarChar(100)
originalname String? @db.VarChar(255) originalname String? @db.VarChar(255)
size Int? @default(0) size Int? @default(0)
created_at DateTime @default(now()) @db.Timestamp(0) destination String? @db.VarChar(500)
type String @default("other") @db.VarChar(10) created_at DateTime @default(now()) @db.Timestamp(0)
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_device") type String @default("other") @db.VarChar(10)
device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_device_info") device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_device")
@@index([device_id], map: "FK_file_device")
} }
model log_config { model log_config {
id Int @id @default(autoincrement()) device_id Int @id @unique(map: "device_id") @default(0)
device_id Int @unique @default(0) 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) 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")
user_fields log_config_userfield_relation[]
} }
model log_config_userfield_relation { model field {
id Int @id @default(autoincrement()) id Int @id @unique(map: "id") @default(autoincrement())
config_id Int @default(0) name String @db.VarChar(20)
user_field_id Int @default(0) type String @default("user") @db.VarChar(10)
log_config log_config @relation(fields: [config_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_userfield_relation_log_config") created_at DateTime @default(now()) @db.Timestamp(0)
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") updated_at DateTime @default(now()) @db.Timestamp(0)
fields field_relation[]
@@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 { /// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.
id Int @id @default(autoincrement()) model field_relation {
name String @db.VarChar(20) id Int @id @default(autoincrement())
created_at DateTime @default(now()) @db.Timestamp(0) device_id Int?
updated_at DateTime @default(now()) @db.Timestamp(0) field_id Int?
log_config_userfield_relation log_config_userfield_relation[] 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' ...@@ -8,7 +8,7 @@ import statusMonitorConfig from './config/statusMonitor'
import { LoggerMiddleware } from './common/middleware/logger.middleware' import { LoggerMiddleware } from './common/middleware/logger.middleware'
import { TasksModule } from './tasks/tasks.module' import { TasksModule } from './tasks/tasks.module'
// import { AudioModule } from './jobs/audio/audio.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 { HelloModule } from './modules/hello/hello.module'
import { DeviceModule } from './modules/device/device.module' import { DeviceModule } from './modules/device/device.module'
// import { ExceptionModule } from './modules/exception/exception.module' // import { ExceptionModule } from './modules/exception/exception.module'
...@@ -23,28 +23,35 @@ import { LogConfigModule } from './modules/config/config.module' ...@@ -23,28 +23,35 @@ 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'
import { JwtModule } from '@nestjs/jwt'
@Module({ @Module({
imports: [ imports: [
ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')), ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')),
// TypeOrmModule.forRootAsync({
// useFactory: (config: ConfigService) => config.get('database'),
// inject: [ConfigService]
// }),
HttpModule.registerAsync({ HttpModule.registerAsync({
useFactory: async (config: ConfigService) => config.get('http'), useFactory: async (config: ConfigService) => config.get('http'),
inject: [ConfigService] inject: [ConfigService]
}), }),
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(),
DeviceModule,
TasksModule, TasksModule,
// AudioModule, // AudioModule,
// AuthModule,
// HelloModule, // HelloModule,
// ExceptionModule, // ExceptionModule,
// RoleGuardModule, // RoleGuardModule,
...@@ -52,10 +59,11 @@ import { HttpModule } from '@nestjs/axios' ...@@ -52,10 +59,11 @@ import { HttpModule } from '@nestjs/axios'
// UsersModule, // UsersModule,
FileModule, FileModule,
// SseModule, // SseModule,
AuthModule,
WsModule, WsModule,
DeviceModule,
BroadcastModule, BroadcastModule,
LogConfigModule LogConfigModule,
FieldsModule
] ]
}) })
export class AppModule { export class AppModule {
......
...@@ -42,17 +42,29 @@ export enum WsAccess { ...@@ -42,17 +42,29 @@ export enum WsAccess {
InvalidDeviceId = '无效设备id', InvalidDeviceId = '无效设备id',
IsOnline = '通过验证,设备上线', IsOnline = '通过验证,设备上线',
IsOffline = '设备下线', 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 { export enum Events {
OnConnected = 'device.connected', OnConnected = 'device.connected',
OnConnectError = 'device.connect.error', OnConnectError = 'device.connect.error',
OnOfflineAll='device.offline.all', OnOfflineAll = 'device.offline.all',
OnMessage='client.mesage.received', OnMessage = 'client.mesage.received',
OnLogFileUploaded = 'log.file.uploaded', OnLogFileUploaded = 'log.file.uploaded',
OnLogFileRemoved='log.file.removed', OnLogFileRemoved = 'log.file.removed',
OnTaskStart='task.start' OnDailyTaskStart = 'task.daily.start',
OnSendMessage = 'client.message.send',
OnMessageToSendClient = 'message.send.to.client'
} }
export enum DocTypes { export enum DocTypes {
Log = 'log', Log = 'log',
...@@ -60,14 +72,18 @@ export enum DocTypes { ...@@ -60,14 +72,18 @@ export enum DocTypes {
Video = 'video', Video = 'video',
Other = 'other' Other = 'other'
} }
export enum Command{ export enum Command {
GetLog='getLog', GetLog = 'getLog',
GetStorage='getStorage', GetStorage = 'getStorage',
Message='message', Message = 'message',
File='file' GetLogList = 'getLogList',
RemoveLog = 'removeLog',
RemoveRecord = 'removeRecord',
StopPolling = 'stopPolling',
StartPolling = 'startPolling',
SetPollingInterval = 'setPollingInterval'
} }
export enum FileCommand{ export enum LogFieldTypes {
GetList='getList', User = 'user'
Remove='remove'
} }
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 { 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, query, body } = req
Logger.debug(`method -> ${method} url -> ${url} params -> ${JSON.stringify(params)} query -> ${JSON.stringify(query)}`); Logger.warn({ method, url, originalUrl, baseUrl, query, body })
next(); next()
} }
} }
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common' import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'
import { Socket } from 'socket.io'
@Injectable() @Injectable()
export class PagesPipe implements PipeTransform<CommonTypes.IPageIn> { export class PagesPipe implements PipeTransform<CommonTypes.IPageIn> {
...@@ -56,3 +57,4 @@ export class ParseIdPipe implements PipeTransform<any, any> { ...@@ -56,3 +57,4 @@ export class ParseIdPipe implements PipeTransform<any, any> {
return transformedValue 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 \ No newline at end of file
...@@ -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 { join,extname } from 'path'; import { join,extname } from 'path';
import { diskStorage } from 'multer'; import { diskStorage } from 'multer';
export default { export default {
root: join(__dirname,'..','..',process.env.STATIC_PATH), root: join(__dirname,'..','..',process.env.STATIC_PATH),
storage: diskStorage({ storage: diskStorage({
......
export default { export default {
host: 'localhost', host: '192.168.3.209',//测试环境
port: 6379, port: 6379,
} }
\ No newline at end of file \ No newline at end of file
import { ApiProperty } from '@nestjs/swagger' import { ApiProperty } from '@nestjs/swagger'
import { Transform } from 'class-transformer' 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) { export function IsNumberOrNumberString(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) { return function (object: Object, propertyName: string) {
...@@ -13,10 +13,10 @@ export function IsNumberOrNumberString(validationOptions?: ValidationOptions) { ...@@ -13,10 +13,10 @@ export function IsNumberOrNumberString(validationOptions?: ValidationOptions) {
validator: { validator: {
validate(value: any, args: ValidationArguments) { validate(value: any, args: ValidationArguments) {
// 如果值为空(null, undefined, ''),则验证通过 // 如果值为空(null, undefined, ''),则验证通过
if (value === null || value === undefined || value === '') { if (value === '') return false
if (value === null || value === undefined) {
return true return true
} }
// 尝试将值转换为数字,如果转换成功或原本就是数字,则验证通过 // 尝试将值转换为数字,如果转换成功或原本就是数字,则验证通过
// 注意:这里使用了 Number.isNaN 来检查转换结果是否为 NaN,从而排除非数字字符串 // 注意:这里使用了 Number.isNaN 来检查转换结果是否为 NaN,从而排除非数字字符串
return !Number.isNaN(Number(value)) return !Number.isNaN(Number(value))
...@@ -60,3 +60,59 @@ export class BaseDto { ...@@ -60,3 +60,59 @@ export class BaseDto {
@IsNumberOrNumberString() @IsNumberOrNumberString()
pageIndex?: number 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 \ No newline at end of file
import { ApiProperty } from '@nestjs/swagger' import { ApiProperty } from '@nestjs/swagger'
import { Command, WsMessageType } from '../common/enums' import { Command, WsMessageType } from '../common/enums'
import { IsDefined, IsEnum, IsNotEmpty, IsNumber, IsString, ValidateIf, ValidateNested } from 'class-validator' import { IsDefined, IsEnum, IsNotEmpty, IsNumber, IsOptional, IsString, registerDecorator, ValidateIf, ValidateNested, ValidationArguments, ValidationOptions } from 'class-validator'
import { Type } from 'class-transformer' import { Type } from 'class-transformer'
import { IsNumberOrNumberString } from './base.dto'
class DataDto { class DataDto {
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: '指令类型' description: '指令类型 '
}) })
@IsEnum(Command, { message: '指令类型错误' }) @IsEnum(Command, { message: '指令类型错误 目前支持 ' })
@IsString({ message: '指令为必填参数' }) @IsString({ message: '指令为必填参数' })
@IsNotEmpty({ message: '指令不能为空' }) @IsNotEmpty({ message: '指令不能为空' })
readonly command: Command readonly command: Command
@ApiProperty({ @ApiProperty({
description: '下发的参数' description: '删除日志传入的天数,非必填,但是如果有值,必须为数字,且当指令为删除日志时,days为必填'
})
@IsOptional()
@IsDefined({ message: '当指令为删除日志时,days为必填' })
@IsNumberOrNumberString()
@ValidateIf(o => o.command === Command.RemoveLog)
readonly days?: number | string
@ApiProperty({
description: '删除接待记录时,为接待记录的ID,且当指令为删除接待记录时,id为必填'
})
@IsOptional()
@ValidateIf(o => o.command === Command.RemoveRecord)
@IsDefined({ message: '当指令为删除接待记录时,id为必填' })
readonly id?: string
@ApiProperty({
description: '设置文件上传轮询间隔时间时,当指令为设置文件上传轮询间隔时间时,interval为必填'
}) })
readonly payload: unknown @ValidateIf(o => o.command === Command.SetPollingInterval)
@IsDefined({ message: '当指令设置文件上传轮询间隔时间,interval为必填 且必须为数字' })
@IsNumberOrNumberString()
readonly interval: number | string
} }
export class BroadcastDto { export class BroadcastDto {
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: '事件类型: private-私有消息,system-系统消息', description: '事件类型: private-私有消息,system-系统消息'
}) })
@IsEnum(WsMessageType, { message: '事件类型错误' }) @IsEnum(WsMessageType, { message: '事件类型错误' })
@IsNotEmpty({ message: '事件类型不能为空' }) @IsNotEmpty({ message: '事件类型不能为空' })
...@@ -32,7 +52,7 @@ export class BroadcastDto { ...@@ -32,7 +52,7 @@ export class BroadcastDto {
@IsDefined({ message: '发送私有消息时,device_id是必填的' }) @IsDefined({ message: '发送私有消息时,device_id是必填的' })
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '设备号,私发信息必填', description: '设备号,私发信息必填'
}) })
readonly device_id: number readonly device_id: number
......
import { ApiProperty } from "@nestjs/swagger" import { ApiProperty, IntersectionType, PartialType, PickType } from '@nestjs/swagger'
import { Transform } from "class-transformer" import { Transform } from 'class-transformer'
import { IsNotEmpty, IsNumber, isString, Matches } from "class-validator" import { IsNotEmpty, IsNumber, isString, Matches } from 'class-validator'
import { DeviceIdDto, TimeDto } from './base.dto'
/* /*
model log_config { model log_config {
...@@ -13,54 +14,13 @@ 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") 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[] user_fields log_config_userfield_relation[]
}*/ }*/
export class LogConfigDto { export class LogConfigDto extends IntersectionType(DeviceIdDto, PartialType(TimeDto)) {
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '设备信息ID', description: '日志保存天数',
required: false, required: false,
default: 0 default: ''
}) })
id: number log_saved_days?: number
@ApiProperty({ }
type: Number, export class LogConfigUpdateDto extends PickType(LogConfigDto, ['log_saved_days']) {}
description: '设备ID',
required: true,
default: 0
})
@IsNotEmpty({ message: '设备ID不能为空' })
device_id: number
@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: []
}
import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone, IsOptional } from 'class-validator' import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone, IsOptional, isNotEmpty } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger' import { ApiProperty, IntersectionType, PartialType, PickType } from '@nestjs/swagger'
import { BaseDto } from './base.dto' import { BaseDto, DeviceIdDto, SnDto, TimeDto, UserBaseDto } from './base.dto'
import { LogConfigUpdateDto } from './config.dto'
export class DeviceQueryDto extends BaseDto { export class DeviceQueryDto extends PartialType(UserBaseDto) {
@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({ @ApiProperty({
type: Number, type: Number,
description: '设备ID', description: '在线状态 1:在线,2:离线,0:弃用',
default: 0 required: false
})
@IsNumber({}, { message: '设备ID必须是数字' })
@IsNotEmpty({ message: '设备ID不能为空' })
device_id: number
@ApiProperty({
type: String,
description: '设备用户',
default: ''
}) })
user: string status?: number
}
@ApiProperty({
type: Number,
description: '设备状态',
default: 0
})
status: number
@ApiProperty({
type: String,
description: '最后一次上传日志的时间',
default: ''
})
last_log_upload_time: string
@ApiProperty({
type: String,
description: '最后一次移除日志的时间',
default: ''
})
last_log_remove_time: string
@ApiProperty({ export class DeviceFindOneDto extends PickType(UserBaseDto, ['user', 'mobile']) {}
type: Number,
description: '创建时间',
default: ''
})
created_at: Date
export class AddDeviceInfoDto extends IntersectionType(PartialType(SnDto),TimeDto) {
@ApiProperty({ @ApiProperty({
type: Date, description: '设备信息 包括 user mobile merchant_name'
description: '更新时间',
default: ''
}) })
updated_at: Date device_info?: UserBaseDto
@IsMobilePhone('zh-CN', {}, { message: '手机号格式不正确' })
@IsOptional()
@ApiProperty({ @ApiProperty({
type: String, description: '设备配置信息 包括 log_saved_days'
description: '使用者手机号',
default: ''
}) })
mobile: string log_config?: LogConfigUpdateDto
@ApiProperty({ @ApiProperty({
type: String, description: '设备对应的日志字段集合 '
description: '使用者商户名称',
default: ''
}) })
merchant_name: string user_fields?: Array<Number>
@ApiProperty({
type: Object,
description: '日志配置',
default: {}
})
log_config: {}
} }
export class UpdateDeviceInfoDto extends IntersectionType(PartialType(AddDeviceInfoDto), DeviceIdDto) {}
import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone, IsOptional } from 'class-validator' import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone, IsOptional } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger' import { ApiProperty } from '@nestjs/swagger'
export class DeviceStatusDto { export class DeviceStatusDto {
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '设备ID', description: '设备ID',
default: 0 required: true,
}) })
@IsNumber({}, { message: '设备ID必须是数字' }) @IsNumber({}, { message: '设备ID必须是数字' })
@IsNotEmpty({ message: '设备ID不能为空' }) @IsNotEmpty({ message: '设备ID不能为空' })
device_id: number device_id: number
@IsNumber({}, { message: '设备状态必须是数字' })
@IsNotEmpty({ message: '设备状态不能为空' })
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '设备状态', description: '设备状态',
default: 0 required: false,
}) })
status: number status?: number
@IsNotEmpty({ message: 'SocketID不能为空' })
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'SocketID', description: '最后一次上传日志的时间',
default: '' 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) {}
...@@ -3,4 +3,5 @@ export * from './config.dto' ...@@ -3,4 +3,5 @@ export * from './config.dto'
export * from './device.dto' 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'
\ No newline at end of file \ No newline at end of file
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'
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston'
export default class Initializer { export default class Initializer {
static async use(app) { static async use(app) {
app.useGlobalFilters(new ExceptionsFilter()) app.useGlobalFilters(new ExceptionsFilter())
...@@ -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 { 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 { Body, Controller, Get, Post, Request, UseGuards, UseInterceptors, UsePipes, ValidationPipe } from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'; import { AuthGuard } from '@nestjs/passport'
import { AuthService } from './auth.service'; 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() @Controller()
@ApiTags('权限管理')
@Controller('device')
@UseInterceptors(TransformInterceptor)
@UsePipes(new ValidationPipe())
export class AuthController { export class AuthController {
constructor(private readonly authService: AuthService) {} constructor(private readonly authService: AuthService) {}
// 登录测试 // 登录测试
@UseGuards(AuthGuard('local')) // @UseGuards(AuthGuard('local'))
@Post('/auth/login') @Post('login')
async login(@Request() req) { async login(@Body() {sn}: SnDto): Promise<CommonTypes.IResData> {
return this.authService.login(req.user); 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才能访问 // 测试登录后才可访问的接口,在需要的地方使用守卫,可保证必须携带token才能访问
@UseGuards(AuthGuard('jwt')) @UseGuards(AuthGuard('jwt'))
@Get('me') @Get('me')
getProfile(@Request() req) { getProfile(@Request() req) {
return req.user; return req.user
} }
} }
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common'
import { AuthService } from './auth.service'; import { AuthService } from './auth.service'
import { PassportModule } from '@nestjs/passport'; import { PassportModule } from '@nestjs/passport'
import { JwtModule } from '@nestjs/jwt'; import { JwtModule, JwtService } from '@nestjs/jwt'
// import { UsersModule } from '../users/users.module'; // import { UsersModule } from '../users/users.module';
import { AuthController } from './auth.controller'; import { AuthController } from './auth.controller'
import { LocalStrategy } from './local.strategy'; import { LocalStrategy } from './local.strategy'
import { JwtStrategy } from './jwt.strategy'; import { JwtStrategy } from './jwt.strategy'
import { jwtConstants } from './constants'; import { jwtConstants } from './constants'
import { PrismaModule, PrismaService } from 'nestjs-prisma'
import { DeviceModule } from '../device/device.module'
@Module({ @Module({
imports: [ imports: [
// UsersModule, PassportModule.register({ defaultStrategy: 'jwt' }),
PassportModule,
JwtModule.register({ JwtModule.register({
secret: jwtConstants.secret, global: true,
signOptions: { expiresIn: '60s' }, secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '24h' }
}), }),
PrismaModule,
DeviceModule
], ],
controllers: [AuthController], controllers: [AuthController],
providers: [AuthService, LocalStrategy, JwtStrategy], providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService], exports: [AuthService]
}) })
export class AuthModule {} export class AuthModule {}
import { Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'; 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() @Injectable()
export class AuthService { export class AuthService {
constructor( constructor(
// private readonly usersService: UsersService, private readonly deviceService: DeviceService,
private readonly jwtService: JwtService, @Inject(JwtService)
private readonly jwtService: JwtService
) {} ) {}
async validateUser(username: string, pass: string): Promise<any> { async validateUser(user: DeviceFindOneDto): Promise<CommonTypes.IResData> {
// const user = await this.usersService.find(username); return await this.deviceService.findOne(user)
const user = { name: 'walker123', password: '123321' }; }
if (user && user.password) {
const { password, ...result } = user; async validateSn(sn:string): Promise<CommonTypes.IResData<CommonTypes.IId&CommonTypes.ISn>> {
return result; return await this.deviceService.findOneBySn(sn)
}
return null;
} }
async login(user: any): Promise<any> { getToken({ user, mobile }: DeviceFindOneDto): string {
const payload = {username: user.username, sub: user.userId}; return this.jwtService.sign({ user, mobile })
return { }
access_token: this.jwtService.sign(payload), 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'; ...@@ -7,7 +7,7 @@ import { jwtConstants } from './constants';
export class JwtStrategy extends PassportStrategy(Strategy) { export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() { constructor() {
super({ super({
jwtFromRequest: ExtractJwt.fromHeader('token'), jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),//ExtractJwt.fromHeader('token'),
ignoreExpiration: false, ignoreExpiration: false,
secretOrKey: jwtConstants.secret, secretOrKey: jwtConstants.secret,
}); });
......
...@@ -2,6 +2,7 @@ import { Strategy } from 'passport-local'; ...@@ -2,6 +2,7 @@ import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport'; import { PassportStrategy } from '@nestjs/passport';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common'; import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { AuthService } from './auth.service'; import { AuthService } from './auth.service';
import { DeviceFindOneDto } from '../../dto';
@Injectable() @Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) { export class LocalStrategy extends PassportStrategy(Strategy) {
...@@ -9,16 +10,13 @@ export class LocalStrategy extends PassportStrategy(Strategy) { ...@@ -9,16 +10,13 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
super(); super();
} }
async validate(username: string, password: string): Promise<any> { async validate(user: DeviceFindOneDto): Promise<any> {
// tslint:disable-next-line const device = await this.authService.validateUser(user);
console.log(username, password) if (!device) {
return {username, password};
const user = await this.authService.validateUser(username, password);
if (!user) {
throw new HttpException( throw new HttpException(
{ message: 'authorized failed', error: 'please try again later.' }, { message: 'authorized failed', error: 'please try again later.' },
HttpStatus.BAD_REQUEST); HttpStatus.BAD_REQUEST);
} }
return user; return device;
} }
} }
import { Controller, Post, Body, UseInterceptors, UsePipes, Logger } from '@nestjs/common' import { Controller, Post, Body, UseInterceptors, UsePipes, Logger } from '@nestjs/common'
import { BroadcastService } from './broadcast.service' import { BroadcastService } from './broadcast.service'
import { TransformInterceptor } from '../../common/interceptors' import { TransformInterceptor } from '../../common/interceptors'
import { WsGateway } from '../ws/ws.gateway'
import { BroadcastDto } from '../../dto' import { BroadcastDto } from '../../dto'
import { ValidationPipe } from '../../common/pipes' import { ParseDeviceIdPipe, ValidationPipe } from '../../common/pipes'
import { ApiOperation, ApiTags } from '@nestjs/swagger' import { ApiOperation, ApiTags } from '@nestjs/swagger'
import { OnEvent } from '@nestjs/event-emitter' import { OnEvent } from '@nestjs/event-emitter'
import { Events } from '../../common/enums' import { Events } from '../../common/enums'
...@@ -14,10 +13,9 @@ import { Events } from '../../common/enums' ...@@ -14,10 +13,9 @@ import { Events } from '../../common/enums'
@UsePipes(new ValidationPipe()) // 使用管道验证 @UsePipes(new ValidationPipe()) // 使用管道验证
export class BroadcastController { export class BroadcastController {
/** /**
* @param wsGateway - WsGateway实例 *
*/ */
constructor( constructor(
private readonly wsGateway: WsGateway,
private readonly broadcastService: BroadcastService private readonly broadcastService: BroadcastService
) {} ) {}
...@@ -28,12 +26,13 @@ export class BroadcastController { ...@@ -28,12 +26,13 @@ export class BroadcastController {
*/ */
@Post('/cmd') @Post('/cmd')
@ApiOperation({ summary: '给设备发送指令' }) @ApiOperation({ summary: '给设备发送指令' })
@UsePipes(new ParseDeviceIdPipe())
async message(@Body() params: BroadcastDto): Promise<CommonTypes.IResData> { async message(@Body() params: BroadcastDto): Promise<CommonTypes.IResData> {
return this.wsGateway.send(params) return this.broadcastService.send(params)
} }
@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)
} }
} }
import { Module } from '@nestjs/common' import { Module } from '@nestjs/common'
import { BroadcastController } from './broadcast.controller' import { BroadcastController } from './broadcast.controller'
import { BroadcastService } from './broadcast.service' import { BroadcastService } from './broadcast.service'
import { WsModule } from '../ws/ws.module';
import { WsService } from '../ws/ws.service';
import { HttpModule } from '@nestjs/axios'; import { HttpModule } from '@nestjs/axios';
import { WsModule } from '../ws/ws.module';
@Module({ @Module({
imports: [WsModule,HttpModule], imports: [HttpModule,WsModule],
controllers: [BroadcastController], controllers: [BroadcastController],
providers: [BroadcastService,WsService] providers: [BroadcastService]
}) })
export class BroadcastModule {} export class BroadcastModule {}
...@@ -2,8 +2,9 @@ import { HttpService } from '@nestjs/axios' ...@@ -2,8 +2,9 @@ import { HttpService } from '@nestjs/axios'
import { Inject, Injectable } from '@nestjs/common' import { Inject, Injectable } from '@nestjs/common'
import { AxiosResponse } from 'axios' import { AxiosResponse } from 'axios'
import { ConfigService } from 'nestjs-config' import { ConfigService } from 'nestjs-config'
import { Command, Events, FileCommand, RESPONSE_CODE } from '../../common/enums' import { Command, Events, RESPONSE_CODE, WsMessageType } from '../../common/enums'
import { EventEmitter2 } from '@nestjs/event-emitter' import { EventEmitter2 } from '@nestjs/event-emitter'
import { WsGateway } from '../ws/ws.gateway'
@Injectable() @Injectable()
export class BroadcastService { export class BroadcastService {
private webHook: string private webHook: string
...@@ -11,15 +12,23 @@ export class BroadcastService { ...@@ -11,15 +12,23 @@ export class BroadcastService {
private readonly httpService: HttpService, private readonly httpService: HttpService,
private readonly config: ConfigService, private readonly config: ConfigService,
@Inject(EventEmitter2) @Inject(EventEmitter2)
private readonly eventEmitter: EventEmitter2 private readonly eventEmitter: EventEmitter2,
private readonly wsGateway: WsGateway
) { ) {
this.webHook = this.config.get('env').AppWebhook 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> { async onMessage(param: any): Promise<CommonTypes.IResData> {
if (param?.code === RESPONSE_CODE.SUCCESS && param?.data?.command === Command.File && param?.data?.payload?.command === FileCommand.Remove) { if (param?.code == RESPONSE_CODE.SUCCESS && param?.data?.command === Command.RemoveLog) {
this.eventEmitter.emit(Events.OnLogFileRemoved, { device_id: param.device_id, last_log_remove_time: new Date() }) const statusInfo: DeviceStatus.IDeviceStatus = { device_id: param.device_id, last_log_remove_time: new Date() }
return this.eventEmitter.emit(Events.OnLogFileRemoved, statusInfo)
} }
const res: AxiosResponse<any, any> = await this.httpService const res: AxiosResponse<any, any> = await this.httpService
.post(this.webHook, { .post(this.webHook, {
......
...@@ -16,12 +16,12 @@ export class ConfigController { ...@@ -16,12 +16,12 @@ export class ConfigController {
@UsePipes(new PagesPipe()) @UsePipes(new PagesPipe())
@UsePipes(new ParseDeviceIdPipe()) @UsePipes(new ParseDeviceIdPipe())
@ApiOperation({ summary: '根据设备号获取配置' }) @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) return this.configService.findAll(params)
} }
@Post('/add') @Post('/add')
@ApiOperation({ summary: '新增设备配置' }) @ApiOperation({ summary: '新增或更新设备配置,de' })
addConfig(@Body() param: LogConfigDto): Promise<CommonTypes.IResData> { upsertConfig(@Body() param: LogConfigDto): Promise<CommonTypes.IResData> {
return this.configService.addConfig(param) return this.configService.upsertConfig(param)
} }
} }
import { Module } from '@nestjs/common' import { Module } from '@nestjs/common'
import { ConfigController } from './config.controller' import { ConfigController } from './config.controller'
import { ConfigService } from './config.service' import { ConfigService } from './config.service'
import { PrismaService } from 'nestjs-prisma' import { PrismaModule, PrismaService } from 'nestjs-prisma'
@Module({ @Module({
imports: [PrismaModule],
controllers: [ConfigController], controllers: [ConfigController],
providers: [ConfigService,PrismaService] providers: [ConfigService]
}) })
export class LogConfigModule {} export class LogConfigModule {}
...@@ -7,7 +7,7 @@ export class ConfigService { ...@@ -7,7 +7,7 @@ export class ConfigService {
@Inject(PrismaService) @Inject(PrismaService)
private readonly prisma: PrismaService // private connection: Connection, 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 = { const where: any = {
device_id device_id
} }
...@@ -15,62 +15,21 @@ export class ConfigService { ...@@ -15,62 +15,21 @@ export class ConfigService {
skip, skip,
take, take,
select: { select: {
id: true,
device_id: true, device_id: true,
log_saved_days: true, log_saved_days: true
user_fields: {
select: {
log_user_field: {
select: {
name: true
}
}
}
}
}, },
where 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({ const total = await this.prisma.log_config.count({
where 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 return resBody
} }
async addConfig(config: ConfigTypes.LogConfigAdd): Promise<CommonTypes.IResData> { async upsertConfig(config: Partial<ConfigTypes.ILogConfig>): Promise<CommonTypes.IResData> {
const { user_fields, ...data } = config const now = new Date()
let config_id: number = 0 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 } })
await this.prisma.$transaction(async prisma => { return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
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 })
})
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
} }
} }
import { Controller, Get, Post, Body, UseInterceptors, Query, UsePipes, Inject } from '@nestjs/common' import { Controller, Get, Post, Body, UseInterceptors, Query, UsePipes, Inject } from '@nestjs/common'
import { DeviceService } from './device.service' import { DeviceService } from './device.service'
import { TransformInterceptor } from '../../common/interceptors' 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 { PagesPipe, ValidationPipe } from '../../common/pipes'
import { OnEvent, EventEmitter2 } from '@nestjs/event-emitter' import { OnEvent, EventEmitter2 } from '@nestjs/event-emitter'
import { WsAccess, Events, WsMessageType, Command, RESPONSE_CODE, FileCommand } from '../../common/enums' import { WsAccess, Events, WsMessageType, Command, RESPONSE_CODE } from '../../common/enums'
import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger' import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'
@ApiTags('设备管理') @ApiTags('设备管理')
...@@ -34,10 +34,13 @@ export class DeviceController { ...@@ -34,10 +34,13 @@ export class DeviceController {
@Get() @Get()
@UsePipes(new PagesPipe()) @UsePipes(new PagesPipe())
@ApiOperation({ summary: '获取所有设备列表' }) @ApiOperation({ summary: '获取所有设备列表' })
findAll(@Query() params: DeviceQueryDto): Promise<CommonTypes.IResData> { async findAll(@Query() params: DeviceQueryDto): Promise<CommonTypes.IResData> {
return this.deviceService.findAll(params) return await this.deviceService.findAll(params)
} }
async finOne(@Query() params: DeviceFindOneDto): Promise<CommonTypes.IResData> {
return await this.deviceService.findOne(params)
}
/** /**
* 添加设备的方法 * 添加设备的方法
* 该方法接收一个包含设备信息的DTO对象,并返回添加后的设备信息 * 该方法接收一个包含设备信息的DTO对象,并返回添加后的设备信息
...@@ -46,9 +49,8 @@ export class DeviceController { ...@@ -46,9 +49,8 @@ export class DeviceController {
*/ */
@Post('/add') @Post('/add')
@ApiOperation({ summary: '添加设备' }) @ApiOperation({ summary: '添加设备' })
addDevice(@Body() param: AddDeviceDto): Promise<CommonTypes.IResponseBase> { async addDevice(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> {
// console.log(param) return await this.deviceService.addDevice(param)
return this.deviceService.addDevice(param)
} }
/** /**
* 添加设备信息的方法 * 添加设备信息的方法
...@@ -58,10 +60,10 @@ export class DeviceController { ...@@ -58,10 +60,10 @@ export class DeviceController {
*/ */
@Post('/addInfo') @Post('/addInfo')
@ApiOperation({ summary: '添加设备信息' }) @ApiOperation({ summary: '添加设备信息' })
addDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> { async addDeviceInfo(@Body() param: UpdateDeviceInfoDto): Promise<CommonTypes.IResData> {
// console.log(param) return await this.deviceService.addDeviceInfo(param)
return this.deviceService.addDeviceInfo(param)
} }
/** /**
* 更新设备信息的方法 * 更新设备信息的方法
* 该方法接收一个包含设备信息的DTO对象,并返回更新后的设备信息 * 该方法接收一个包含设备信息的DTO对象,并返回更新后的设备信息
...@@ -70,9 +72,8 @@ export class DeviceController { ...@@ -70,9 +72,8 @@ export class DeviceController {
*/ */
@Post('/updateInfo') @Post('/updateInfo')
@ApiOperation({ summary: '修改设备信息' }) @ApiOperation({ summary: '修改设备信息' })
@OnEvent(Events.OnLogFileRemoved) async updateDeviceInfo(@Body() param: UpdateDeviceInfoDto): Promise<CommonTypes.IResData> {
updateDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> { return await this.deviceService.updateDeviceInfo(param)
return this.deviceService.updateDeviceInfo(param)
} }
/** /**
...@@ -81,15 +82,21 @@ export class DeviceController { ...@@ -81,15 +82,21 @@ export class DeviceController {
* @param param - 包含设备状态的DTO对象 * @param param - 包含设备状态的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象 * @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/ */
@OnEvent(Events.OnConnected)
@Post('/upsertStatus') @Post('/upsertStatus')
@OnEvent(Events.OnConnected)
@ApiOperation({ summary: '更新设备状态' }) @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 => { return await this.deviceService.upsertDeviceStatus(param).catch(error => {
const out: WsTypes.WsConnError = { message: WsAccess.ConnFailure, device_id: param.device_id } const out: WsTypes.WsConnError = { message: WsAccess.ConnFailure, device_id: param.device_id }
this.eventEmitter.emit(Events.OnConnectError, out) 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 { ...@@ -100,19 +107,19 @@ export class DeviceController {
@Post('/offlineAll') @Post('/offlineAll')
@OnEvent(Events.OnOfflineAll) @OnEvent(Events.OnOfflineAll)
@ApiOperation({ summary: '修改所有设备状态为离线' }) @ApiOperation({ summary: '修改所有设备状态为离线' })
async resetAllDeviceStatus(): Promise<void | CommonTypes.IResponseBase> { async resetAllDeviceStatus(): Promise<void | CommonTypes.IResData> {
return await this.deviceService.resetAllDeviceStatus() return await this.deviceService.resetAllDeviceStatus()
} }
@Get('/task') @Get('/task')
@OnEvent(Events.OnTaskStart) @OnEvent(Events.OnDailyTaskStart)
@ApiOperation({ summary: '日任务' }) @ApiOperation({ summary: '每日任务' })
async task(): Promise<void | CommonTypes.IResData> { async task(): Promise<void | CommonTypes.IResData> {
return await this.deviceService.removeFilesTask() return await this.deviceService.removeFilesTask()
} }
@Get('/addAll') @Get('/addAll')
@ApiOperation({ summary: '批量导入设备,用于初始化数据' }) @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) // return this.deviceService.addAll(devices)
} }
} }
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { DeviceController } from './device.controller'; import { DeviceController } from './device.controller';
import { DeviceService } from './device.service'; import { DeviceService } from './device.service';
import { PrismaService } from 'nestjs-prisma'; import { PrismaModule } from 'nestjs-prisma';
import { WsModule } from '../ws/ws.module';
import { WsService } from '../ws/ws.service';
// import { EventEmitter2 } from '@nestjs/event-emitter';
@Module({ @Module({
imports: [WsModule], imports: [PrismaModule],
controllers: [DeviceController], controllers: [DeviceController],
providers: [DeviceService,PrismaService,WsService], providers: [DeviceService],
exports: [DeviceService],
}) })
export class DeviceModule {} export class DeviceModule {}
...@@ -3,153 +3,248 @@ import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } f ...@@ -3,153 +3,248 @@ import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } f
// import { InjectRepository } from '@nestjs/typeorm'; // import { InjectRepository } from '@nestjs/typeorm';
// import { Device as DeviceEntity } from '../entities/Device' // import { Device as DeviceEntity } from '../entities/Device'
import { PrismaService } from 'nestjs-prisma' import { PrismaService } from 'nestjs-prisma'
import { Command, FileCommand, RESPONSE_CODE, WsMessageType, WsStatus } from '../../common/enums' import { Command, Events, RESPONSE_CODE, WsMessageType, WsStatus } from '../../common/enums'
import { WsGateway } from '../ws/ws.gateway' import { EventEmitter2 } from '@nestjs/event-emitter'
@Injectable() @Injectable()
export class DeviceService implements OnModuleInit { export class DeviceService implements OnModuleInit {
constructor( constructor(
@Inject(PrismaService) @Inject(PrismaService)
private readonly prisma: PrismaService, // private connection: Connection, private readonly prisma: PrismaService, // private connection: Connection,
private readonly wsGateway: WsGateway @Inject(EventEmitter2)
private readonly eventEmitter: EventEmitter2
) {} ) {}
async onModuleInit() { async onModuleInit() {
this.resetAllDeviceStatus() this.resetAllDeviceStatus()
} }
async findAll({ user, mobile, sn, skip, take, status }: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData<DeviceTypes.IDevice[]>> {
async findAll({ user, mobile, sn, skip, take }: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData<DeviceTypes.IDeviceInfo[]>> {
const where = { const where = {
sn: { sn: {
contains: sn contains: sn
}, },
AND: { device_info: {
device_info: { mobile: {
mobile: { contains: mobile
contains: mobile },
}, user: {
user: { contains: user
contains: user
}
} }
},
device_status: {
status: status || status == 0 ? +status : undefined
} }
} }
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: {
user: true, user: true,
mobile: true, mobile: true,
merchant_name: true, merchant_name: true
log_config: { }
},
log_config: {
select: {
log_saved_days: true
}
},
fields: {
select: {
field: {
select: { select: {
log_saved_days: true, name: true,
user_fields: { type: true
select: {
log_user_field: {
select: {
name: true
}
}
}
}
} }
},
device_status: {
select: { status: true }
} }
} }
},
device_status: {
select: { status: true, last_log_remove_time: true, last_log_upload_time: true, last_login_time: true, last_offline_time: true }
} }
}, },
where where,
orderBy: { created_at: 'desc' }
}) })
const total: number = await this.prisma.device.count({ const total: number = await this.prisma.device.count({
where where
}) })
const data: DeviceTypes.IDeviceInfo[] = result.reduce((pre: DeviceTypes.IDeviceInfo[], cur: DeviceTypes.IDeviceResult) => { const data: DeviceTypes.IDevice[] = result.reduce((pre: DeviceTypes.IDevice[], 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_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, last_log_remove_time: cur.device_status?.last_log_remove_time,
log_user_fields: cur.device_info?.log_config?.user_fields?.map((item: DeviceTypes.ILogUserFields) => item.log_user_field.name) last_log_upload_time: cur.device_status?.last_log_upload_time,
last_login_time: cur.device_status?.last_login_time,
last_offline_time: cur.device_status?.last_offline_time,
log_saved_days: cur?.log_config?.log_saved_days,
fields: cur?.fields?.map((item: DeviceTypes.IFields) => ({ name: item.field.name, type: item.field.type }))
}) })
return pre return pre
}, []) }, [])
const resBody: CommonTypes.IResData<DeviceTypes.IDeviceInfo[]> = { total, data } const resBody: CommonTypes.IResData<DeviceTypes.IDevice[]> = { total, data }
return resBody return resBody
} }
async addDevice(device: Omit<DeviceTypes.IDevice, 'id' | 'create_time'>): Promise<CommonTypes.IResData> { async findOne({ user, mobile }: Pick<CommonTypes.IUser, 'mobile' | 'user'>): Promise<CommonTypes.IResData<DeviceTypes.TOneDeviceInfo>> {
const deviceInfo: DeviceTypes.TOneDeviceInfo = await this.prisma.device_info.findFirstOrThrow({
where: { user, mobile }
})
return { code: RESPONSE_CODE.SUCCESS, data: deviceInfo }
}
async findOneBySn(sn: string): Promise<CommonTypes.IResData<CommonTypes.IId & CommonTypes.ISn>> {
try {
const device: CommonTypes.IId & CommonTypes.ISn = await this.prisma.device.findFirstOrThrow({
where: { sn }
})
return { code: RESPONSE_CODE.SUCCESS, data: device }
} catch (error) {
return { code: RESPONSE_CODE.NOSUCCESS, message: '用户验证失败!', error }
}
}
async addDevice(device: Omit<DeviceTypes.IDeviceSaves, 'device_id'>): Promise<CommonTypes.IResData> {
const { device_info, log_config, user_fields, sn } = device
await this.prisma.$transaction(async prisma => { await this.prisma.$transaction(async prisma => {
const { id } = await prisma.device.create({ data: device, select: { id: true } }) const now = new Date()
// await this.addDeviceInfo({device_id:id}) const { id } = await prisma.device.create({ data: { sn, created_at: now }, select: { id: true } })
await prisma.device_info.create({ data: { device_id: id, created_at: new Date(), updated_at: new Date() } }) const device_id = id
await prisma.device_status.create({ data: { device_id: id, status: WsStatus.Offline } }) if (device_info) {
await prisma.device_info.create({ data: { device_id, user: device_info.user, mobile: device_info.mobile, merchant_name: device_info.merchant_name, updated_at: now, created_at: now } })
}
if (log_config) {
await prisma.log_config.create({ data: { log_saved_days: log_config.log_saved_days, device_id, created_at: now, updated_at: now } })
}
if (user_fields) {
await prisma.field_relation.deleteMany({ where: { device_id } })
await prisma.field_relation.createMany({
data: user_fields.map((item: number) => ({ device_id, field_id: item }))
})
}
await prisma.device_status.create({ data: { device_id: id, status: WsStatus.Offline, last_log_remove_time: now } })
// await this.addDeviceInfo(Object.assign({ device_id: id },deviceInfo))
}) })
return { code: RESPONSE_CODE.SUCCESS, message: '添加设备成功' } return { code: RESPONSE_CODE.SUCCESS, message: '添加设备成功' }
} }
async addDeviceInfo(deviceInfo: Omit<DeviceTypes.IDeviceInfoInput, 'sn'>): Promise<CommonTypes.IResData> { async addDeviceInfo(deviceInfo: DeviceTypes.IDeviceSaves): Promise<CommonTypes.IResData> {
deviceInfo.created_at = new Date() const now = new Date()
deviceInfo.updated_at = new Date() const { device_id, ...data } = deviceInfo
const { device_info, log_config, user_fields, sn } = data
await this.prisma.$transaction(async prisma => { await this.prisma.$transaction(async prisma => {
await prisma.device_info.create({ data: deviceInfo }) if (sn) {
await prisma.device_status.create({ data: { device_id: deviceInfo.device_id, status: WsStatus.Offline } }) await prisma.device.update({ where: { id: device_id }, data: { sn } })
}
if (device_info) {
await prisma.device_info.create({ data: { device_id, user: device_info.user, mobile: device_info.mobile, merchant_name: device_info.merchant_name, updated_at: now, created_at: now } })
}
if (log_config) {
await prisma.log_config.create({ data: { log_saved_days: log_config.log_saved_days, device_id, created_at: now, updated_at: now } })
}
if (user_fields) {
await prisma.field_relation.deleteMany({ where: { device_id } })
await prisma.field_relation.createMany({
data: user_fields.map((item: number) => ({ device_id, field_id: item }))
})
}
await prisma.device_status.create({ data: { device_id, status: WsStatus.Offline, last_log_remove_time: now } })
}) })
return { code: RESPONSE_CODE.SUCCESS, message: '添加设备信息成功' } return { code: RESPONSE_CODE.SUCCESS, message: '添加设备信息成功' }
} }
async updateDeviceInfo(deviceInfo: Omit<DeviceTypes.IDeviceInfoInput, 'sn'>): Promise<CommonTypes.IResData> { async updateDeviceInfo(deviceInfo: DeviceTypes.IDeviceSaves): Promise<CommonTypes.IResData> {
const { device_id, ...data } = deviceInfo const { device_id, ...data } = deviceInfo
data.updated_at = new Date() const where = { device_id }
await this.prisma.device_info.update({ await this.prisma.$transaction(async prisma => {
where: { const now = new Date()
device_id: deviceInfo.device_id const { device_info, log_config, user_fields, sn } = data
}, if (sn) {
data await prisma.device.update({ where: { id: device_id }, data: { sn } })
}
if (device_info) {
device_info.updated_at = now
await prisma.device_info.update({
where,
data: { user: device_info.user, mobile: device_info.mobile, merchant_name: device_info.merchant_name, updated_at: now }
})
}
if (log_config) {
await prisma.log_config.update({
where,
data: { log_saved_days: log_config.log_saved_days, updated_at: now }
})
}
if (user_fields) {
await prisma.field_relation.deleteMany({ where })
await prisma.field_relation.createMany({
data: user_fields.map((item: number) => ({ device_id, field_id: item }))
})
}
}) })
return { code: RESPONSE_CODE.SUCCESS, message: '设备信息更新成功' } return { code: RESPONSE_CODE.SUCCESS, message: '设备信息更新成功' }
} }
async upsertDeviceStatus(data: DeviceStatus.IDeviceStatus): Promise<CommonTypes.IResData> { async upsertDeviceStatus(data: DeviceStatus.IDeviceStatus): Promise<CommonTypes.IResData> {
const now = new Date()
await this.prisma.device_status.upsert({ await this.prisma.device_status.upsert({
where: { where: { device_id: data.device_id },
device_id: data.device_id create: { device_id: data.device_id, status: WsStatus.Offline, last_log_remove_time: now },
}, update: { status: data.status, last_login_time: data.status === WsStatus.Online ? now : undefined, last_offline_time: data.status === WsStatus.Offline ? now : undefined, last_log_remove_time: data.last_log_remove_time, last_log_upload_time: data.last_log_upload_time }
create: data,
update: {
status: data.status
}
}) })
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' } return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
} }
async upsertFileRemovedTime(data: DeviceStatus.IDeviceStatus): Promise<CommonTypes.IResData> {
await this.prisma.device_status.update({
where: { device_id: data.device_id },
data: { last_log_remove_time: data.last_log_remove_time }
})
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
}
}) })
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' } return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
} }
async addAll(devices: Array<any>): Promise<CommonTypes.IResponseBase> { async addAll(devices: Array<any>): Promise<CommonTypes.IResponseBase> {
// devices =[
// {
// "设备编号": "26DYD23B25202154",
// "APP编码": "4DF8801064461802495A2452CCD04EE4",
// "保管人": "葛阳阳",
// "手机号": 15009585544,
// "品牌": "鸿蒙智行",
// "直营": "否",
// "业务场景": "延保",
// "督导": "刘洁琼",
// "最近使用时间": "2024-11-01",
// "最近使用人": "葛阳阳",
// "最近使用人所在门店": "银川华为2.(44212813)",
// "修改日期": "2024-09-19"
// },
// ]
for (let index = 0; index < devices.length; index++) { for (let index = 0; index < devices.length; index++) {
const el = devices[index] const el = devices[index]
await this.prisma.$transaction(async prisma => { await this.prisma.$transaction(async prisma => {
const { id } = await prisma.device.create({ data: { sn: el.设备编号 }, select: { id: true } }) const { id } = await prisma.device.create({ data: { sn: el.APP编码 }, select: { id: true } })
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, last_log_remove_time: new Date() } })
const { id: cfgid } = await prisma.log_config.create({ data: { device_id: id, log_saved_days: 7 }, select: { id: true } }) await prisma.log_config.create({ data: { device_id: id, log_saved_days: 30 } })
await prisma.log_config_userfield_relation.createMany({ await prisma.field_relation.createMany({
data: [ data: [
{ config_id: cfgid, user_field_id: 1 }, { device_id: id, field_id: 1 },
{ config_id: cfgid, user_field_id: 2 }, { device_id: id, field_id: 2 },
{ config_id: cfgid, user_field_id: 3 } { device_id: id, field_id: 3 }
] ]
}) })
}) })
...@@ -158,13 +253,21 @@ export class DeviceService implements OnModuleInit { ...@@ -158,13 +253,21 @@ export class DeviceService implements OnModuleInit {
} }
async removeFilesTask(): Promise<CommonTypes.IResData> { async removeFilesTask(): Promise<CommonTypes.IResData> {
const results: (CommonTypes.IDeviceId & Pick<DeviceTypes.IDeviceInfoBase, 'log_saved_days'>)[] = await this.prisma.$queryRaw<(CommonTypes.IDeviceId & Pick<DeviceTypes.IDeviceInfoBase, 'log_saved_days'>)[]>` const results: DeviceTypes.TRemoveLogsResultByTask[] = await this.prisma.$queryRaw<DeviceTypes.TRemoveLogsResultByTask[]>`
SELECT d.device_id, c.log_saved_days SELECT d.device_id, c.log_saved_days
FROM device_info d FROM device_info d
JOIN log_config c ON c.device_id = d.device_id JOIN log_config c ON c.device_id = d.device_id
WHERE c.log_saved_days >= TIMESTAMPDIFF(DAY, d.last_log_remove_time, NOW());` JOIN device_status s ON s.device_id = d.device_id
for (const { device_id, log_saved_days } of results) { WHERE c.log_saved_days < TIMESTAMPDIFF(DAY, s.last_log_remove_time, NOW()) AND s.status=1`
await this.wsGateway.send({ event: WsMessageType.Private, device_id, data: { command: Command.File, payload: { command: FileCommand.Remove, days: log_saved_days } } }) return this.sendMessage(results)
}
async sendMessage(results: DeviceTypes.TRemoveLogsResultByTask[]): Promise<CommonTypes.IResData> {
if (results.length) {
const { device_id, log_saved_days } = results.pop()
const message = { event: WsMessageType.Private, device_id, data: { command: Command.RemoveLog, days: log_saved_days } }
this.eventEmitter.emit(Events.OnMessageToSendClient, message)
await this.sendMessage(results)
} }
return { code: RESPONSE_CODE.SUCCESS, message: '每日日志删除任务完成' } return { code: RESPONSE_CODE.SUCCESS, message: '每日日志删除任务完成' }
} }
......
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' ...@@ -8,6 +8,7 @@ import { DocTypes } from '../../common/enums'
import { FileDeleteDto, FileQueryDto } from '../../dto' import { FileDeleteDto, FileQueryDto } from '../../dto'
import { ApiOperation, ApiTags } from '@nestjs/swagger' import { ApiOperation, ApiTags } from '@nestjs/swagger'
import { FilePathPipe, PagesPipe, ParseDeviceIdPipe, ParseIdPipe } from '../../common/pipes' import { FilePathPipe, PagesPipe, ParseDeviceIdPipe, ParseIdPipe } from '../../common/pipes'
import { join } from 'path'
@ApiTags('文件管理') @ApiTags('文件管理')
@UsePipes(new ValidationPipe()) @UsePipes(new ValidationPipe())
@Controller('file') @Controller('file')
...@@ -29,13 +30,12 @@ export class FileController { ...@@ -29,13 +30,12 @@ export class FileController {
@Post('upload') @Post('upload')
@UsePipes(new FilePathPipe()) @UsePipes(new FilePathPipe())
@ApiOperation({ summary: '文件上传' }) @ApiOperation({ summary: '文件上传' })
@UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain'), limits: { fileSize: 1024 * 1024 * 100 } }) @UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain') })
upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request): FileTypes.FileUpload<DocTypes> { async upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request): Promise<CommonTypes.IResData<FileTypes.FileUpload<DocTypes>>> {
const { fieldname, encoding, destination, stream, buffer, path, ...o } = file 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 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) const f: FileTypes.FileUpload<DocTypes> = Object.assign({ created_at: new Date(), path: `${req.protocol}://${req.get('Host')}${origin_path}` }, bodyData, o)
this.fileService.save(f) return await this.fileService.save(f)
return f
} }
/** /**
......
...@@ -3,7 +3,7 @@ import { MulterModule } from '@nestjs/platform-express'; ...@@ -3,7 +3,7 @@ import { MulterModule } from '@nestjs/platform-express';
import { ConfigService } from 'nestjs-config'; import { ConfigService } from 'nestjs-config';
import { FileController } from './file.controller'; import { FileController } from './file.controller';
import { FileService } from './file.service'; import { FileService } from './file.service';
import { PrismaService } from 'nestjs-prisma'; import { PrismaModule, PrismaService } from 'nestjs-prisma';
@Module({ @Module({
imports: [ imports: [
...@@ -11,8 +11,9 @@ import { PrismaService } from 'nestjs-prisma'; ...@@ -11,8 +11,9 @@ import { PrismaService } from 'nestjs-prisma';
useFactory: (config: ConfigService) => config.get('file'), useFactory: (config: ConfigService) => config.get('file'),
inject: [ConfigService], inject: [ConfigService],
}), }),
PrismaModule
], ],
controllers: [FileController], controllers: [FileController],
providers: [FileService,PrismaService], providers: [FileService],
}) })
export class FileModule {} export class FileModule {}
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'
...@@ -6,6 +6,7 @@ import * as path from 'path' ...@@ -6,6 +6,7 @@ import * as path from 'path'
import { DocTypes, RESPONSE_CODE } from '../../common/enums' import { DocTypes, RESPONSE_CODE } from '../../common/enums'
import { PrismaService } from 'nestjs-prisma' import { PrismaService } from 'nestjs-prisma'
import { Doc } from 'prettier' import { Doc } from 'prettier'
import { join } from 'path'
@Injectable() @Injectable()
export class FileService { export class FileService {
...@@ -37,7 +38,8 @@ export class FileService { ...@@ -37,7 +38,8 @@ export class FileService {
contains: filename 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({ const total: number = await this.prisma.file.count({
where where
}) })
...@@ -51,18 +53,25 @@ export class FileService { ...@@ -51,18 +53,25 @@ export class FileService {
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。 * @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/ */
async save(file: FileTypes.FileUpload<DocTypes>): Promise<CommonTypes.IResData> { async save(file: FileTypes.FileUpload<DocTypes>): Promise<CommonTypes.IResData> {
const { filename, path, created_at, ...where } = file const { filename, path, created_at, destination, size, ...where } = file
this.prisma.$transaction(async prisma => { await this.prisma.$transaction(async prisma => {
const { id, path: origin_path } = (await prisma.file.findFirst({ where, select: { id: true, path: true } })) || {} const files: Pick<FileTypes.IFile<DocTypes>, 'id' | 'destination' | 'filename'>[] = await prisma.file.findMany({ where, select: { id: true, destination: true, filename: true } })
if (id) { if (files?.length) {
fs.unlinkSync(origin_path) files.forEach(async ({ id, destination: dest, filename: fname }) => {
await prisma.file.update({ where: { id }, data: { filename, path, created_at } }) 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 { } else {
await prisma.file.create({ data: file }) 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' ...@@ -3,9 +3,12 @@ import { from, Observable } from 'rxjs'
import { map } from 'rxjs/operators' import { map } from 'rxjs/operators'
import { Server, Socket } from 'socket.io' import { Server, Socket } from 'socket.io'
import { WsService } from './ws.service' import { WsService } from './ws.service'
import { Logger, Module, UseInterceptors } from '@nestjs/common' import { Inject, Logger, Module, UseInterceptors, UsePipes } from '@nestjs/common'
import { WsMessageType, WsStatus, WsAccess, Command } from '../../common/enums' import { WsMessageType, WsStatus, WsAccess, Command, WsAccessCode, Events } from '../../common/enums'
import { TransformInterceptor } from '../../common/interceptors' import { TransformInterceptor } from '../../common/interceptors'
import { JwtService, TokenExpiredError } from '@nestjs/jwt'
import { AuthService } from '../auth/auth.service'
import { OnEvent } from '@nestjs/event-emitter'
/** /**
* WebSocket 网关 * WebSocket 网关
...@@ -25,7 +28,10 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws ...@@ -25,7 +28,10 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* *
* @param wsService - 注入的 WebSocket 服务实例,用于处理 WebSocket 相关操作。 * @param wsService - 注入的 WebSocket 服务实例,用于处理 WebSocket 相关操作。
*/ */
constructor(public readonly wsService: WsService) {} constructor(
public readonly wsService: WsService,
private readonly authService: AuthService
) {}
/** /**
* WebSocket 服务器实例 * WebSocket 服务器实例
*/ */
...@@ -39,7 +45,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws ...@@ -39,7 +45,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 })))
} }
/** /**
...@@ -56,38 +62,38 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws ...@@ -56,38 +62,38 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* @param client client * @param client client
* @param args * @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 auth = client.handshake?.auth ?? client.handshake?.headers
const ValidateData: WsTypes.LoginValidate<WsAccess> = { isValidate: true, errMsg: WsAccess.IsOnline }
if (!auth) { if (!auth) {
ValidateData.isValidate = false return this.handleInvalidAuth(client, WsAccess.NotAllowed, WsAccessCode.NotAllowed)
ValidateData.errMsg = WsAccess.NotAllowed
} }
const { token, deviceId } = auth const { token, deviceId } = auth
// 注册用户
if (!token) { if (!token) {
ValidateData.isValidate = false return this.handleInvalidAuth(client, WsAccess.InValidToken, WsAccessCode.InValidToken)
ValidateData.errMsg = WsAccess.InValidToken
} }
if (!deviceId) { if (!deviceId) {
ValidateData.isValidate = false return this.handleInvalidAuth(client, WsAccess.InvalidDeviceId, WsAccessCode.InvalidDeviceId)
ValidateData.errMsg = WsAccess.InvalidDeviceId
} }
if (!ValidateData.isValidate) { const verify = this.authService.verifyToken(String(token))
const msg = `${ValidateData.errMsg} token->${token} deviceId->${deviceId}}` if (!verify.isPass) {
client.emit(WsMessageType.Private, msg) const errorCode = verify.isExpired ? WsAccessCode.TokenExpired : WsAccessCode.InValidToken
Logger.error(msg) return this.handleInvalidAuth(client, WsAccess.TokenExpired, errorCode)
const resData: WsTypes.IWsResponse<WsStatus, WsAccess> = {
status: WsStatus.Offline,
message: ValidateData.errMsg,
device_id: deviceId
}
client.disconnect()
return resData
} }
return this.wsService.login(client, token, deviceId) 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 {
status: WsStatus.Offline,
message: errMsg,
device_id: client.handshake.auth?.deviceId
}
}
/** /**
* 用户断开连接 * 用户断开连接
* @param client client * @param client client
...@@ -103,7 +109,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws ...@@ -103,7 +109,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()
...@@ -113,7 +119,14 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws ...@@ -113,7 +119,14 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* 发送消息 * 发送消息
* @param payload * @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) 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 { Module } from '@nestjs/common'
import { WsGateway } from './ws.gateway' import { WsGateway } from './ws.gateway'
import { WsService } from './ws.service' import { WsService } from './ws.service'
// import { DeviceService } from '../device/device.service' import { AuthModule } from '../auth/auth.module'
@Module({ @Module({
imports: [], imports: [AuthModule],
providers: [WsGateway, WsService], providers: [WsGateway, WsService],
exports: [WsGateway] 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 { Server, Socket } from 'socket.io'
import { Logger } from '@nestjs/common' 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' import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'
@Injectable() @Injectable()
...@@ -25,15 +25,11 @@ export class WsService { ...@@ -25,15 +25,11 @@ export class WsService {
login(client: Socket, token: string, deviceId: number): WsTypes.IWsResponse<WsStatus, WsAccess> { login(client: Socket, token: string, deviceId: number): WsTypes.IWsResponse<WsStatus, WsAccess> {
const clientIsOnline: Socket = this.findClientByDeviceId(deviceId) const clientIsOnline: Socket = this.findClientByDeviceId(deviceId)
// 处理同一设备号在多处登录 // 处理同一设备号在多处登录
if (clientIsOnline) { this.handleDuplicateLogin(clientIsOnline, deviceId)
clientIsOnline.emit(WsMessageType.System, `设备-> ${deviceId} 已在别处上线, 此客户端 [${clientIsOnline.id}] 下线处理`)
clientIsOnline?.disconnect()
Logger.debug(`设备-> ${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,
...@@ -44,6 +40,19 @@ export class WsService { ...@@ -44,6 +40,19 @@ export class WsService {
return resData 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 { private findClientByDeviceId(deviceId: number): Socket {
return this.allClients?.get(this.clientIds.get(deviceId)) return this.allClients?.get(this.clientIds.get(deviceId))
} }
...@@ -51,7 +60,6 @@ export class WsService { ...@@ -51,7 +60,6 @@ export class WsService {
private get allClients(): Map<string, Socket> { private get allClients(): Map<string, Socket> {
return this.server?.sockets?.sockets return this.server?.sockets?.sockets
} }
/** /**
* 登出 * 登出
* @param client client * @param client client
...@@ -61,15 +69,14 @@ export class WsService { ...@@ -61,15 +69,14 @@ 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
} }
} }
return { data: { code: RESPONSE_CODE.SUCCESS, message: '登出成功' } } return { data: { code: RESPONSE_CODE.SUCCESS, message: '登出成功' } }
} }
@OnEvent(Events.OnConnectError) async onConnectError(out: WsTypes.WsConnError): Promise<void> {
async onConnError(out: WsTypes.WsConnError): Promise<void> {
const { device_id, message } = out const { device_id, message } = out
const client: Socket = this.findClientByDeviceId(device_id) const client: Socket = this.findClientByDeviceId(device_id)
if (client) { if (client) {
...@@ -88,7 +95,7 @@ export class WsService { ...@@ -88,7 +95,7 @@ export class WsService {
*/ */
resetClients(): void { resetClients(): void {
this.clientIds.clear() this.clientIds.clear()
Logger.debug('===WebSocket初始化成功!重置所有客户端连接数据===') Logger.warn('========WebSocket初始化成功!重置所有客户端连接数据========')
} }
/** /**
...@@ -96,13 +103,13 @@ export class WsService { ...@@ -96,13 +103,13 @@ export class WsService {
* @param messagePath 发布地址 * @param messagePath 发布地址
* @param response 响应数据 * @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) const res = this.server?.emit(WsMessageType.System, payload.data)
if (!res) { if (!res) {
Logger.log('Websocket Send Private Error->', payload) Logger.log('Websocket Send Private Error->', payload)
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败`, error: 'send error' }, HttpStatus.BAD_REQUEST) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败`, error: 'send error' }, HttpStatus.BAD_REQUEST)
} }
Logger.log('发送系统消息成功->', payload) Logger.log(payload)
return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' } return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' }
} }
...@@ -112,18 +119,18 @@ export class WsService { ...@@ -112,18 +119,18 @@ export class WsService {
* @param response 响应数据 * @param response 响应数据
* @param deviceId 接收者设备号 * @param deviceId 接收者设备号
*/ */
async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResData> { async sendPrivateMessage(payload: WsTypes.MessageBody<Command>): Promise<CommonTypes.IResData> {
if (!payload.device_id) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: '请求参数employeeId 必传', error: 'deviceId is required' }, HttpStatus.BAD_REQUEST) if (!payload.device_id) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: '请求参数device_id 必传', error: 'deviceId is required' }, HttpStatus.BAD_REQUEST)
const client = this.allClients?.get(this.clientIds.get(payload.device_id)) const client = this.allClients?.get(this.clientIds.get(payload.device_id))
const res = client?.emit(WsMessageType.Private, payload.data) const res = client?.emit(WsMessageType.Private, payload.data)
if (!res) { if (!res) {
Logger.error('Websocket Send Private Error->', payload) Logger.error('Websocket Send Private Error->', payload)
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败,客户端:(设备号->${payload.device_id}) 不在线`, error: 'send error' }, HttpStatus.BAD_REQUEST) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败,客户端:(设备号->${payload.device_id}) 不在线`, error: 'send error' }, HttpStatus.BAD_REQUEST)
} }
Logger.log('发送私有消息成功->', payload) Logger.log(payload)
return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' } return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' }
} }
onMessage(message:any){ onMessage(message: any) {
this.emit(Events.OnMessage,message) this.emit(Events.OnMessage, message)
} }
} }
import { Inject, Injectable, Logger } from '@nestjs/common'; import { Inject, Injectable, Logger } from '@nestjs/common'
import { Cron, Interval, Timeout } from '@nestjs/schedule'; import { Cron, Interval, Timeout } from '@nestjs/schedule'
import { EventEmitter2 } from '@nestjs/event-emitter'; import { EventEmitter2 } from '@nestjs/event-emitter'
import { Events } from '../common/enums'; import { Events } from '../common/enums'
@Injectable() @Injectable()
export class TasksService { export class TasksService {
private readonly logger = new Logger(TasksService.name);
constructor( constructor(
@Inject(EventEmitter2) @Inject(EventEmitter2)
private eventEmitter: EventEmitter2 private eventEmitter: EventEmitter2
){} ) {}
@Cron('0 10 * * * *') @Cron('0 10 0 * * *')
handleCron() { handleCron() {
this.eventEmitter.emit(Events.OnTaskStart) this.eventEmitter.emit(Events.OnDailyTaskStart)
Logger.debug('============开始定时任务============='); Logger.warn('============开始每日定时任务=============')
} }
// @Interval(5000) // @Interval(5000)
// handleInterval() { // handleInterval() {
// } // }
// @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()
// } // }
} }
declare module Broadcastypes {
}
\ No newline at end of file \ No newline at end of file
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 { ...@@ -104,11 +104,12 @@ declare namespace CommonTypes {
updated_at: Date | string updated_at: Date | string
} }
interface ISn { interface ISn {
sn: string sn: string
} }
interface IUser extends IDeviceId, ISn { interface IUser {
user: string user: string
mobile: string mobile: string
merchant_name: string merchant_name: string
......
...@@ -11,13 +11,11 @@ model log_config { ...@@ -11,13 +11,11 @@ model log_config {
}*/ }*/
declare namespace ConfigTypes { declare namespace ConfigTypes {
interface ILogConfig extends CommonTypes.IId, CommonTypes.IDeviceId, CommonTypes.ITime { interface ILogConfig extends 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 LogConfigResult = Partial<ILogConfig> type LogConfigResult = Partial<ILogConfig>
type LogConfigResponse = Omit<LogConfigResult, 'user_fields'> & { user_fields: string[] }
type LogConfigUpdate = CommonTypes.Optional<ILogConfig, 'device_id'> type LogConfigUpdate = CommonTypes.Optional<ILogConfig, 'device_id'>
} }
declare namespace DeviceTypes { declare namespace DeviceTypes {
/** type IQueryDevices = Partial<CommonTypes.IQueryBase & CommonTypes.ISn & CommonTypes.IUser & Pick<DeviceStatus.Status, 'status'>>
* 查询设备信息的查询对象接口
*
* @param user - 用户
* @param mobile - 手机号
* @param sn - 设备号
* @param skip - 可选,跳过的记录数量
* @param take - 可选,获取的记录数量
*/
type IQueryDevices = Partial<CommonTypes.IQueryBase & CommonTypes.ISn & IDeviceInfoBase>
interface IDeviceInfoBase extends CommonTypes.IUser { type TDeviceInfo = CommonTypes.ITime & Partial<CommonTypes.IUser>
/**
* 日志保存天数
*/
log_saved_days?: number
}
/**
* 设备信息接口
*/
interface IDeviceInfo extends Omit<IDeviceInfoBase,'device_id'>, CommonTypes.PartialOne<IDevice, 'id'>, DeviceStatus.Status {
/**
* 日志用户字段
*/
log_user_fields?: string[]
}
/** type TOneDeviceInfo = TDeviceInfo & CommonTypes.IDeviceId
* 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 UpdateDeviceInfo = CommonTypes.Optional<IDeviceInfoInput, 'device_id'> interface IDevice extends CommonTypes.IId, CommonTypes.ISn, DeviceStatus.Status, Partial<TDeviceInfo>, Partial<ConfigTypes.ILogConfig> {
/** fields: FieldTypes.TFieldRequird[]
* 表示设备结果的接口
*/
interface IDeviceResult extends IDevice {
/**
* 与设备关联的详细信息
*/
device_info: IDeviceInfoRes
} }
interface IDevice extends CommonTypes.IId,CommonTypes.ISn { interface IDeviceResult extends CommonTypes.IId, CommonTypes.ISn, Partial<Pick<CommonTypes.ITime, 'created_at'>> {
device_info: Partial<TDeviceInfo>
/**
* 设备创建的时间戳
*/
create_time?: number
}
/**
* 表示设备详细信息的接口
*/
interface IDeviceInfoRes extends CommonTypes.PartialOne<Omit<IDeviceInfoBase,'device_id'>,'sn'>, CommonTypes.PartialOne<IDeviceInfoInput, 'created_at' | 'updated_at' | 'id' | 'device_id'|'sn'> {
/**
* 与设备关联的日志配置信息
*/
log_config: Partial<ConfigTypes.ILogConfig> log_config: Partial<ConfigTypes.ILogConfig>
device_status: DeviceStatus.Status device_status: DeviceStatus.Status
fields: IFields[]
} }
/** interface IDeviceSaves extends CommonTypes.IDeviceId, Partial<CommonTypes.ISn> {
* 表示日志配置的接口 device_info?: Partial<TDeviceInfo>
*/ log_config?: Partial<ConfigTypes.ILogConfig>
interface ILogConfig { user_fields?: Array<Number>
/**
* 日志保存的天数
*/
log_saved_days: number
/**
* 日志用户字段的配置信息
*/
user_fields: ILogUserFields[]
} }
interface IFields {
/** field?: FieldTypes.TFieldRequird
* 表示日志用户字段的接口
*/
interface ILogUserFields {
/**
* 日志用户字段的详细信息
*/
log_user_field?: CommonTypes.Optional<Partial<UserFieldTypes.ILogUserFields>, 'name'>
} }
type TRemoveLogsResultByTask = (CommonTypes.IDeviceId & Pick<ConfigTypes.ILogConfig, 'log_saved_days'>)
} }
declare namespace DeviceStatus { declare namespace DeviceStatus {
interface IDeviceStatus extends CommonTypes.IDeviceId{ 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'> 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 { ...@@ -5,6 +5,7 @@ declare namespace FileTypes {
filename: string filename: string
path: string path: string
size: number size: number
destination: string
type: T type: T
} }
type FileUpload<T> = Omit<IFile<T>, 'id'> type FileUpload<T> = Omit<IFile<T>, 'id'>
......
declare namespace RelationsTypes { declare namespace RelationsTypes {
interface IRelation extends CommonTypes.IId { interface IRelation extends CommonTypes.IId, CommonTypes.IDeviceId {
config_id: number field_id: number
user_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 { ...@@ -8,10 +8,9 @@ declare namespace WsTypes {
type MessageBody<U, T = WsMsgType> = { type MessageBody<U, T = WsMsgType> = {
event: T event: T
data: U data: MessageData<U>
} & (T extends 'private' ? CommonTypes.IDeviceId : Partial<CommonTypes.IDeviceId>) } & (T extends 'private' ? CommonTypes.IDeviceId : Partial<CommonTypes.IDeviceId>)
interface IWsResponse<T, U> extends CommonTypes.IDeviceId { interface IWsResponse<T, U> extends CommonTypes.IDeviceId {
/** /**
* 状态码 * 状态码
...@@ -19,15 +18,14 @@ declare namespace WsTypes { ...@@ -19,15 +18,14 @@ declare namespace WsTypes {
status: T status: T
message: U message: U
} }
type LoginValidate<T> = { isValidate: boolean; errMsg: T } type LoginValidate<T> = { isValidate: boolean; errMsg: T; errorCode: number }
type MessageData<T, U = CommonTypes.TObj> = {
command: T | string
payload: U
}
type WsMessageData<T> = MessageData<T>
type MessageData<T> = {
command: T
days?: number
id?: string
interval?: number,
key?: string
}
type WsConnError = CommonTypes.IDeviceId & { message: string } type WsConnError = CommonTypes.IDeviceId & { message: string }
} }
# http://localhost:3000/device?pageIndex=1&pageSize=5 # http://localhost:3000/device?user=尹
# http://localhost:3000/device/addAll http://localhost:3000/device/addAll
# http://localhost:3000/device/task # http://localhost:3000/device/task
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
# content-type: application/json # content-type: application/json
# { # {
# "sn":"26DYD24513203857" # "sn":"test2002"
# } # }
# POST http://localhost:3000/device/addInfo HTTP/1.1 # POST http://localhost:3000/device/addInfo HTTP/1.1
...@@ -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":"1000068",
"data":{ # "data":{
"command":"getStorage", # "command":"getLog",
"payload":{ # "days":20,
"key":"recordList" # "interval":1000,
} # "force":true
} # }
} # }
# 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!