Commit 85d8752f by yixinjj

新增日志config

1 parent 83be0ccc
......@@ -37,6 +37,7 @@
"@nestjs/bull": "^0.1.1",
"@nestjs/common": "^10.4.1",
"@nestjs/core": "^10.4.1",
"@nestjs/event-emitter": "^2.0.4",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^7.0.0",
"@nestjs/platform-express": "^10.4.1",
......
......@@ -20,8 +20,9 @@ import { FileModule } from './modules/file/file.module'
import { WsModule } from './modules/ws/ws.module'
// import { WsGateway } from './modules/ws/ws.gateway';
import { SseModule } from './modules/sse/sse.module'
import { LogConfigModule } from './modules/config/config.module';
import { BroadcastModule } from './modules/broadcast/broadcast.module'
import { EventEmitterModule } from '@nestjs/event-emitter';
@Module({
imports: [
ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')),
......@@ -36,11 +37,11 @@ import { BroadcastModule } from './modules/broadcast/broadcast.module'
inject: [ConfigService]
}),
ScheduleModule.forRoot(),
EventEmitterModule.forRoot(),
// TasksModule,
// AudioModule,
AuthModule,
HelloModule,
DeviceModule,
ExceptionModule,
RoleGuardModule,
EmailModule,
......@@ -48,7 +49,9 @@ import { BroadcastModule } from './modules/broadcast/broadcast.module'
FileModule,
SseModule,
WsModule,
BroadcastModule
DeviceModule,
BroadcastModule,
LogConfigModule
],
})
export class AppModule {
......
/**
/**
* @description: 响应码
*/
export enum RESPONSE_CODE {
export enum RESPONSE_CODE {
NOSUCCESS = -1, // 表示请求成功,但操作未成功
SUCCESS = 200, // 请求成功
BAD_REQUEST = 400, // 请求错误
UNAUTHORIZED = 401, // 未授权
FORBIDDEN = 403, // 禁止访问
NOT_FOUND = 404, // 资源未找到
INTERNAL_SERVER_ERROR = 500, // 服务器错误
}
INTERNAL_SERVER_ERROR = 500 // 服务器错误
}
/**
/**
* @description: 请求提示语
*/
export enum RESPONSE_MSG {
export enum RESPONSE_MSG {
SUCCESS = '请求成功',
FAILURE = '请求失败',
}
FAILURE = '请求失败'
}
export enum WsMessageType {
export enum WsMessageType {
/**
* 私有订阅
*/
......@@ -28,4 +28,22 @@
* 系统订阅
*/
System = 'system'
}
\ No newline at end of file
}
export enum WsStatus {
Disuse = 0,
Online = 1,
Offline = 2
}
export enum WsAccess {
NotAllowed = '无访问权限',
InValidToken = '无效token',
InvalidDeviceId = '无效设备id',
IsOnline = '通过验证,设备上线',
IsOffline = '设备下线',
}
export enum WsConnEvents {
Connection='connection',
}
......@@ -3,7 +3,8 @@ import { PipeTransform, Injectable } from '@nestjs/common'
@Injectable()
export class PagesPipe implements PipeTransform<CommonTypes.IPageIn> {
async transform(value: CommonTypes.IPageIn) {
const { pageIndex, pageSize } = value
console.log(value)
const { pageIndex=1, pageSize =10 } = value
const skip = (pageIndex - 1) * pageSize
value.skip = +skip < 0 ? 0 : skip
value.take = +pageSize
......
export * from './pages-arguments.pipe'
export * from './arguments.pipe'
export * from "./parse-int.pipe";
export * from "./validation.pipe";
import { ApiProperty } from "@nestjs/swagger"
import { IsNotEmpty, IsNumber } from "class-validator"
/*
model log_config {
id Int @id @default(autoincrement())
device_id Int @unique(map: "device_id") @default(0)
log_saved_days Int? @default(7) @db.TinyInt
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device")
device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device_info")
user_fields log_config_userfield_relation[]
}*/
export class LogConfigDto {
@ApiProperty({
type: Number,
description: '设备信息ID',
default: 0
})
id: number
@ApiProperty({
type: Number,
description: '设备ID',
default: 0
})
@IsNumber({},{ message: '设备ID必须是数字'})
@IsNotEmpty({ message: '设备ID不能为空' })
device_id: number
@ApiProperty({
type: Number,
description: '日志保存天数',
default: ''
})
log_saved_days: number
@ApiProperty({
type: Number,
description: '创建时间',
default: ''
})
created_at: Date | string
@ApiProperty({
type: Date,
description: '更新时间',
default: ''
})
updated_at: Date | string
@ApiProperty({
type: Array,
description: '需要上传的用户字段',
default: []
})
user_fields: []
}
\ No newline at end of file
import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone,IsOptional } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger'
export class AddDeviceDto {
@ApiProperty({
type: String,
description: '设备SN',
default: ''
})
@MaxLength(20, { message: '设备SN不能超过20个字符' })
@IsNotEmpty({ message: '设备SN不能为空' })
sn: string
}
/**
* model device_info {
id Int @id @default(autoincrement())
device_id Int @unique(map: "device_id") @default(0)
user String? @db.VarChar(20)
status Int? @db.TinyInt
last_log_upload_time String? @db.VarChar(30)
last_log_remove_time String? @db.VarChar(30)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
mobile String? @db.VarChar(20)
merchant_name String? @db.VarChar(50)
log_config log_config?
}
*/
export class AddDeviceInfoDto {
@ApiProperty({
type: Number,
description: '设备信息ID',
default: 0
})
id: number
@ApiProperty({
type: Number,
description: '设备ID',
default: 0
})
@IsNumber({},{ message: '设备ID必须是数字'})
@IsNotEmpty({ message: '设备ID不能为空' })
device_id: number
@ApiProperty({
type: String,
description: '设备用户',
default: ''
})
user: string
@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({
type: Number,
description: '创建时间',
default: ''
})
created_at: Date | string
@ApiProperty({
type: Date,
description: '更新时间',
default: ''
})
updated_at: Date | string
@IsMobilePhone('zh-CN',{},{ message: '手机号格式不正确'})
@IsOptional()
@ApiProperty({
type: String,
description: '使用者手机号',
default: ''
})
mobile: string
@ApiProperty({
type: String,
description: '使用者商户名称',
default: ''
})
merchant_name: string
@ApiProperty({
type: Object,
description: '日志配置',
default: {}
})
log_config: {}
}
import { Controller, Post, Body, UseInterceptors, Get, UsePipes, Param, Query } from '@nestjs/common'
import { ConfigService } from './config.service'
import { TransformInterceptor } from '../../common/interceptors'
import { LogConfigDto } from '../../dto/config.dto'
import { PagesPipe, ValidationPipe } from '../../common/pipes'
@Controller('config')
@UseInterceptors(TransformInterceptor)
@UsePipes(new ValidationPipe()) // 使用管道验证
export class ConfigController {
constructor(private readonly configService: ConfigService) {}
@Get()
@UsePipes(new PagesPipe())
async findAll(@Query() params: ConfigTypes.LogConfigQuery): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> {
return this.configService.findAll(params)
}
@Post('/add')
addConfig(@Body() param: LogConfigDto): Promise<CommonTypes.IResData<boolean>> {
return this.configService.addConfig(param)
}
}
import { Module } from '@nestjs/common'
import { ConfigController } from './config.controller'
import { ConfigService } from './config.service'
import { PrismaService } from 'nestjs-prisma'
@Module({
controllers: [ConfigController],
providers: [ConfigService,PrismaService]
})
export class LogConfigModule {}
import { Injectable, Inject } from '@nestjs/common'
import { PrismaService } from 'nestjs-prisma'
import { LogConfigDto } from 'src/dto/config.dto'
@Injectable()
export class ConfigService {
constructor(
@Inject(PrismaService)
private readonly prisma: PrismaService // private connection: Connection,
) {}
async findAll({ device_id, skip, take }: ConfigTypes.LogConfigQuery): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> {
const where: any = {
device_id: +device_id
}
const result: ConfigTypes.LogConfigResult[] = await this.prisma.log_config.findMany({
skip,
take,
select: {
id: true,
device_id: true,
log_saved_days: true,
user_fields: {
select: {
log_user_field: {
select: {
name: true
}
}
}
}
},
where
})
const data: ConfigTypes.LogConfigResponse[] = result.map(item => {
return {
id: item.id,
device_id: item.device_id,
log_saved_days: item.log_saved_days,
user_fields: item.user_fields.map(item => item.log_user_field.name)
}
})
const total = await this.prisma.log_config.count({
where
})
const resBody: CommonTypes.IResData<ConfigTypes.LogConfigResponse[]> = { total, data }
return resBody
}
async addConfig(config: ConfigTypes.LogConfigAdd):Promise<CommonTypes.IResData<boolean>> {
const { user_fields, ...data } = config
let config_id: number = 0
await this.prisma.$transaction(async prisma => {
const date = new Date()
const { id } = (await prisma.log_config.findUnique({ where: { device_id: data.device_id }, select: { id: true } })) || {}
config.updated_at = date
if (id) {
config_id = id
await prisma.log_config.update({ where: { device_id: data.device_id }, data })
await prisma.log_config_userfield_relation.deleteMany({ where: { config_id: id } })
} else {
config.created_at = date
const { id } = await prisma.log_config.create({ data, select: { id: true } })
config_id = id
}
const relations: ConfigTypes.LogConfigResult[] = user_fields.map((ufid: number) => {
return {
config_id,
user_field_id: ufid,
created_at: date,
updated_at: date
}
})
await prisma.log_config_userfield_relation.createMany({ data: relations, skipDuplicates: true })
})
return { data: true }
}
}
import { Controller, Get, Post, Body, UseInterceptors, Query, UsePipes } from '@nestjs/common'
import { DeviceService } from './device.service'
import { TransformInterceptor } from '../../common/interceptors'
import { AddDeviceDto, AddDeviceInfoDto } from './dto/device.dto'
import { AddDeviceDto, AddDeviceInfoDto } from '../../dto/device.dto'
import { PagesPipe, ValidationPipe } from '../../common/pipes'
import { OnEvent } from '@nestjs/event-emitter'
import { WsConnEvents } from '../../common/enums'
@Controller('device')
@UseInterceptors(TransformInterceptor)
// @UsePipes(new ValidationPipe({transform: true}))
@UsePipes(new ValidationPipe()) // 使用管道验证
export class DeviceController {
constructor(
private readonly deviceService: DeviceService,
) {}
constructor(private readonly deviceService: DeviceService) {}
@Get()
@UsePipes(new PagesPipe())
......@@ -19,13 +18,18 @@ export class DeviceController {
return this.deviceService.findAll(params)
}
@Post('/add')
addDevice(@Body() param: AddDeviceDto){
addDevice(@Body() param: AddDeviceDto) {
// console.log(param)
return this.deviceService.addDevice(param)
}
@Post('/addInfo')
addDeviceInfo(@Body() param: AddDeviceInfoDto){
addDeviceInfo(@Body() param: AddDeviceInfoDto) {
// console.log(param)
return this.deviceService.addDeviceInfo(param)
}
@OnEvent(WsConnEvents.Connection)
@Post('/updateInfo')
updateDeviceInfo(param: AddDeviceInfoDto) {
return this.deviceService.updateDeviceInfo(param)
}
}
......@@ -2,7 +2,7 @@ import { Module } from '@nestjs/common';
import { DeviceController } from './device.controller';
import { DeviceService } from './device.service';
import { PrismaService } from 'nestjs-prisma';
// import { EventEmitter2 } from '@nestjs/event-emitter';
@Module({
imports: [],
controllers: [DeviceController],
......
......@@ -3,15 +3,17 @@ import { Inject, Injectable, HttpException, HttpStatus } from '@nestjs/common'
// import { InjectRepository } from '@nestjs/typeorm';
// import { Device as DeviceEntity } from '../entities/Device'
import { PrismaService } from 'nestjs-prisma'
import { AddDeviceInfoDto } from './dto/device.dto'
import { AddDeviceInfoDto } from '../../dto/device.dto'
import { WsConnEvents, WsStatus } from '../../common/enums'
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'
@Injectable()
export class DeviceService {
constructor(
// @InjectRepository(DeviceEntity)/
// private readonly deviceRepository: Repository<DeviceEntity>,
@Inject(PrismaService)
private readonly prisma: PrismaService // private connection: Connection,
) {}
) {
}
async findAll({ user, mobile, sn, skip, take }: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData<DeviceTypes.IDeviceInfo[]>> {
const where = {
......@@ -83,44 +85,20 @@ export class DeviceService {
}
async addDeviceInfo(deviceInfo: AddDeviceInfoDto) {
deviceInfo.created_at = new Date()
deviceInfo.updated_at = new Date()
deviceInfo.status = WsStatus.Offline
return await this.prisma.device_info.create({ data: deviceInfo })
}
// async create(user): Promise<DeviceEntity[]> {
// const { name } = user;
// const u = await getRepository(DeviceEntity).findOne({ where: { name } });
// // .createQueryBuilder('users')
// // .where('users.name = :name', { name });
// // const u = await qb.getOne();
// if (u) {
// throw new HttpException(
// {
// message: 'Input data validation failed',
// error: 'name must be unique.',
// },
// HttpStatus.BAD_REQUEST,
// );
// }
// return await this.deviceRepository.save(user);
// }
// async createMany(users: DeviceEntity[]) {
// const queryRunner = this.connection.createQueryRunner();
// await queryRunner.connect();
// await queryRunner.startTransaction();
// try {
// users.forEach(async user => {
// await queryRunner.manager.getRepository(DeviceEntity).save(user);
// });
// await queryRunner.commitTransaction();
// } catch (err) {
// // since we have errors lets rollback the changes we made
// await queryRunner.rollbackTransaction();
// } finally {
// // you need to release a queryRunner which was manually instantiated
// await queryRunner.release();
// }
// }
async updateDeviceInfo(deviceInfo: AddDeviceInfoDto) {
const {device_id,...data} = deviceInfo
data.updated_at = new Date()
return await this.prisma.device_info.update({
where: {
device_id: deviceInfo.device_id
},
data,
})
}
}
import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone,IsOptional } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger'
export class AddDeviceDto {
export class WsDto {
@ApiProperty({
type: String,
description: '设备SN',
......
......@@ -4,7 +4,7 @@ import { map } from 'rxjs/operators'
import { Server, Socket } from 'socket.io'
import { WsService } from './ws.service'
import { Logger, Module, UseInterceptors } from '@nestjs/common'
import { WsMessageType } from '../../common/enums'
import { WsMessageType, WsStatus, WsAccess } from '../../common/enums'
import { TransformInterceptor } from '../..//common/interceptors'
/**
......@@ -57,11 +57,37 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* @param client client
* @param args
*/
handleConnection(client: Socket, ...args: any[]) {
console.log('用户连接上', client.id)
handleConnection(client: Socket, ...args: any[]): WsTypes.IWsResponse<WsStatus, WsAccess> {
Logger.log('用户连接上', client.id)
const auth = client.handshake?.auth ?? client.handshake?.headers
const ValidateData: WsTypes.LoginValidate<WsAccess> = { isValidate: true, errMsg: WsAccess.IsOnline }
if (!auth) {
ValidateData.isValidate = false
ValidateData.errMsg = WsAccess.NotAllowed
}
const { token, deviceId } = auth
// 注册用户
const token = client.handshake?.auth?.token ?? client.handshake?.headers?.authorization
return this.wsService.login(client, token)
if (!token) {
ValidateData.isValidate = false
ValidateData.errMsg = WsAccess.InValidToken
}
if (!deviceId) {
ValidateData.isValidate = false
ValidateData.errMsg = WsAccess.InvalidDeviceId
}
if (!ValidateData.isValidate) {
const msg = `${ValidateData.errMsg} token->${token} deviceId->${deviceId}}`
client.emit(WsMessageType.Private, msg)
Logger.error(msg)
const resData: WsTypes.IWsResponse<WsStatus, WsAccess> = {
status: WsStatus.Offline,
message: ValidateData.errMsg,
device_id: deviceId
}
client.disconnect()
return resData
}
return this.wsService.login(client, token, deviceId)
}
/**
......@@ -84,7 +110,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
this.wsService.resetClients()
}
public send(payload:WsTypes.MessageBody):Promise<any> {
public send(payload: WsTypes.MessageBody): Promise<any> {
if (payload.event === WsMessageType.Private) {
return this.wsService.sendPrivateMessage(payload)
} else {
......
......@@ -2,8 +2,8 @@ import { Module } from '@nestjs/common';
import { WsGateway } from './ws.gateway';
import { WsService } from './ws.service';
@Module({
imports: [],
providers: [WsGateway,WsService],
exports: [WsGateway],
})
......
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'
import { HttpException, HttpStatus, Injectable, Inject } from '@nestjs/common'
import { Server, Socket } from 'socket.io'
import { Logger } from '@nestjs/common'
// import { WSResponse } from '../message/model/ws-response.model';
// import { validateToken } from '@/utils/helper';
// import { Message } from '@/entities/message.entity';
// import { User } from '@/entities/user.entity';
import { WsMessageType } from '../../common/enums'
import { WsAccess, WsConnEvents, WsMessageType, WsStatus } from '../../common/enums'
import { EventEmitter2 } from '@nestjs/event-emitter'
@Injectable()
export class WsService {
constructor() {}
constructor(
@Inject(EventEmitter2)
private eventEmitter: EventEmitter2
) {}
// ws 服务器, gateway 传进来
server: Server
// 存储连接的客户端
clientIds: Map<string, string> = new Map()
clientIds: Map<number, string> = new Map()
/**
* 登录
* @param client socket 客户端
* @param token token
* @returns
*/
async login(client: Socket, token: string): Promise<void> {
if (!token) {
Logger.error('token error: ', token)
client.send('token error')
client.disconnect() // T下线
return
}
// 认证用户
const res = client.handshake?.auth //{ employeeId: 1 + '' } //JwtInterface = validateToken(token.replace('Bearer ', ''))
if (!res) {
Logger.error('token 验证不通过')
client.send('token 验证不通过')
client.disconnect()
return
}
const employeeId: string = res?.employeeId
if (!employeeId) {
Logger.log('token error')
client.send('token error')
client.disconnect()
return
}
login(client: Socket, token: string, deviceId: number): WsTypes.IWsResponse<WsStatus, WsAccess> {
const clients: Map<string, Socket> = this.server.sockets.sockets
const clientIsOnline: Socket = clients.get(this.clientIds.get(employeeId))
const clientIsOnline: Socket = clients.get(this.clientIds.get(deviceId))
// 处理同一工号在多处登录
clientIsOnline?.emit(WsMessageType.System, `${employeeId} 已在别处上线, 此客户端下线处理`)
clientIsOnline?.emit(WsMessageType.System, `设备 ${deviceId} 已在别处上线, 此客户端下线处理`)
clientIsOnline?.disconnect()
// 保存工号
this.clientIds.set(employeeId, client.id)
Logger.log(`${employeeId} connected, onLine: ${clients.size}`)
this.server.emit(WsMessageType.System, `${employeeId} connected, onLine: ${clients.size}`)
return
this.clientIds.set(deviceId, client.id)
Logger.log(`${deviceId} connected, onLine: ${clients.size}`)
this.server.emit(WsMessageType.System, `${deviceId} connected, onLine: ${clients.size}`)
const resData: WsTypes.IWsResponse<WsStatus, WsAccess> = {
device_id: deviceId,
status: WsStatus.Online,
message: WsAccess.IsOnline
}
this.emit(resData)
return resData
}
/**
......@@ -60,13 +50,20 @@ export class WsService {
*/
async logout({ id }: Socket) {
// 移除在线 client
this.clientIds.forEach((clientId: string, employeeId: string) => {
for (let [deviceId, clientId] of this.clientIds) {
if (clientId === id) {
this.clientIds.delete(employeeId)
Logger.log(`${employeeId} disconnected, onLine: ${this.clientIds.size}`)
this.clientIds.delete(deviceId)
Logger.log(`${deviceId} disconnected, onLine: ${this.clientIds.size}`)
this.emit({ device_id: deviceId, status: WsStatus.Offline, message: WsAccess.IsOffline })
break
}
}
})
}
private emit(data: WsTypes.IWsResponse<WsStatus, WsAccess>) {
const { message, ...rest } = data
this.eventEmitter.emit(WsConnEvents.Connection, rest)
}
/**
* 重置 connectedClients
*/
......@@ -84,6 +81,7 @@ export class WsService {
const res = this.server?.emit(WsMessageType.System, payload.data)
if (!res) {
Logger.log('websocket send error', payload)
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败`, error: 'send error' }, HttpStatus.BAD_REQUEST)
}
}
......@@ -91,15 +89,16 @@ export class WsService {
* 发送私人消息(事务消息、个人消息)
* @param messagePath 发布地址
* @param response 响应数据
* @param employeeId 接收者工号
* @param deviceId 接收者设备号
*/
async sendPrivateMessage(payload: WsTypes.MessageBody) {
console.log('websocket send', payload)
if (!payload.employeeId) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: '请求参数employeeId 必传', error: 'employeeId is required' }, HttpStatus.BAD_REQUEST)
const client = this.server.sockets.sockets.get(this.clientIds.get(payload.employeeId))
if (!payload.device_id) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: '请求参数employeeId 必传', error: 'deviceId is required' }, HttpStatus.BAD_REQUEST)
const client = this.server.sockets.sockets.get(this.clientIds.get(payload.device_id))
const res = client?.emit(WsMessageType.Private, payload.data)
if (!res) {
Logger.log('websocket send error', payload)
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败,客户端:${payload.device_id}不在线`, error: 'send error' }, HttpStatus.BAD_REQUEST)
}
}
}
......@@ -98,6 +98,8 @@
* @returns 返回给前端的响应体
*/
type TBodyResponse = (result: IResData, msg?: 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>>
}
/*
model log_config {
id Int @id @default(autoincrement())
device_id Int @unique(map: "device_id") @default(0)
log_saved_days Int? @default(7) @db.TinyInt
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device")
device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device_info")
user_fields log_config_userfield_relation[]
}*/
declare module ConfigTypes {
interface ILogConfig {
id: number
device_id: number
log_saved_days: number
created_at: Date | string
updated_at: Date | string
user_fields: DeviceTypes.ILogUserFields[]
}
type LogConfigQuery = Pick<Partial<ILogConfig>,'device_id'> & CommonTypes.IQueryBase
type LogConfigAdd = Omit<Partial<ILogConfig>,'id'|'user_fields'> & {user_fields: number[]}
type LogConfigResult = Partial<ILogConfig>
type LogConfigResponse = Omit<LogConfigResult,'user_fields'> & {user_fields: string[]}
type LogConfigUpdate = CommonTypes.Optional<ILogConfig,'device_id'>
}
......@@ -64,11 +64,12 @@ declare module DeviceTypes {
id?: number
last_log_upload_time?: string
last_log_remove_time?: string
device_id?: number
device_id: number
created_at?: number
updated_at?: number
}
type UpdateDeviceInfo = CommonTypes.Optional<IDeviceInfoInput,"device_id">
/**
* 表示设备结果的接口
*/
......@@ -125,7 +126,7 @@ declare module DeviceTypes {
/**
* 与设备关联的日志配置信息
*/
log_config: ILogConfig
log_config: Partial<ConfigTypes.ILogConfig>
}
/**
......
......@@ -9,12 +9,21 @@ declare module WsTypes {
type MessageBody<T = WsMsgType> = {
event: T
data: any
} & (T extends 'private' ? PrivateData : Partial<PrivateData>)
} & (T extends 'private' ? IPrivateData : Partial<IPrivateData>)
interface PrivateData {
interface IPrivateData {
/**
* 接收者工号
* 接收设备号
*/
employeeId: string
device_id: number
}
interface IWsResponse<T, U> extends IPrivateData {
/**
* 状态码
*/
status: T
message: U
}
type LoginValidate<T> = { isValidate: boolean; errMsg: T }
}
......@@ -52,12 +52,12 @@
// }
const socket = io('http://192.168.1.129:8080',{
auth: { token:'12`13`23',employeeId:Math.random()+'' },
const socket = io('http://192.168.1.129:8080', {
auth: { token: '123456', deviceId: 12 },
});
socket.on('connect', function (a) {
socket.on('connect', function () {
console.log('Connected');
console.log(socket,a)
console.log(socket)
//socket.emit('private', { test: 'test' });
// socket.emit('system', 0, response =>
// console.log('Identity:', response),
......@@ -66,7 +66,7 @@
socket.on('private', function (data) {
console.log('event', data);
});
socket.on('system',function (data) {
socket.on('system', function (data) {
console.log('消息', data);
});
socket.on('disconnect', function () {
......
# http://localhost:3000/device?pageIndex=1&pageSize=1&user=李四
# http://localhost:3000/device?pageIndex=2&pageSize=5
# POST http://localhost:3000/device/add HTTP/1.1
# content-type: application/json
......@@ -11,21 +11,33 @@
# content-type: application/json
# {
# "device_id":1,
# "mobile":"3800138000"
# "device_id":13,
# "mobile":"13800138000",
# "user":"王老七",
# "merchant_name":"老点"
# }
# http://localhost:3000/sse/event
POST http://localhost:3000/broadcast/message HTTP/1.1
content-type: application/json
# POST http://localhost:3000/broadcast/message HTTP/1.1
# content-type: application/json
# {
# "event":"private",
# "device_id":1,
# "data":{
# "message":"hello limin"
# }
# }
# http://localhost:3000/config?device_id=2
POST http://localhost:3000/config/add HTTP/1.1
content-type: application/json
{
"event":"private",
"employeeId":"0.35481605237824265",
"data":{
"message":"hello limin"
}
}
\ No newline at end of file
{
"device_id":1,
"log_saved_days":8,
"user_fields":[1,2,3,4]
}
......@@ -701,6 +701,13 @@
path-to-regexp "3.2.0"
tslib "2.6.3"
"@nestjs/event-emitter@^2.0.4":
version "2.0.4"
resolved "https://registry.npmmirror.com/@nestjs/event-emitter/-/event-emitter-2.0.4.tgz#de7d3986cfeb82639bb95181fab4fe5525437c74"
integrity sha512-quMiw8yOwoSul0pp3mOonGz8EyXWHSBTqBy8B0TbYYgpnG1Ix2wGUnuTksLWaaBiiOTDhciaZ41Y5fJZsSJE1Q==
dependencies:
eventemitter2 "6.4.9"
"@nestjs/jwt@^10.2.0":
version "10.2.0"
resolved "https://registry.npmmirror.com/@nestjs/jwt/-/jwt-10.2.0.tgz#6aa35a04922d19c6426efced4671620f92e6dbd0"
......@@ -4060,6 +4067,11 @@ etag@~1.8.1:
resolved "https://registry.npmmirror.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887"
integrity sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==
eventemitter2@6.4.9:
version "6.4.9"
resolved "https://registry.npmmirror.com/eventemitter2/-/eventemitter2-6.4.9.tgz#41f2750781b4230ed58827bc119d293471ecb125"
integrity sha512-JEPTiaOt9f04oa6NOkc4aH+nVp5I3wEjpHbIPqfgCdD5v5bUzy7xQqwcVO2aDQgOWhI28da57HksMrzK9HlRxg==
events@^3.2.0:
version "3.3.0"
resolved "https://registry.npmmirror.com/events/download/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400"
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!