Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
node
/
app-admin
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 210a462f
authored
Sep 30, 2024
by
yixinjj
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
修改日常任务的BUG
1 parent
6806a535
Hide whitespace changes
Inline
Side-by-side
Showing
14 changed files
with
107 additions
and
110 deletions
src/common/enums/index.ts
src/common/exceptions/ws-access.exception.ts
src/modules/broadcast/broadcast.controller.ts
src/modules/broadcast/broadcast.module.ts
src/modules/broadcast/broadcast.service.ts
src/modules/device/device.controller.ts
src/modules/device/device.module.ts
src/modules/device/device.service.ts
src/modules/ws/ws.gateway.ts
src/modules/ws/ws.module.ts
src/modules/ws/ws.service.ts
src/tasks/tasks.service.ts
src/typings/device.d.ts
test.http
src/common/enums/index.ts
View file @
210a462
...
...
@@ -43,7 +43,7 @@ export enum WsAccess {
IsOnline
=
'通过验证,设备上线'
,
IsOffline
=
'设备下线'
,
ConnFailure
=
'设备连接失败,请检查设备号是否正确'
,
TokenExpired
=
'token已过期,请重新登录'
TokenExpired
=
'token已过期,请重新登录'
}
export
enum
WsAccessCode
{
NotAllowed
=
901
,
...
...
@@ -62,9 +62,9 @@ export enum Events {
OnMessage
=
'client.mesage.received'
,
OnLogFileUploaded
=
'log.file.uploaded'
,
OnLogFileRemoved
=
'log.file.removed'
,
On
TaskStart
=
'task
.start'
,
On
DailyTaskStart
=
'task.daily
.start'
,
OnSendMessage
=
'client.message.send'
,
OnMessageToSendClient
=
'message.send.to.client'
}
export
enum
DocTypes
{
Log
=
'log'
,
...
...
src/common/exceptions/ws-access.exception.ts
0 → 100644
View file @
210a462
import
{
WsAccess
,
WsAccessCode
}
from
'../enums'
export
class
WsAccessException
extends
Error
{
constructor
(
public
errMsg
:
WsAccess
,
public
errorCode
:
WsAccessCode
)
{
super
(
errMsg
)
}
}
src/modules/broadcast/broadcast.controller.ts
View file @
210a462
import
{
Controller
,
Post
,
Body
,
UseInterceptors
,
UsePipes
,
Logger
}
from
'@nestjs/common'
import
{
BroadcastService
}
from
'./broadcast.service'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
WsGateway
}
from
'../ws/ws.gateway'
import
{
BroadcastDto
}
from
'../../dto'
import
{
ParseDeviceIdPipe
,
ValidationPipe
}
from
'../../common/pipes'
import
{
ApiOperation
,
ApiTags
}
from
'@nestjs/swagger'
...
...
@@ -14,10 +13,9 @@ import { Events } from '../../common/enums'
@
UsePipes
(
new
ValidationPipe
())
// 使用管道验证
export
class
BroadcastController
{
/**
*
@param wsGateway - WsGateway实例
*
*/
constructor
(
private
readonly
wsGateway
:
WsGateway
,
private
readonly
broadcastService
:
BroadcastService
)
{}
...
...
@@ -30,7 +28,7 @@ export class BroadcastController {
@
ApiOperation
({
summary
:
'给设备发送指令'
})
@
UsePipes
(
new
ParseDeviceIdPipe
())
async
message
(@
Body
()
params
:
BroadcastDto
):
Promise
<
CommonTypes
.
IResData
>
{
return
this
.
wsGateway
.
send
(
params
)
return
this
.
broadcastService
.
send
(
params
)
}
@
OnEvent
(
Events
.
OnMessage
)
onMessage
(@
Body
()
params
:
any
):
Promise
<
CommonTypes
.
IResData
>
{
...
...
src/modules/broadcast/broadcast.module.ts
View file @
210a462
import
{
Module
}
from
'@nestjs/common'
import
{
BroadcastController
}
from
'./broadcast.controller'
import
{
BroadcastService
}
from
'./broadcast.service'
import
{
WsModule
}
from
'../ws/ws.module'
;
import
{
HttpModule
}
from
'@nestjs/axios'
;
@
Module
({
imports
:
[
WsModule
,
HttpModule
],
imports
:
[
HttpModule
],
controllers
:
[
BroadcastController
],
providers
:
[
BroadcastService
]
})
...
...
src/modules/broadcast/broadcast.service.ts
View file @
210a462
...
...
@@ -2,7 +2,7 @@ import { HttpService } from '@nestjs/axios'
import
{
Inject
,
Injectable
}
from
'@nestjs/common'
import
{
AxiosResponse
}
from
'axios'
import
{
ConfigService
}
from
'nestjs-config'
import
{
Command
,
Events
,
RESPONSE_CODE
}
from
'../../common/enums'
import
{
Command
,
Events
,
RESPONSE_CODE
,
WsMessageType
}
from
'../../common/enums'
import
{
EventEmitter2
}
from
'@nestjs/event-emitter'
@
Injectable
()
export
class
BroadcastService
{
...
...
@@ -15,6 +15,11 @@ export class BroadcastService {
)
{
this
.
webHook
=
this
.
config
.
get
(
'env'
).
AppWebhook
}
async
send
(
message
:
WsTypes
.
MessageBody
<
Command
,
WsMessageType
>
):
Promise
<
CommonTypes
.
IResData
>
{
const
success
=
this
.
eventEmitter
.
emit
(
Events
.
OnMessageToSendClient
,
message
)
return
{
code
:
success
?
RESPONSE_CODE
.
SUCCESS
:
RESPONSE_CODE
.
NOSUCCESS
,
data
:
{
success
}
}
}
// // 广播消息
async
onMessage
(
param
:
any
):
Promise
<
CommonTypes
.
IResData
>
{
if
(
param
?.
code
==
RESPONSE_CODE
.
SUCCESS
&&
param
?.
data
?.
command
===
Command
.
RemoveLog
)
{
...
...
src/modules/device/device.controller.ts
View file @
210a462
import
{
Controller
,
Get
,
Post
,
Body
,
UseInterceptors
,
Query
,
UsePipes
,
Inject
}
from
'@nestjs/common'
import
{
DeviceService
}
from
'./device.service'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
AddDeviceInfoDto
,
DeviceFindOneDto
,
DeviceQueryDto
,
DeviceStatusDto
,
UpdateDeviceInfoDto
}
from
'../../dto'
import
{
AddDeviceInfoDto
,
DeviceFindOneDto
,
DeviceQueryDto
,
DeviceStatusDto
,
UpdateDeviceInfoDto
}
from
'../../dto'
import
{
PagesPipe
,
ValidationPipe
}
from
'../../common/pipes'
import
{
OnEvent
,
EventEmitter2
}
from
'@nestjs/event-emitter'
import
{
WsAccess
,
Events
,
WsMessageType
,
Command
,
RESPONSE_CODE
}
from
'../../common/enums'
...
...
@@ -50,7 +50,6 @@ export class DeviceController {
@
Post
(
'/add'
)
@
ApiOperation
({
summary
:
'添加设备'
})
async
addDevice
(@
Body
()
param
:
AddDeviceInfoDto
):
Promise
<
CommonTypes
.
IResponseBase
>
{
// console.log(param)
return
await
this
.
deviceService
.
addDevice
(
param
)
}
/**
...
...
@@ -62,10 +61,9 @@ export class DeviceController {
@
Post
(
'/addInfo'
)
@
ApiOperation
({
summary
:
'添加设备信息'
})
async
addDeviceInfo
(@
Body
()
param
:
UpdateDeviceInfoDto
):
Promise
<
CommonTypes
.
IResData
>
{
// console.log(param)
return
await
this
.
deviceService
.
addDeviceInfo
(
param
)
}
/**
* 更新设备信息的方法
* 该方法接收一个包含设备信息的DTO对象,并返回更新后的设备信息
...
...
@@ -84,8 +82,8 @@ export class DeviceController {
* @param param - 包含设备状态的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
@
OnEvent
(
Events
.
OnConnected
)
@
Post
(
'/upsertStatus'
)
@
OnEvent
(
Events
.
OnConnected
)
@
ApiOperation
({
summary
:
'更新设备状态'
})
async
upsertDeviceStatus
(@
Body
()
param
:
DeviceStatusDto
):
Promise
<
void
|
CommonTypes
.
IResData
>
{
return
await
this
.
deviceService
.
upsertDeviceStatus
(
param
).
catch
(
error
=>
{
...
...
@@ -93,8 +91,8 @@ export class DeviceController {
this
.
eventEmitter
.
emit
(
Events
.
OnConnectError
,
out
)
})
}
@
OnEvent
(
Events
.
OnLogFileRemoved
)
@
Post
(
'/upsertFileRemovedTime'
)
@
OnEvent
(
Events
.
OnLogFileRemoved
)
@
ApiOperation
({
summary
:
'更新设备状态'
})
async
upsertFileRemovedTime
(@
Body
()
param
:
DeviceStatusDto
):
Promise
<
void
|
CommonTypes
.
IResData
>
{
return
await
this
.
deviceService
.
upsertFileRemovedTime
(
param
)
...
...
@@ -114,8 +112,8 @@ export class DeviceController {
}
@
Get
(
'/task'
)
@
OnEvent
(
Events
.
OnTaskStart
)
@
ApiOperation
({
summary
:
'日任务'
})
@
OnEvent
(
Events
.
On
Daily
TaskStart
)
@
ApiOperation
({
summary
:
'
每
日任务'
})
async
task
():
Promise
<
void
|
CommonTypes
.
IResData
>
{
return
await
this
.
deviceService
.
removeFilesTask
()
}
...
...
@@ -124,11 +122,4 @@ export class DeviceController {
async
addAll
(
devices
:
Array
<
any
>
):
Promise
<
void
|
CommonTypes
.
IResData
>
{
// return this.deviceService.addAll(devices)
}
@
Get
(
'/upsertFields'
)
@
ApiOperation
({
summary
:
'添加设备关联的日志字段'
})
upsertFields
()
{
}
}
src/modules/device/device.module.ts
View file @
210a462
...
...
@@ -2,13 +2,10 @@ import { Module } from '@nestjs/common';
import
{
DeviceController
}
from
'./device.controller'
;
import
{
DeviceService
}
from
'./device.service'
;
import
{
PrismaModule
}
from
'nestjs-prisma'
;
import
{
WsModule
}
from
'../ws/ws.module'
;
import
{
WsService
}
from
'../ws/ws.service'
;
// import { EventEmitter2 } from '@nestjs/event-emitter';
@
Module
({
imports
:
[
PrismaModule
],
controllers
:
[
DeviceController
],
providers
:
[
DeviceService
,
WsService
],
providers
:
[
DeviceService
],
exports
:
[
DeviceService
],
})
export
class
DeviceModule
{}
src/modules/device/device.service.ts
View file @
210a462
...
...
@@ -3,8 +3,7 @@ import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } f
// import { InjectRepository } from '@nestjs/typeorm';
// import { Device as DeviceEntity } from '../entities/Device'
import
{
PrismaService
}
from
'nestjs-prisma'
import
{
Command
,
RESPONSE_CODE
,
WsMessageType
,
WsStatus
}
from
'../../common/enums'
import
{
WsService
}
from
'../ws/ws.service'
import
{
Command
,
Events
,
RESPONSE_CODE
,
WsMessageType
,
WsStatus
}
from
'../../common/enums'
import
{
EventEmitter2
}
from
'@nestjs/event-emitter'
@
Injectable
()
...
...
@@ -13,7 +12,7 @@ export class DeviceService implements OnModuleInit {
@
Inject
(
PrismaService
)
private
readonly
prisma
:
PrismaService
,
// private connection: Connection,
@
Inject
(
EventEmitter2
)
private
readonly
wsService
:
WsService
private
readonly
eventEmitter
:
EventEmitter2
)
{}
async
onModuleInit
()
{
this
.
resetAllDeviceStatus
()
...
...
@@ -119,7 +118,7 @@ export class DeviceService implements OnModuleInit {
data
:
user_fields
.
map
((
item
:
number
)
=>
({
device_id
,
field_id
:
item
}))
})
}
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
:
now
}
})
// await this.addDeviceInfo(Object.assign({ device_id: id },deviceInfo))
})
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'添加设备成功'
}
...
...
@@ -128,8 +127,6 @@ export class DeviceService implements OnModuleInit {
async
addDeviceInfo
(
deviceInfo
:
DeviceTypes
.
IDeviceSaves
):
Promise
<
CommonTypes
.
IResData
>
{
const
now
=
new
Date
()
const
{
device_id
,
...
data
}
=
deviceInfo
console
.
log
(
'device_id'
,
device_id
)
const
{
device_info
,
log_config
,
user_fields
,
sn
}
=
data
await
this
.
prisma
.
$transaction
(
async
prisma
=>
{
if
(
sn
)
{
...
...
@@ -147,7 +144,7 @@ export class DeviceService implements OnModuleInit {
data
:
user_fields
.
map
((
item
:
number
)
=>
({
device_id
,
field_id
:
item
}))
})
}
await
prisma
.
device_status
.
create
({
data
:
{
device_id
,
status
:
WsStatus
.
Offline
}
})
await
prisma
.
device_status
.
create
({
data
:
{
device_id
,
status
:
WsStatus
.
Offline
,
last_log_remove_time
:
now
}
})
})
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'添加设备信息成功'
}
}
...
...
@@ -184,10 +181,11 @@ export class DeviceService implements OnModuleInit {
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'设备信息更新成功'
}
}
async
upsertDeviceStatus
(
data
:
DeviceStatus
.
IDeviceStatus
):
Promise
<
CommonTypes
.
IResData
>
{
const
now
=
new
Date
()
await
this
.
prisma
.
device_status
.
upsert
({
where
:
{
device_id
:
data
.
device_id
},
create
:
{
device_id
:
data
.
device_id
,
status
:
WsStatus
.
Offline
},
update
:
{
status
:
data
.
status
,
last_login_time
:
data
.
status
===
WsStatus
.
Online
?
n
ew
Date
()
:
undefined
,
last_offline_time
:
data
.
status
===
WsStatus
.
Offline
?
new
Date
()
:
undefined
,
last_log_remove_time
:
data
.
last_log_remove_time
,
last_log_upload_time
:
data
.
last_log_upload_time
}
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
?
n
ow
:
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
}
})
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'设备状态更新成功'
}
}
...
...
@@ -213,7 +211,7 @@ export class DeviceService implements OnModuleInit {
await
this
.
prisma
.
$transaction
(
async
prisma
=>
{
const
{
id
}
=
await
prisma
.
device
.
create
({
data
:
{
sn
:
el
.
设备编号
},
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_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
()
}
})
await
prisma
.
log_config
.
create
({
data
:
{
device_id
:
id
,
log_saved_days
:
7
}
})
await
prisma
.
field_relation
.
createMany
({
data
:
[
...
...
@@ -228,14 +226,21 @@ export class DeviceService implements OnModuleInit {
}
async
removeFilesTask
():
Promise
<
CommonTypes
.
IResData
>
{
const
results
:
(
CommonTypes
.
IDeviceId
&
Pick
<
ConfigTypes
.
ILogConfig
,
'log_saved_days'
>
)[]
=
await
this
.
prisma
.
$queryRaw
<
(
CommonTypes
.
IDeviceId
&
Pick
<
ConfigTypes
.
ILogConfig
,
'log_saved_days'
>
)[]
>
`
SELECT d.device_id, c.log_saved_days
FROM device_info d
JOIN log_config c ON c.device_id = d.device_id
WHERE c.log_saved_days >= TIMESTAMPDIFF(DAY, d.last_log_remove_time, NOW());`
for
(
const
{
device_id
,
log_saved_days
}
of
results
)
{
const
results
:
DeviceTypes
.
TRemoveLogsResultByTask
[]
=
await
this
.
prisma
.
$queryRaw
<
DeviceTypes
.
TRemoveLogsResultByTask
[]
>
`
SELECT d.device_id, c.log_saved_days
FROM device_info d
JOIN log_config c ON c.device_id = d.device_id
JOIN device_status s ON s.device_id = d.device_id
WHERE c.log_saved_days < TIMESTAMPDIFF(DAY, s.last_log_remove_time, NOW()) AND s.status=1`
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
}
}
await
this
.
wsService
.
sendPrivateMessage
(
message
)
this
.
eventEmitter
.
emit
(
Events
.
OnMessageToSendClient
,
message
)
await
this
.
sendMessage
(
results
)
}
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'每日日志删除任务完成'
}
}
...
...
src/modules/ws/ws.gateway.ts
View file @
210a462
...
...
@@ -3,11 +3,12 @@ import { from, Observable } from 'rxjs'
import
{
map
}
from
'rxjs/operators'
import
{
Server
,
Socket
}
from
'socket.io'
import
{
WsService
}
from
'./ws.service'
import
{
Inject
,
Logger
,
Module
,
UseInterceptors
}
from
'@nestjs/common'
import
{
WsMessageType
,
WsStatus
,
WsAccess
,
Command
,
WsAccessCode
}
from
'../../common/enums'
import
{
Inject
,
Logger
,
Module
,
UseInterceptors
,
UsePipes
}
from
'@nestjs/common'
import
{
WsMessageType
,
WsStatus
,
WsAccess
,
Command
,
WsAccessCode
,
Events
}
from
'../../common/enums'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
JwtService
,
TokenExpiredError
}
from
'@nestjs/jwt'
import
{
AuthService
}
from
'../auth/auth.service'
import
{
OnEvent
}
from
'@nestjs/event-emitter'
/**
* WebSocket 网关
...
...
@@ -63,50 +64,36 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
*/
handleConnection
(
client
:
Socket
):
WsTypes
.
IWsResponse
<
WsStatus
,
WsAccess
>
{
const
auth
=
client
.
handshake
?.
auth
??
client
.
handshake
?.
headers
const
ValidateData
:
WsTypes
.
LoginValidate
<
WsAccess
>
=
{
isValidate
:
true
,
errMsg
:
WsAccess
.
IsOnline
,
errorCode
:
WsAccessCode
.
IsOnline
}
if
(
!
auth
)
{
ValidateData
.
isValidate
=
false
ValidateData
.
errMsg
=
WsAccess
.
NotAllowed
ValidateData
.
errorCode
=
WsAccessCode
.
NotAllowed
return
this
.
handleInvalidAuth
(
client
,
WsAccess
.
NotAllowed
,
WsAccessCode
.
NotAllowed
)
}
const
{
token
,
deviceId
}
=
auth
// 注册用户
if
(
!
token
)
{
ValidateData
.
isValidate
=
false
ValidateData
.
errMsg
=
WsAccess
.
InValidToken
ValidateData
.
errorCode
=
WsAccessCode
.
InValidToken
return
this
.
handleInvalidAuth
(
client
,
WsAccess
.
InValidToken
,
WsAccessCode
.
InValidToken
)
}
if
(
!
deviceId
)
{
ValidateData
.
isValidate
=
false
ValidateData
.
errMsg
=
WsAccess
.
InvalidDeviceId
ValidateData
.
errorCode
=
WsAccessCode
.
InvalidDeviceId
return
this
.
handleInvalidAuth
(
client
,
WsAccess
.
InvalidDeviceId
,
WsAccessCode
.
InvalidDeviceId
)
}
const
verify
=
this
.
authService
.
verifyToken
(
String
(
token
))
if
(
!
verify
.
isPass
)
{
ValidateData
.
isValidate
=
false
if
(
verify
.
isExpired
)
{
ValidateData
.
errMsg
=
WsAccess
.
TokenExpired
ValidateData
.
errorCode
=
WsAccessCode
.
TokenExpired
}
else
{
ValidateData
.
errMsg
=
WsAccess
.
InValidToken
ValidateData
.
errorCode
=
WsAccessCode
.
InValidToken
}
}
if
(
!
ValidateData
.
isValidate
)
{
const
msg
=
`
${
ValidateData
.
errMsg
}
token->
${
token
}
deviceId->
${
deviceId
}
}`
Logger
.
error
(
msg
)
client
.
emit
(
WsMessageType
.
Private
,
ValidateData
)
const
resData
:
WsTypes
.
IWsResponse
<
WsStatus
,
WsAccess
>
=
{
status
:
WsStatus
.
Offline
,
message
:
ValidateData
.
errMsg
,
device_id
:
deviceId
}
client
.
disconnect
()
return
resData
const
errorCode
=
verify
.
isExpired
?
WsAccessCode
.
TokenExpired
:
WsAccessCode
.
InValidToken
return
this
.
handleInvalidAuth
(
client
,
WsAccess
.
TokenExpired
,
errorCode
)
}
return
this
.
wsService
.
login
(
client
,
token
,
deviceId
)
}
private
handleInvalidAuth
(
client
:
Socket
,
errMsg
:
WsAccess
,
errorCode
:
WsAccessCode
):
WsTypes
.
IWsResponse
<
WsStatus
,
WsAccess
>
{
const
msg
=
`
${
errMsg
}
token->
${
client
.
handshake
.
auth
?.
token
}
deviceId
->
$
{
client
.
handshake
.
auth
?.
deviceId
}
`
Logger.error(msg)
client.emit(WsMessageType.Private, { isValidate: false, errMsg, errorCode })
client.disconnect()
return {
status: WsStatus.Offline,
message: errMsg,
device_id: client.handshake.auth?.deviceId
}
}
/**
* 用户断开连接
* @param client client
...
...
@@ -133,7 +120,13 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* @param payload
*/
@OnEvent(Events.OnMessageToSendClient)
public send(payload: WsTypes.MessageBody<Command, WsMessageType>): Promise<CommonTypes.IResData> {
return this.wsService[{ [WsMessageType.Private]: 'sendPrivateMessage', [WsMessageType.System]: 'sendPublicMessage' }[payload.event]](payload)
}
@OnEvent(Events.OnConnectError)
async onConnectError(out: WsTypes.WsConnError): Promise<void> {
return this.wsService.onConnectError(out)
}
}
src/modules/ws/ws.module.ts
View file @
210a462
import
{
Module
}
from
'@nestjs/common'
import
{
WsGateway
}
from
'./ws.gateway'
import
{
WsService
}
from
'./ws.service'
import
{
JwtModule
,
JwtService
}
from
'@nestjs/jwt'
import
{
AuthModule
}
from
'../auth/auth.module'
import
{
AuthService
}
from
'../auth/auth.service'
import
{
EventEmitter2
}
from
'@nestjs/event-emitter'
import
{
ConfigModule
}
from
'nestjs-config'
import
{
BroadcastModule
}
from
'../broadcast/broadcast.module'
import
{
PrismaModule
}
from
'nestjs-prisma'
import
{
FileModule
}
from
'../file/file.module'
// import { DeviceService } from '../device/device.service'
@
Module
({
imports
:
[
AuthModule
],
providers
:
[
WsGateway
,
WsService
],
exports
:
[
WsGateway
]
providers
:
[
WsGateway
,
WsService
]
})
export
class
WsModule
{}
src/modules/ws/ws.service.ts
View file @
210a462
import
{
HttpException
,
HttpStatus
,
Injectable
,
Inject
}
from
'@nestjs/common'
import
{
HttpException
,
HttpStatus
,
Injectable
,
Inject
,
OnModuleDestroy
,
OnApplicationShutdown
}
from
'@nestjs/common'
import
{
Server
,
Socket
}
from
'socket.io'
import
{
Logger
}
from
'@nestjs/common'
import
{
RESPONSE_CODE
,
WsAccess
,
Events
,
WsMessageType
,
WsStatus
,
Command
}
from
'../../common/enums'
...
...
@@ -25,11 +25,7 @@ export class WsService {
login
(
client
:
Socket
,
token
:
string
,
deviceId
:
number
):
WsTypes
.
IWsResponse
<
WsStatus
,
WsAccess
>
{
const
clientIsOnline
:
Socket
=
this
.
findClientByDeviceId
(
deviceId
)
// 处理同一设备号在多处登录
if
(
clientIsOnline
)
{
clientIsOnline
.
emit
(
WsMessageType
.
System
,
`设备->
${
deviceId
}
已在别处上线, 此客户端 [
${
clientIsOnline
.
id
}
] 下线处理`
)
clientIsOnline
?.
disconnect
()
Logger
.
warn
(
`设备->
${
deviceId
}
重复登录, [
${
clientIsOnline
.
id
}
] 先登录的设备下线处理`
)
}
this
.
handleDuplicateLogin
(
clientIsOnline
,
deviceId
)
// 保存工号
this
.
clientIds
.
set
(
deviceId
,
client
.
id
)
const
message
=
`Device->
${
deviceId
}
[
${
client
.
id
}
] Has Connected, OnLine Number:
${
this
.
allClients
.
size
}
`
...
...
@@ -44,6 +40,19 @@ export class WsService {
return
resData
}
/**
* 处理重复登录
* @param clientIsOnline 已经在线的客户端
* @param deviceId 设备ID
*/
private
handleDuplicateLogin
(
clientIsOnline
:
Socket
,
deviceId
:
number
)
{
if
(
clientIsOnline
)
{
clientIsOnline
.
emit
(
WsMessageType
.
Private
,
`设备->
${
deviceId
}
已在别处上线, 此客户端 [
${
clientIsOnline
.
id
}
] 下线处理`
)
clientIsOnline
.
disconnect
()
Logger
.
warn
(
`设备->
${
deviceId
}
重复登录, [
${
clientIsOnline
.
id
}
] 先登录的设备下线处理`
)
}
}
private
findClientByDeviceId
(
deviceId
:
number
):
Socket
{
return
this
.
allClients
?.
get
(
this
.
clientIds
.
get
(
deviceId
))
}
...
...
@@ -51,7 +60,6 @@ export class WsService {
private
get
allClients
():
Map
<
string
,
Socket
>
{
return
this
.
server
?.
sockets
?.
sockets
}
/**
* 登出
* @param client client
...
...
@@ -68,8 +76,7 @@ export class WsService {
}
return
{
data
:
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'登出成功'
}
}
}
@
OnEvent
(
Events
.
OnConnectError
)
async
onConnError
(
out
:
WsTypes
.
WsConnError
):
Promise
<
void
>
{
async
onConnectError
(
out
:
WsTypes
.
WsConnError
):
Promise
<
void
>
{
const
{
device_id
,
message
}
=
out
const
client
:
Socket
=
this
.
findClientByDeviceId
(
device_id
)
if
(
client
)
{
...
...
@@ -102,7 +109,7 @@ export class WsService {
Logger
.
log
(
'Websocket Send Private Error->'
,
payload
)
throw
new
HttpException
({
status
:
HttpStatus
.
BAD_REQUEST
,
message
:
`发送失败`
,
error
:
'send error'
},
HttpStatus
.
BAD_REQUEST
)
}
Logger
.
log
(
payload
)
Logger
.
log
(
payload
)
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'发送成功'
}
}
...
...
@@ -123,7 +130,7 @@ export class WsService {
Logger
.
log
(
payload
)
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'发送成功'
}
}
onMessage
(
message
:
any
)
{
this
.
emit
(
Events
.
OnMessage
,
message
)
onMessage
(
message
:
any
)
{
this
.
emit
(
Events
.
OnMessage
,
message
)
}
}
src/tasks/tasks.service.ts
View file @
210a462
...
...
@@ -5,14 +5,13 @@ import { Events } from '../common/enums'
@
Injectable
()
export
class
TasksService
{
private
readonly
logger
=
new
Logger
(
TasksService
.
name
)
constructor
(
@
Inject
(
EventEmitter2
)
private
eventEmitter
:
EventEmitter2
)
{}
@
Cron
(
'0 10 0 * * *'
)
handleCron
()
{
this
.
eventEmitter
.
emit
(
Events
.
OnTaskStart
)
this
.
eventEmitter
.
emit
(
Events
.
On
Daily
TaskStart
)
Logger
.
warn
(
'============开始每日定时任务============='
)
}
...
...
src/typings/device.d.ts
View file @
210a462
declare
namespace
DeviceTypes
{
type
IQueryDevices
=
Partial
<
CommonTypes
.
IQueryBase
&
CommonTypes
.
ISn
&
CommonTypes
.
IUser
&
Pick
<
DeviceStatus
.
Status
,
'status'
>>
type
IQueryDevices
=
Partial
<
CommonTypes
.
IQueryBase
&
CommonTypes
.
ISn
&
CommonTypes
.
IUser
&
Pick
<
DeviceStatus
.
Status
,
'status'
>>
type
TDeviceInfo
=
CommonTypes
.
ITime
&
Partial
<
CommonTypes
.
IUser
>
type
TDeviceInfo
=
CommonTypes
.
ITime
&
Partial
<
CommonTypes
.
IUser
>
type
TOneDeviceInfo
=
TDeviceInfo
&
CommonTypes
.
IDeviceId
...
...
@@ -15,12 +15,14 @@ declare namespace DeviceTypes {
device_status
:
DeviceStatus
.
Status
fields
:
IFields
[]
}
interface
IDeviceSaves
extends
CommonTypes
.
IDeviceId
,
Partial
<
CommonTypes
.
ISn
>
{
device_info
?:
Partial
<
TDeviceInfo
>
,
log_config
?:
Partial
<
ConfigTypes
.
ILogConfig
>
,
interface
IDeviceSaves
extends
CommonTypes
.
IDeviceId
,
Partial
<
CommonTypes
.
ISn
>
{
device_info
?:
Partial
<
TDeviceInfo
>
log_config
?:
Partial
<
ConfigTypes
.
ILogConfig
>
user_fields
?:
Array
<
Number
>
}
interface
IFields
{
field
?:
FieldTypes
.
TFieldRequird
}
type
TRemoveLogsResultByTask
=
(
CommonTypes
.
IDeviceId
&
Pick
<
ConfigTypes
.
ILogConfig
,
'log_saved_days'
>
)
}
test.http
View file @
210a462
...
...
@@ -39,10 +39,10 @@ POST http://localhost:3000/broadcast/cmd HTTP/1.1
{
"event":"private",
"device_id":"10000
69
",
"device_id":"10000
70
",
"data":{
"command":"getLog",
"days":
7
,
"days":
2
,
"interval":1000,
"force":true
}
...
...
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment