Commit 94c758af by yixinjj

完善一些功能

1 parent 5dc523d9
...@@ -34,6 +34,7 @@ ...@@ -34,6 +34,7 @@
"dependencies": { "dependencies": {
"@nest-modules/mailer": "^1.3.22", "@nest-modules/mailer": "^1.3.22",
"@nestjs-modules/mailer": "^1.6.0", "@nestjs-modules/mailer": "^1.6.0",
"@nestjs/axios": "^3.0.3",
"@nestjs/bull": "^0.1.1", "@nestjs/bull": "^0.1.1",
"@nestjs/common": "^10.4.1", "@nestjs/common": "^10.4.1",
"@nestjs/core": "^10.4.1", "@nestjs/core": "^10.4.1",
...@@ -49,6 +50,7 @@ ...@@ -49,6 +50,7 @@
"@nestjs/websockets": "^10.4.1", "@nestjs/websockets": "^10.4.1",
"@prisma/client": "^5.19.1", "@prisma/client": "^5.19.1",
"@socket.io/redis-adapter": "^8.3.0", "@socket.io/redis-adapter": "^8.3.0",
"axios": "^1.7.7",
"bull": "^3.14.0", "bull": "^3.14.0",
"class-transformer": "^0.3.1", "class-transformer": "^0.3.1",
"class-validator": "^0.12.2", "class-validator": "^0.12.2",
......
...@@ -48,7 +48,8 @@ export enum WsAccess { ...@@ -48,7 +48,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' OnOfflineAll='device.offline.all',
OnMessage='client.mesage.received'
} }
export enum FileUploadEvents { export enum FileUploadEvents {
OnLogFileUploaded = 'log.file.uploaded' OnLogFileUploaded = 'log.file.uploaded'
......
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, isString, IsString, Matches, ValidateIf, ValidateNested } from 'class-validator'
import { Type } from 'class-transformer' import { Transform, Type } from 'class-transformer'
class DataDto { class DataDto {
@ApiProperty({ @ApiProperty({
...@@ -30,7 +30,10 @@ export class BroadcastDto { ...@@ -30,7 +30,10 @@ export class BroadcastDto {
@ValidateIf(o => o.event === WsMessageType.Private) @ValidateIf(o => o.event === WsMessageType.Private)
@IsDefined({ message: '发送私有消息时,device_id是必填的' }) @IsDefined({ message: '发送私有消息时,device_id是必填的' })
@IsNumber({}, { message: 'device_id必须是数字' }) @Transform(({ value }) => (isString(value) && !isNaN(Number(value)) ? value : undefined), {
toClassOnly: true,
})
@Matches(/[0-9]+$/, { message: '设备ID必须是数字' })
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '设备号,私发信息必填', description: '设备号,私发信息必填',
......
import { ApiProperty } from "@nestjs/swagger" import { ApiProperty } from "@nestjs/swagger"
import { IsNotEmpty, IsNumber } from "class-validator" import { Transform } from "class-transformer"
import { IsNotEmpty, IsNumber, isString, Matches } from "class-validator"
/* /*
model log_config { model log_config {
...@@ -16,21 +17,27 @@ export class LogConfigDto { ...@@ -16,21 +17,27 @@ export class LogConfigDto {
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '设备信息ID', description: '设备信息ID',
required: false,
default: 0 default: 0
}) })
id: number id: number
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '设备ID', description: '设备ID',
required: true,
default: 0 default: 0
}) })
@IsNumber({},{ message: '设备ID必须是数字'}) @Transform(({ value }) => (isString(value) && !isNaN(Number(value)) ? value : undefined), {
toClassOnly: true,
})
@Matches(/[0-9]+$/, { message: '设备ID必须是数字' })
@IsNotEmpty({ message: '设备ID不能为空' }) @IsNotEmpty({ message: '设备ID不能为空' })
device_id: number device_id: number
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '日志保存天数', description: '日志保存天数',
required: false,
default: '' default: ''
}) })
log_saved_days: number log_saved_days: number
...@@ -39,6 +46,7 @@ export class LogConfigDto { ...@@ -39,6 +46,7 @@ export class LogConfigDto {
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '创建时间', description: '创建时间',
required: false,
default: '' default: ''
}) })
created_at: Date | string created_at: Date | string
...@@ -46,6 +54,7 @@ export class LogConfigDto { ...@@ -46,6 +54,7 @@ export class LogConfigDto {
@ApiProperty({ @ApiProperty({
type: Date, type: Date,
description: '更新时间', description: '更新时间',
required: false,
default: '' default: ''
}) })
updated_at: Date | string updated_at: Date | string
...@@ -54,8 +63,8 @@ export class LogConfigDto { ...@@ -54,8 +63,8 @@ export class LogConfigDto {
@ApiProperty({ @ApiProperty({
type: Array, type: Array,
description: '需要上传的用户字段', description: '需要上传的用户字段',
required: false,
default: [] default: []
}) })
user_fields: [] user_fields: []
} }
\ No newline at end of file \ No newline at end of file
import { Controller, Post, Body, UseInterceptors, UsePipes } 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 { WsGateway } from '../ws/ws.gateway'
import { BroadcastDto } from '../../dto' import { BroadcastDto } from '../../dto'
import { ValidationPipe } from '../../common/pipes' import { ValidationPipe } from '../../common/pipes'
import { ApiTags } from '@nestjs/swagger' import { ApiTags } from '@nestjs/swagger'
import { OnEvent } from '@nestjs/event-emitter'
import { WsConnEvents } from '../../common/enums'
@ApiTags('broadcast') @ApiTags('broadcast')
@Controller('broadcast') @Controller('broadcast')
@UseInterceptors(TransformInterceptor) @UseInterceptors(TransformInterceptor)
...@@ -13,7 +15,9 @@ export class BroadcastController { ...@@ -13,7 +15,9 @@ export class BroadcastController {
/** /**
* @param wsGateway - WsGateway实例 * @param wsGateway - WsGateway实例
*/ */
constructor(private readonly wsGateway: WsGateway) {} constructor(private readonly wsGateway: WsGateway,
private readonly broadcastService: BroadcastService
) {}
/** /**
* 发送广播消息 * 发送广播消息
...@@ -24,4 +28,9 @@ export class BroadcastController { ...@@ -24,4 +28,9 @@ export class BroadcastController {
async message(@Body() params: BroadcastDto): Promise<CommonTypes.IResData> { async message(@Body() params: BroadcastDto): Promise<CommonTypes.IResData> {
return this.wsGateway.send(params) return this.wsGateway.send(params)
} }
@OnEvent(WsConnEvents.OnMessage)
onMessage(@Body() params: any){
Logger.debug('收到私有订阅消息:', params)
this.broadcastService.onMessage(params)
}
} }
...@@ -3,8 +3,9 @@ import { BroadcastController } from './broadcast.controller' ...@@ -3,8 +3,9 @@ import { BroadcastController } from './broadcast.controller'
import { BroadcastService } from './broadcast.service' import { BroadcastService } from './broadcast.service'
import { WsModule } from '../ws/ws.module'; import { WsModule } from '../ws/ws.module';
import { WsService } from '../ws/ws.service'; import { WsService } from '../ws/ws.service';
import { HttpModule } from '@nestjs/axios';
@Module({ @Module({
imports: [WsModule], imports: [WsModule,HttpModule],
controllers: [BroadcastController], controllers: [BroadcastController],
providers: [BroadcastService,WsService] providers: [BroadcastService,WsService]
}) })
......
import { HttpService } from '@nestjs/axios'
import { Injectable, HttpException, HttpStatus } from '@nestjs/common' import { Injectable, HttpException, HttpStatus } from '@nestjs/common'
import { AxiosResponse } from 'axios'
import { Observable } from 'rxjs'
@Injectable() @Injectable()
export class BroadcastService { export class BroadcastService {
// constructor(private readonly wsGateway: WsGateway) { } constructor(private readonly httpService: HttpService) {}
// // 广播消息 // // 广播消息
// message(param:WsTypes.SendBody<WsTypes.MessageType>) { onMessage(param: any) :Observable<AxiosResponse<any, any>>{
// return this.wsGateway.send(param) return this.httpService.post('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=2f2ba84b-1b7f-4556-8508-e6c605e2671c', {
// } msgtype: 'markdown',
markdown: {
content: param
}
})
}
} }
...@@ -13,7 +13,7 @@ export class ConfigController { ...@@ -13,7 +13,7 @@ export class ConfigController {
@Get() @Get()
@UsePipes(new PagesPipe()) @UsePipes(new PagesPipe())
async findAll(@Query() params: ConfigTypes.LogConfigQuery): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> { async findAll(@Query() params: LogConfigDto): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> {
return this.configService.findAll(params) return this.configService.findAll(params)
} }
@Post('/add') @Post('/add')
......
...@@ -38,9 +38,10 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws ...@@ -38,9 +38,10 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* @param data - 传入的数据 * @param data - 传入的数据
* @returns 包含事件和数据的 Observable 对象 * @returns 包含事件和数据的 Observable 对象
*/ */
// @SubscribeMessage(WsMessageType.Private)'' @SubscribeMessage(WsMessageType.Private)
subPrivate(@MessageBody() data: any): Observable<WsResponse<string>> { subPrivate(@MessageBody() data: any): Observable<WsResponse<string>> {
return from<string>('hello').pipe(map(item => ({ event: 'events', data: item }))) this.wsService.onMessage(data)
return from<string>('ok').pipe(map(item => ({ event: WsMessageType.Private, data: item })))
} }
/** /**
......
...@@ -119,7 +119,6 @@ export class WsService { ...@@ -119,7 +119,6 @@ export class WsService {
* @param deviceId 接收者设备号 * @param deviceId 接收者设备号
*/ */
async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResData> { async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>): Promise<CommonTypes.IResData> {
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)
...@@ -130,4 +129,7 @@ export class WsService { ...@@ -130,4 +129,7 @@ export class WsService {
Logger.log('发送私有消息成功->', payload) Logger.log('发送私有消息成功->', payload)
return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' } return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' }
} }
onMessage(message:any){
this.emit(WsConnEvents.OnMessage,message)
}
} }
...@@ -31,23 +31,23 @@ ...@@ -31,23 +31,23 @@
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":1, # "device_id":1,
"data":{ # "data":{
"command":"getStorage", # "command":"getStorage",
"payload":{ # "payload":{
"message":"log message" # "key":"userInfo"
} # }
} # }
} # }
# 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
......
...@@ -741,6 +741,11 @@ ...@@ -741,6 +741,11 @@
handlebars "^4.7.8" handlebars "^4.7.8"
pug "^3.0.2" pug "^3.0.2"
"@nestjs/axios@^3.0.3":
version "3.0.3"
resolved "https://registry.npmmirror.com/@nestjs/axios/-/axios-3.0.3.tgz#a663cb13cff07ea6b9a7107263de2ae472d41118"
integrity sha512-h6TCn3yJwD6OKqqqfmtRS5Zo4E46Ip2n+gK1sqwzNBC+qxQ9xpCu+ODVRFur6V3alHSCSBxb3nNtt73VEdluyA==
"@nestjs/bull@^0.1.1": "@nestjs/bull@^0.1.1":
version "0.1.2" version "0.1.2"
resolved "https://registry.npmmirror.com/@nestjs/bull/-/bull-0.1.2.tgz#26422a7d97020ba5132f6efc6731b8631480c5e0" resolved "https://registry.npmmirror.com/@nestjs/bull/-/bull-0.1.2.tgz#26422a7d97020ba5132f6efc6731b8631480c5e0"
...@@ -2300,6 +2305,15 @@ axios@^0.19.2: ...@@ -2300,6 +2305,15 @@ axios@^0.19.2:
dependencies: dependencies:
follow-redirects "1.5.10" follow-redirects "1.5.10"
axios@^1.7.7:
version "1.7.7"
resolved "https://registry.npmmirror.com/axios/-/axios-1.7.7.tgz#2f554296f9892a72ac8d8e4c5b79c14a91d0a47f"
integrity sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==
dependencies:
follow-redirects "^1.15.6"
form-data "^4.0.0"
proxy-from-env "^1.1.0"
babel-jest@^25.5.1: babel-jest@^25.5.1:
version "25.5.1" version "25.5.1"
resolved "https://registry.npmmirror.com/babel-jest/-/babel-jest-25.5.1.tgz#bc2e6101f849d6f6aec09720ffc7bc5332e62853" resolved "https://registry.npmmirror.com/babel-jest/-/babel-jest-25.5.1.tgz#bc2e6101f849d6f6aec09720ffc7bc5332e62853"
...@@ -4748,6 +4762,11 @@ follow-redirects@1.5.10: ...@@ -4748,6 +4762,11 @@ follow-redirects@1.5.10:
dependencies: dependencies:
debug "=3.1.0" debug "=3.1.0"
follow-redirects@^1.15.6:
version "1.15.9"
resolved "https://registry.npmmirror.com/follow-redirects/-/follow-redirects-1.15.9.tgz#a604fa10e443bf98ca94228d9eebcc2e8a2c8ee1"
integrity sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==
for-each@^0.3.3: for-each@^0.3.3:
version "0.3.3" version "0.3.3"
resolved "https://registry.npmmirror.com/for-each/-/for-each-0.3.3.tgz#69b447e88a0a5d32c3e7084f3f1710034b21376e" resolved "https://registry.npmmirror.com/for-each/-/for-each-0.3.3.tgz#69b447e88a0a5d32c3e7084f3f1710034b21376e"
...@@ -8691,7 +8710,7 @@ proxy-agent@^4.0.0: ...@@ -8691,7 +8710,7 @@ proxy-agent@^4.0.0:
proxy-from-env "^1.0.0" proxy-from-env "^1.0.0"
socks-proxy-agent "^5.0.0" socks-proxy-agent "^5.0.0"
proxy-from-env@^1.0.0: proxy-from-env@^1.0.0, proxy-from-env@^1.1.0:
version "1.1.0" version "1.1.0"
resolved "https://registry.npmmirror.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2" resolved "https://registry.npmmirror.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2"
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg== integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!