Commit 80f75154 by yixinjj

优化类型定义

1 parent 549940e1
...@@ -6,4 +6,5 @@ ...@@ -6,4 +6,5 @@
DATABASE_URL="mysql://limin:limin1018@192.168.1.129:3306/app_admin?schema=public" DATABASE_URL="mysql://limin:limin1018@192.168.1.129:3306/app_admin?schema=public"
SOCKET_PORT= 8080 SOCKET_PORT= 8080
APP_PORT= 3000
STATIC_PATH= "public" STATIC_PATH= "public"
\ No newline at end of file \ No newline at end of file
...@@ -47,7 +47,8 @@ export enum WsAccess { ...@@ -47,7 +47,8 @@ export enum WsAccess {
export enum WsConnEvents { export enum WsConnEvents {
OnConnected = 'device.connected', OnConnected = 'device.connected',
OnConnectError = 'device.connect.error' OnConnectError = 'device.connect.error',
OnOfflineAll='device.offline.all'
} }
export enum FileUploadEvents { export enum FileUploadEvents {
OnLogFileUploaded = 'log.file.uploaded' OnLogFileUploaded = 'log.file.uploaded'
......
...@@ -8,9 +8,9 @@ export const getCurrentTimestamp = (): number => { ...@@ -8,9 +8,9 @@ export const getCurrentTimestamp = (): number => {
/** /**
* @description: 统一返回体 * @description: 统一返回体
*/ */
export const BodyResponse: CommonTypes.TBodyResponse = (result, msg, code, error, url) => { export const BodyResponse: CommonTypes.TBodyResponse = (result, message, code, error, url) => {
if (msg instanceof Array) { if (message instanceof Array) {
msg = msg.join(';') message = message.join(';')
} }
const { total, data } = result || {} const { total, data } = result || {}
return { return {
...@@ -19,7 +19,7 @@ export const BodyResponse: CommonTypes.TBodyResponse = (result, msg, code, error ...@@ -19,7 +19,7 @@ export const BodyResponse: CommonTypes.TBodyResponse = (result, msg, code, error
total, total,
error, error,
timestamp: getCurrentTimestamp(), timestamp: getCurrentTimestamp(),
msg: data?.msg || msg || RESPONSE_MSG.SUCCESS, message: data?.message || message || RESPONSE_MSG.SUCCESS,
code: data?.code || code || RESPONSE_CODE.SUCCESS code: data?.code || code || RESPONSE_CODE.SUCCESS
} }
} }
export * from './doc'
export * from './ws'
\ No newline at end of file \ No newline at end of file
import { INestApplication } from '@nestjs/common'
import { ValidationPipe } from '../common/pipes/validation.pipe'
import { LoggingInterceptor } from '../common/interceptors/logging.interceptor'
import { ExceptionsFilter, HttpExceptionFilter } from '../common/filters'
import { docBuilder } from './doc'
import { wsRedisAdapter } from './ws'
import { join } from 'path'
export default class Initializer {
static async use(app) {
app.useGlobalFilters(new ExceptionsFilter())
app.useGlobalFilters(new HttpExceptionFilter())
app.enableCors()
// 全局使用中间件
// app.use(logger)
// app.useGlobalFilters(new ValidateExceptionFilter())
// 全局管道
app.useGlobalPipes(new ValidationPipe())
// 全局拦截器
app.useGlobalInterceptors(new LoggingInterceptor())
app.useStaticAssets(join(__dirname, '..', '..', process.env.STATIC_PATH))
// 初始化文档
docBuilder(app)
// 初始化websocket
await wsRedisAdapter(app)
}
}
import { NestFactory } from '@nestjs/core' import { NestFactory } from '@nestjs/core'
import { HttpExceptionFilter, ExceptionsFilter } from './common/filters'
import { ValidationPipe } from './common/pipes/validation.pipe'
import { LoggingInterceptor } from './common/interceptors/logging.interceptor'
import { AppModule } from './app.module' import { AppModule } from './app.module'
import { join } from 'path'
import { NestExpressApplication } from '@nestjs/platform-express' import { NestExpressApplication } from '@nestjs/platform-express'
import { docBuilder, wsRedisAdapter } from './initor' import Initializer from './initor'
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule) const app = await NestFactory.create<NestExpressApplication>(AppModule)
await Initializer.use(app)
// 全局使用中间件 await app.listen(process.env.APP_PORT)
// app.use(logger)
// 全局过滤器
app.useGlobalFilters(new ExceptionsFilter())
app.useGlobalFilters(new HttpExceptionFilter())
app.enableCors()
await wsRedisAdapter(app)
// app.useWebSocketAdapter(new WsAdapter(app))
// app.useGlobalFilters(new ValidateExceptionFilter())
// 全局管道
// app.useGlobalPipes(new ValidationPipe());
// 全局拦截器
// app.useGlobalInterceptors(new LoggingInterceptor());
app.useStaticAssets(join(__dirname, '..', process.env.STATIC_PATH))
docBuilder(app)
await app.listen(3000)
} }
bootstrap() bootstrap()
...@@ -43,7 +43,7 @@ export class DeviceController { ...@@ -43,7 +43,7 @@ export class DeviceController {
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象 * @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/ */
@Post('/add') @Post('/add')
addDevice(@Body() param: AddDeviceDto): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> { addDevice(@Body() param: AddDeviceDto): Promise<CommonTypes.IResponseBase> {
// console.log(param) // console.log(param)
return this.deviceService.addDevice(param) return this.deviceService.addDevice(param)
} }
...@@ -54,7 +54,7 @@ export class DeviceController { ...@@ -54,7 +54,7 @@ export class DeviceController {
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象 * @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/ */
@Post('/addInfo') @Post('/addInfo')
addDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> { addDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> {
// console.log(param) // console.log(param)
return this.deviceService.addDeviceInfo(param) return this.deviceService.addDeviceInfo(param)
} }
...@@ -65,7 +65,7 @@ export class DeviceController { ...@@ -65,7 +65,7 @@ export class DeviceController {
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象 * @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/ */
@Post('/updateInfo') @Post('/updateInfo')
updateDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> { updateDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> {
return this.deviceService.updateDeviceInfo(param) return this.deviceService.updateDeviceInfo(param)
} }
...@@ -77,10 +77,22 @@ export class DeviceController { ...@@ -77,10 +77,22 @@ export class DeviceController {
*/ */
@OnEvent(WsConnEvents.OnConnected) @OnEvent(WsConnEvents.OnConnected)
@Post('/upsertStatus') @Post('/upsertStatus')
async upsertDeviceStatus(@Body() param: DeviceStatusDto): Promise<void | CommonTypes.IResData<CommonTypes.IResponseBase>> { async upsertDeviceStatus(@Body() param: DeviceStatusDto): Promise<void | CommonTypes.IResponseBase> {
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(WsConnEvents.OnConnectError, out) this.eventEmitter.emit(WsConnEvents.OnConnectError, out)
}) })
} }
/**
* 重置所有设备状态的方法
* 该方法接收一个包含设备状态的DTO对象,并返回更新后的设备状态
* @param param - 包含设备状态的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@Post('/offlineAll')
@OnEvent(WsConnEvents.OnOfflineAll)
async resetAllDeviceStatus(): Promise<void | CommonTypes.IResponseBase> {
return await this.deviceService.resetAllDeviceStatus()
}
} }
import { Inject, Injectable, HttpException, HttpStatus } from '@nestjs/common' import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } from '@nestjs/common'
// import { Repository, Connection, getRepository } from 'typeorm'; // import { Repository, Connection, getRepository } from 'typeorm';
// import { InjectRepository } from '@nestjs/typeorm'; // import { InjectRepository } from '@nestjs/typeorm';
// import { Device as DeviceEntity } from '../entities/Device' // import { Device as DeviceEntity } from '../entities/Device'
...@@ -6,11 +6,14 @@ import { PrismaService } from 'nestjs-prisma' ...@@ -6,11 +6,14 @@ import { PrismaService } from 'nestjs-prisma'
import { RESPONSE_CODE, WsConnEvents, WsStatus } from '../../common/enums' import { RESPONSE_CODE, WsConnEvents, WsStatus } from '../../common/enums'
@Injectable() @Injectable()
export class DeviceService { 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,
) {} ) {}
async onModuleInit() {
this.resetAllDeviceStatus()
}
async findAll({ user, mobile, sn, skip, take }: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData<DeviceTypes.IDeviceInfo[]>> { async findAll({ user, mobile, sn, skip, take }: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData<DeviceTypes.IDeviceInfo[]>> {
const where = { const where = {
...@@ -28,7 +31,7 @@ export class DeviceService { ...@@ -28,7 +31,7 @@ export class DeviceService {
} }
} }
} }
const result: DeviceTypes.IDeviceResult[] = await this.prisma.device.findMany({ const result: Omit<DeviceTypes.IDeviceResult,'id'>[] = await this.prisma.device.findMany({
skip, skip,
take, take,
select: { select: {
...@@ -60,7 +63,7 @@ export class DeviceService { ...@@ -60,7 +63,7 @@ export class DeviceService {
}, },
where where
}) })
const total = 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.IDeviceInfo[] = result.reduce((pre: DeviceTypes.IDeviceInfo[], cur: DeviceTypes.IDeviceResult) => {
...@@ -79,27 +82,27 @@ export class DeviceService { ...@@ -79,27 +82,27 @@ export class DeviceService {
return resBody return resBody
} }
async addDevice(device: Omit<DeviceTypes.IDevice, 'id' | 'create_time'>): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> { async addDevice(device: Omit<DeviceTypes.IDevice, 'id' | 'create_time'>): Promise<CommonTypes.IResponseBase> {
await this.prisma.$transaction(async prisma => { await this.prisma.$transaction(async prisma => {
const { id } = await prisma.device.create({ data: device, select: { id: true } }) const { id } = await prisma.device.create({ data: device, select: { id: true } })
// await this.addDeviceInfo({device_id:id}) // await this.addDeviceInfo({device_id:id})
await prisma.device_info.create({ data: { device_id: id, created_at: new Date(), updated_at: new Date() } }) await prisma.device_info.create({ data: { device_id: id, 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 } })
}) })
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '添加设备成功' } } return { code: RESPONSE_CODE.SUCCESS, message: '添加设备成功' }
} }
async addDeviceInfo(deviceInfo: DeviceTypes.IDeviceInfoInput): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> { async addDeviceInfo(deviceInfo: Omit<DeviceTypes.IDeviceInfoInput,'sn'>): Promise<CommonTypes.IResponseBase> {
deviceInfo.created_at = new Date() deviceInfo.created_at = new Date()
deviceInfo.updated_at = new Date() deviceInfo.updated_at = new Date()
await this.prisma.$transaction(async prisma => { await this.prisma.$transaction(async prisma => {
await prisma.device_info.create({ data: deviceInfo }) await prisma.device_info.create({ data: deviceInfo })
await prisma.device_status.create({ data: { device_id: deviceInfo.device_id, status: WsStatus.Offline } }) await prisma.device_status.create({ data: { device_id: deviceInfo.device_id, status: WsStatus.Offline } })
}) })
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '添加设备信息成功' } } return { code: RESPONSE_CODE.SUCCESS, message: '添加设备信息成功' }
} }
async updateDeviceInfo(deviceInfo: DeviceTypes.IDeviceInfoInput): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> { async updateDeviceInfo(deviceInfo: Omit<DeviceTypes.IDeviceInfoInput,'sn'>): Promise<CommonTypes.IResponseBase> {
const { device_id, ...data } = deviceInfo const { device_id, ...data } = deviceInfo
data.updated_at = new Date() data.updated_at = new Date()
await this.prisma.device_info.update({ await this.prisma.device_info.update({
...@@ -108,9 +111,9 @@ export class DeviceService { ...@@ -108,9 +111,9 @@ export class DeviceService {
}, },
data data
}) })
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '设备信息更新成功' } } return { code: RESPONSE_CODE.SUCCESS, message: '设备信息更新成功' }
} }
async upsertDeviceStatus(data: DeviceStatus.IDeviceStatus): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> { async upsertDeviceStatus(data: DeviceStatus.IDeviceStatus): Promise<CommonTypes.IResponseBase> {
await this.prisma.device_status.upsert({ await this.prisma.device_status.upsert({
where: { where: {
device_id: data.device_id device_id: data.device_id
...@@ -120,6 +123,15 @@ export class DeviceService { ...@@ -120,6 +123,15 @@ export class DeviceService {
status: data.status status: data.status
} }
}) })
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '设备状态更新成功' } } return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
}
async resetAllDeviceStatus(): Promise<CommonTypes.IResponseBase> {
Logger.debug('===重置所有设备状态===')
await this.prisma.device_status.updateMany({
data: {
status: WsStatus.Offline
}
})
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
} }
} }
...@@ -42,7 +42,7 @@ export class FileController { ...@@ -42,7 +42,7 @@ export class FileController {
* @returns 返回删除结果 * @returns 返回删除结果
*/ */
@Get('delete') @Get('delete')
async remove(@Query() { id }: FileDto): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> { async remove(@Query() { id }: FileDto): Promise<CommonTypes.IResponseBase> {
return await this.fileService.remove(+id) return await this.fileService.remove(+id)
} }
......
...@@ -26,7 +26,7 @@ export class FileService { ...@@ -26,7 +26,7 @@ export class FileService {
* @param file - 要保存的文件对象,包含文件名、路径、创建时间等信息。 * @param file - 要保存的文件对象,包含文件名、路径、创建时间等信息。
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。 * @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/ */
async save(file: FileTypes.IFile<DocTypes>): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> { async save(file: FileTypes.IFile<DocTypes>): Promise<CommonTypes.IResponseBase> {
const { filename, path, created_at, ...where } = file const { filename, path, created_at, ...where } = file
this.prisma.$transaction(async prisma => { this.prisma.$transaction(async prisma => {
const { id, path: origin_path } = (await prisma.file.findFirst({ where, select: { id: true, path: true } })) || {} const { id, path: origin_path } = (await prisma.file.findFirst({ where, select: { id: true, path: true } })) || {}
...@@ -37,7 +37,7 @@ export class FileService { ...@@ -37,7 +37,7 @@ export class FileService {
return await prisma.file.create({ data: file }) return await prisma.file.create({ data: file })
} }
}) })
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '文件保存成功' } } return { code: RESPONSE_CODE.SUCCESS, message: '文件保存成功' }
} }
/** /**
...@@ -46,16 +46,15 @@ export class FileService { ...@@ -46,16 +46,15 @@ export class FileService {
* @param id - 要移除的文件的唯一标识符。 * @param id - 要移除的文件的唯一标识符。
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。 * @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/ */
async remove(id: number): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> { async remove(id: number): Promise<CommonTypes.IResponseBase> {
await this.prisma.$transaction(async prisma => { await this.prisma.$transaction(async prisma => {
const { path } = (await prisma.file.findFirst({ where: { id }, select: { path: true } })) || {} const { path } = (await prisma.file.findFirst({ where: { id }, select: { path: true } })) || {}
await prisma.file.delete({ where: { id } }) await prisma.file.delete({ where: { id } })
fs.unlinkSync(path) fs.unlinkSync(path)
}) })
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '删除成功' } } return { code: RESPONSE_CODE.SUCCESS, message: '删除成功' }
} }
async downloadAll() { async downloadAll() {
const uploadDir = this.configService.get('file').root const uploadDir = this.configService.get('file').root
const tarStream = new tar.Stream() const tarStream = new tar.Stream()
......
...@@ -58,7 +58,6 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws ...@@ -58,7 +58,6 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* @param args * @param args
*/ */
handleConnection(client: Socket, ...args: any[]): WsTypes.IWsResponse<WsStatus, WsAccess> { handleConnection(client: Socket, ...args: any[]): WsTypes.IWsResponse<WsStatus, WsAccess> {
Logger.log('用户连接上', client.id)
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 } const ValidateData: WsTypes.LoginValidate<WsAccess> = { isValidate: true, errMsg: WsAccess.IsOnline }
if (!auth) { if (!auth) {
......
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'
@Module({ @Module({
imports: [], imports: [],
providers: [WsGateway,WsService], providers: [WsGateway, WsService],
exports: [WsGateway], exports: [WsGateway]
}) })
export class WsModule {} export class WsModule {}
import { HttpException, HttpStatus, Injectable, Inject } from '@nestjs/common' import { HttpException, HttpStatus, Injectable, Inject, OnApplicationBootstrap } 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 { WSResponse } from '../message/model/ws-response.model'; // import { WSResponse } from '../message/model/ws-response.model';
...@@ -7,18 +7,21 @@ import { Logger } from '@nestjs/common' ...@@ -7,18 +7,21 @@ import { Logger } from '@nestjs/common'
// import { User } from '@/entities/user.entity'; // import { User } from '@/entities/user.entity';
import { RESPONSE_CODE, WsAccess, WsConnEvents, WsMessageType, WsStatus } from '../../common/enums' import { RESPONSE_CODE, WsAccess, WsConnEvents, WsMessageType, WsStatus } from '../../common/enums'
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter' import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'
// import { DeviceService } from '../device/device.service'
@Injectable() @Injectable()
export class WsService { export class WsService {
constructor( constructor(
@Inject(EventEmitter2) @Inject(EventEmitter2)
private eventEmitter: EventEmitter2 private eventEmitter: EventEmitter2
// private readonly deviceService: DeviceService
) {} ) {}
// ws 服务器, gateway 传进来 // ws 服务器, gateway 传进来
server: Server server: Server
// 存储连接的客户端 // 存储连接的客户端
clientIds: Map<number, string> = new Map() clientIds: Map<number, string> = new Map()
/** /**
* 登录 * 登录
* @param client socket 客户端 * @param client socket 客户端
...@@ -27,13 +30,17 @@ export class WsService { ...@@ -27,13 +30,17 @@ 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)
// 处理同一工号在多处登录 // 处理同一设备号在多处登录
clientIsOnline?.emit(WsMessageType.System, `设备 ${deviceId} 已在别处上线, 此客户端下线处理`) if (clientIsOnline) {
clientIsOnline?.disconnect() 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)
Logger.log(`${deviceId} connected, onLine: ${this.allClients.size}`) const message = `Device-> ${deviceId} [${client.id}] Has Connected, OnLine Number: ${this.allClients.size}`
this.server.emit(WsMessageType.System, `${deviceId} connected, onLine: ${this.allClients.size}`) Logger.debug(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,
status: WsStatus.Online, status: WsStatus.Online,
...@@ -60,25 +67,26 @@ export class WsService { ...@@ -60,25 +67,26 @@ 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.log(`${deviceId} disconnected, onLine: ${this.clientIds.size}`) Logger.debug(`Device-> ${deviceId} [${id}] Logout, OnLine Number: ${this.clientIds.size}`)
this.emit(WsConnEvents.OnConnected, { status: WsStatus.Offline, message: WsAccess.IsOffline, device_id: deviceId }) this.emit(WsConnEvents.OnConnected, { status: WsStatus.Offline, message: WsAccess.IsOffline, device_id: deviceId })
break break
} }
} }
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '登出成功' } } return { data: { code: RESPONSE_CODE.SUCCESS, message: '登出成功' } }
} }
@OnEvent(WsConnEvents.OnConnectError) @OnEvent(WsConnEvents.OnConnectError)
async onConnError(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) {
Logger.error(`设备-> ${device_id} [${client.id}] 连接异常, 原因: ${message}`)
client.emit(WsMessageType.Private, message) client.emit(WsMessageType.Private, message)
client.disconnect() client.disconnect()
} }
} }
private emit(event: WsConnEvents, data: WsTypes.IWsResponse<WsStatus, WsAccess>) { private emit(event: WsConnEvents, data?: WsTypes.IWsResponse<WsStatus, WsAccess>) {
const { message, ...rest } = data const { message, ...rest } = data || {}
this.eventEmitter.emit(event, rest) return this.eventEmitter.emit(event, rest)
} }
/** /**
...@@ -86,6 +94,7 @@ export class WsService { ...@@ -86,6 +94,7 @@ export class WsService {
*/ */
resetClients(): void { resetClients(): void {
this.clientIds.clear() this.clientIds.clear()
Logger.debug('===WebSocket初始化成功!重置所有客户端连接数据===')
} }
/** /**
...@@ -93,14 +102,14 @@ export class WsService { ...@@ -93,14 +102,14 @@ export class WsService {
* @param messagePath 发布地址 * @param messagePath 发布地址
* @param response 响应数据 * @param response 响应数据
*/ */
async sendPublicMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> { async sendPublicMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResponseBase> {
console.log('websocket send', payload)
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 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)
} }
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '发送成功' } } Logger.log('发送系统消息成功->', payload)
return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' }
} }
/** /**
...@@ -109,15 +118,16 @@ export class WsService { ...@@ -109,15 +118,16 @@ export class WsService {
* @param response 响应数据 * @param response 响应数据
* @param deviceId 接收者设备号 * @param deviceId 接收者设备号
*/ */
async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResData<CommonTypes.IResponseBase>> { async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResponseBase> {
console.log('websocket send', payload) console.log('websocket send', payload)
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: '请求参数employeeId 必传', 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.log('websocket send 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)
} }
return { data: { code: RESPONSE_CODE.SUCCESS, msg: '发送成功' } } Logger.log('发送私有消息成功->', payload)
return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' }
} }
} }
...@@ -13,7 +13,7 @@ declare namespace CommonTypes { ...@@ -13,7 +13,7 @@ declare namespace CommonTypes {
/** /**
* 响应信息 * 响应信息
*/ */
msg?: string | string[] message?: string | string[]
/** /**
* 请求接口路径 * 请求接口路径
...@@ -25,57 +25,49 @@ declare namespace CommonTypes { ...@@ -25,57 +25,49 @@ declare namespace CommonTypes {
*/ */
timestamp?: number timestamp?: number
} }
/**
* 定义一个基本的分页对象接口 type IPage = {
*/ /**
interface IPageBase { * 总条数
*/
total: number
/** /**
* 页码 * 页码
*/ */
pageIndex?: number pageIndex: number
/** /**
* 当前页条数 * 当前页条数
*/ */
pageSize?: number pageSize: number
} }
/** /**
* 扩展分页对象接口,包括总条数 * 扩展分页对象接口,包括总条数
*/ */
interface IPagenation extends IPageBase { type IPagenation = Partial<IPage>
/**
* 总条数 /**
*/
total?: number
}
/** /**
* 响应数据接口,继承自分页对象接口,包含业务数据 * 响应数据接口,继承自分页对象接口,包含业务数据
*/ */
interface IResData<T = any> extends IPageBase { interface IResData<T = any> extends IPagenation {
/** /**
* 业务数据 * 业务数据
*/ */
data?: T data?: T
/**
* 总条数
*/
total?: number
} }
/** /**
* 全局响应体接口,继承自分页对象、响应基本对象和响应数据接口 * 全局响应体接口,继承自分页对象、响应基本对象和响应数据接口
*/ */
interface IResponse<T> extends IPagenation, IResponseBase { type IResponse<T> = IResData<T> & IResponseBase
/**
* 业务数据
*/
data?: T
}
/** /**
* 扩展分页对象接口,用于传入查询参数,包含附加属性 * 扩展分页对象接口,用于传入查询参数,包含附加属性
*/ */
// interface IPageIn extends IPageBase { // interface IPageIn extends IPageBase {
// [key: string]: any // [key: string]: any
// } // }
type IPageIn = IPageBase & TObj type IPageIn = Omit<IPagenation, 'total'> & TObj
/** /**
* 定义一个基本的查询对象接口 * 定义一个基本的查询对象接口
*/ */
...@@ -98,8 +90,30 @@ declare namespace CommonTypes { ...@@ -98,8 +90,30 @@ declare namespace CommonTypes {
* @param url - 路径 * @param url - 路径
* @returns 返回给前端的响应体 * @returns 返回给前端的响应体
*/ */
type TBodyResponse = (result: IResData, msg?: string | string[], code?: number, error?: any, url?: string) => IResponse<IResData<any>> type TBodyResponse = (result: IResData, message?: string | string[], code?: number, error?: any, url?: string) => IResponse<IResData<any>>
type Optional<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>> type Optional<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>
type PartialOne<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
type TObj = { [key: string]: any } type TObj = { [key: string]: any }
interface IDeviceId {
device_id: number
}
interface IId {
id: number
}
interface ITime {
created_at: Date | string
updated_at: Date | string
}
interface ISn {
sn: string
}
interface IUser extends IDeviceId, ISn {
user: string
mobile: string
merchant_name: string
}
} }
...@@ -10,13 +10,9 @@ model log_config { ...@@ -10,13 +10,9 @@ model log_config {
user_fields log_config_userfield_relation[] user_fields log_config_userfield_relation[]
}*/ }*/
declare module ConfigTypes { declare namespace ConfigTypes {
interface ILogConfig { interface ILogConfig extends CommonTypes.IId, CommonTypes.IDeviceId, CommonTypes.ITime {
id: number
device_id: number
log_saved_days: number log_saved_days: number
created_at: Date | string
updated_at: Date | string
user_fields: DeviceTypes.ILogUserFields[] user_fields: DeviceTypes.ILogUserFields[]
} }
type LogConfigQuery = Pick<Partial<ILogConfig>, 'device_id'> & CommonTypes.IQueryBase type LogConfigQuery = Pick<Partial<ILogConfig>, 'device_id'> & CommonTypes.IQueryBase
......
...@@ -8,24 +8,9 @@ declare module DeviceTypes { ...@@ -8,24 +8,9 @@ declare module DeviceTypes {
* @param skip - 可选,跳过的记录数量 * @param skip - 可选,跳过的记录数量
* @param take - 可选,获取的记录数量 * @param take - 可选,获取的记录数量
*/ */
interface IQueryDevices extends CommonTypes.IQueryBase { type IQueryDevices = Partial<CommonTypes.IQueryBase & CommonTypes.ISn & IDeviceInfoBase>
user?: string
mobile?: string interface IDeviceInfoBase extends CommonTypes.IUser {
sn?: string
}
interface IDeviceInfoBase {
/**
* 用户
*/
user?: string
/**
* 手机号
*/
mobile?: string
/**
* 商户名称
*/
merchant_name?: string
/** /**
* 日志保存天数 * 日志保存天数
*/ */
...@@ -34,7 +19,7 @@ declare module DeviceTypes { ...@@ -34,7 +19,7 @@ declare module DeviceTypes {
/** /**
* 设备信息接口 * 设备信息接口
*/ */
interface IDeviceInfo extends IDeviceInfoBase, IDevice, DeviceStatus.Status { interface IDeviceInfo extends Omit<IDeviceInfoBase,'device_id'>, CommonTypes.PartialOne<IDevice, 'id'>, DeviceStatus.Status {
/** /**
* 日志用户字段 * 日志用户字段
*/ */
...@@ -56,13 +41,9 @@ declare module DeviceTypes { ...@@ -56,13 +41,9 @@ declare module DeviceTypes {
log_config log_config? log_config log_config?
} }
*/ */
interface IDeviceInfoInput extends IDeviceInfoBase { interface IDeviceInfoInput extends IDeviceInfoBase, CommonTypes.IId, CommonTypes.IDeviceId, CommonTypes.ITime {
id?: number
last_log_upload_time?: string last_log_upload_time?: string
last_log_remove_time?: string last_log_remove_time?: string
device_id: number
created_at?: Date
updated_at?: Date
} }
type UpdateDeviceInfo = CommonTypes.Optional<IDeviceInfoInput, 'device_id'> type UpdateDeviceInfo = CommonTypes.Optional<IDeviceInfoInput, 'device_id'>
...@@ -76,15 +57,8 @@ declare module DeviceTypes { ...@@ -76,15 +57,8 @@ declare module DeviceTypes {
device_info: IDeviceInfoRes device_info: IDeviceInfoRes
} }
interface IDevice { interface IDevice extends CommonTypes.IId,CommonTypes.ISn {
/**
* 设备的唯一标识符
*/
id?: number
/**
* 设备的序列号
*/
sn: string
/** /**
* 设备创建的时间戳 * 设备创建的时间戳
*/ */
...@@ -94,31 +68,7 @@ declare module DeviceTypes { ...@@ -94,31 +68,7 @@ declare module DeviceTypes {
/** /**
* 表示设备详细信息的接口 * 表示设备详细信息的接口
*/ */
interface IDeviceInfoRes extends IDeviceInfoBase { interface IDeviceInfoRes extends CommonTypes.PartialOne<Omit<IDeviceInfoBase,'device_id'>,'sn'>, CommonTypes.PartialOne<IDeviceInfoInput, 'created_at' | 'updated_at' | 'id' | 'device_id'|'sn'> {
/**
* 设备信息的唯一标识符
*/
id?: number
/**
* 设备的唯一标识符(外键)
*/
device_id?: number
/**
* 上次日志上传的时间
*/
last_log_upload_time?: string
/**
* 上次日志移除的时间
*/
last_log_remove_time?: string
/**
* 设备信息创建的时间戳
*/
created_at?: number
/**
* 设备信息更新的时间戳
*/
updated_at?: number
/** /**
* 与设备关联的日志配置信息 * 与设备关联的日志配置信息
*/ */
......
declare module DeviceStatus { declare namespace DeviceStatus {
interface IDeviceStatus { interface IDeviceStatus extends CommonTypes.IDeviceId{
device_id: number
status: number status: number
} }
type Status = Omit<IDeviceStatus,'device_id'> type Status = Omit<IDeviceStatus,'device_id'>
......
declare namespace FileTypes { declare namespace FileTypes {
interface IFile<T> { interface IFile<T> extends CommonTypes.IDeviceId, Pick<CommonTypes.ITime,'created_at'> {
originalname: string originalname: string
mimetype: string mimetype: string
filename: string filename: string
path: string path: string
size: number, size: number,
device_id: number,
created_at: Date,
type: T type: T
} }
} }
declare module RelationsTypes { declare namespace RelationsTypes {
interface IRelation { interface IRelation extends CommonTypes.IId {
id: number
config_id: number config_id: number
user_field_id: number user_field_id: number
} }
......
declare module UserFieldTypes { declare namespace UserFieldTypes {
interface ILogUserFields { interface ILogUserFields extends CommonTypes.IId {
id: number
name: string name: string
} }
} }
declare module WsTypes { declare namespace WsTypes {
abstract class WebSocketGateway<S, T, U> { abstract class WebSocketGateway<S, T, U> {
server: S server: S
abstract subPrivate(data: any): T abstract subPrivate(data: any): T
...@@ -9,16 +9,10 @@ declare module WsTypes { ...@@ -9,16 +9,10 @@ declare module WsTypes {
type MessageBody<U, T = WsMsgType> = { type MessageBody<U, T = WsMsgType> = {
event: T event: T
data: U data: U
} & (T extends 'private' ? IPrivateData : Partial<IPrivateData>) } & (T extends 'private' ? CommonTypes.IDeviceId : Partial<CommonTypes.IDeviceId>)
interface IPrivateData {
/**
* 接收设备号
*/
device_id: number
}
interface IWsResponse<T, U> extends IPrivateData { interface IWsResponse<T, U> extends CommonTypes.IDeviceId {
/** /**
* 状态码 * 状态码
*/ */
...@@ -33,5 +27,5 @@ declare module WsTypes { ...@@ -33,5 +27,5 @@ declare module WsTypes {
type WsMessageData<T> = MessageData<T> type WsMessageData<T> = MessageData<T>
type WsConnError = IPrivateData & { message: string } type WsConnError = CommonTypes.IDeviceId & { message: string }
} }
...@@ -31,29 +31,29 @@ ...@@ -31,29 +31,29 @@
# POST http://localhost:3000/broadcast/message HTTP/1.1 POST http://localhost:3000/broadcast/message HTTP/1.1
# content-type: application/json content-type: application/json
# { {
# "event":"private", "event":"private",
# "device_id":1, "device_id":1,
# "data":{ "data":{
# "order":"logs", "order":"logs",
# "payload":{ "payload":{
# "message":"log message" "message":"log message"
# } }
# } }
# } }
# http://localhost:3000/file/delete?id=16 # http://localhost:3000/file/delete?id=16
# http://localhost:3000/config?device_id=2 # http://localhost:3000/config?device_id=2
POST http://localhost:3000/config/add HTTP/1.1 # POST http://localhost:3000/config/add HTTP/1.1
content-type: application/json # content-type: application/json
{ # {
"device_id":1, # "device_id":1,
"log_saved_days":8, # "log_saved_days":8,
"user_fields":[1,2,3,4] # "user_fields":[1,2,3,4]
} # }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!