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
Show whitespace changes
Inline
Side-by-side
Showing
14 changed files
with
98 additions
and
101 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 {
...
@@ -43,7 +43,7 @@ export enum WsAccess {
IsOnline
=
'通过验证,设备上线'
,
IsOnline
=
'通过验证,设备上线'
,
IsOffline
=
'设备下线'
,
IsOffline
=
'设备下线'
,
ConnFailure
=
'设备连接失败,请检查设备号是否正确'
,
ConnFailure
=
'设备连接失败,请检查设备号是否正确'
,
TokenExpired
=
'token已过期,请重新登录'
TokenExpired
=
'token已过期,请重新登录'
}
}
export
enum
WsAccessCode
{
export
enum
WsAccessCode
{
NotAllowed
=
901
,
NotAllowed
=
901
,
...
@@ -62,9 +62,9 @@ export enum Events {
...
@@ -62,9 +62,9 @@ export enum Events {
OnMessage
=
'client.mesage.received'
,
OnMessage
=
'client.mesage.received'
,
OnLogFileUploaded
=
'log.file.uploaded'
,
OnLogFileUploaded
=
'log.file.uploaded'
,
OnLogFileRemoved
=
'log.file.removed'
,
OnLogFileRemoved
=
'log.file.removed'
,
On
TaskStart
=
'task
.start'
,
On
DailyTaskStart
=
'task.daily
.start'
,
OnSendMessage
=
'client.message.send'
,
OnSendMessage
=
'client.message.send'
,
OnMessageToSendClient
=
'message.send.to.client'
}
}
export
enum
DocTypes
{
export
enum
DocTypes
{
Log
=
'log'
,
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
{
Controller
,
Post
,
Body
,
UseInterceptors
,
UsePipes
,
Logger
}
from
'@nestjs/common'
import
{
BroadcastService
}
from
'./broadcast.service'
import
{
BroadcastService
}
from
'./broadcast.service'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
WsGateway
}
from
'../ws/ws.gateway'
import
{
BroadcastDto
}
from
'../../dto'
import
{
BroadcastDto
}
from
'../../dto'
import
{
ParseDeviceIdPipe
,
ValidationPipe
}
from
'../../common/pipes'
import
{
ParseDeviceIdPipe
,
ValidationPipe
}
from
'../../common/pipes'
import
{
ApiOperation
,
ApiTags
}
from
'@nestjs/swagger'
import
{
ApiOperation
,
ApiTags
}
from
'@nestjs/swagger'
...
@@ -14,10 +13,9 @@ import { Events } from '../../common/enums'
...
@@ -14,10 +13,9 @@ import { Events } from '../../common/enums'
@
UsePipes
(
new
ValidationPipe
())
// 使用管道验证
@
UsePipes
(
new
ValidationPipe
())
// 使用管道验证
export
class
BroadcastController
{
export
class
BroadcastController
{
/**
/**
*
@param wsGateway - WsGateway实例
*
*/
*/
constructor
(
constructor
(
private
readonly
wsGateway
:
WsGateway
,
private
readonly
broadcastService
:
BroadcastService
private
readonly
broadcastService
:
BroadcastService
)
{}
)
{}
...
@@ -30,7 +28,7 @@ export class BroadcastController {
...
@@ -30,7 +28,7 @@ export class BroadcastController {
@
ApiOperation
({
summary
:
'给设备发送指令'
})
@
ApiOperation
({
summary
:
'给设备发送指令'
})
@
UsePipes
(
new
ParseDeviceIdPipe
())
@
UsePipes
(
new
ParseDeviceIdPipe
())
async
message
(@
Body
()
params
:
BroadcastDto
):
Promise
<
CommonTypes
.
IResData
>
{
async
message
(@
Body
()
params
:
BroadcastDto
):
Promise
<
CommonTypes
.
IResData
>
{
return
this
.
wsGateway
.
send
(
params
)
return
this
.
broadcastService
.
send
(
params
)
}
}
@
OnEvent
(
Events
.
OnMessage
)
@
OnEvent
(
Events
.
OnMessage
)
onMessage
(@
Body
()
params
:
any
):
Promise
<
CommonTypes
.
IResData
>
{
onMessage
(@
Body
()
params
:
any
):
Promise
<
CommonTypes
.
IResData
>
{
...
...
src/modules/broadcast/broadcast.module.ts
View file @
210a462
import
{
Module
}
from
'@nestjs/common'
import
{
Module
}
from
'@nestjs/common'
import
{
BroadcastController
}
from
'./broadcast.controller'
import
{
BroadcastController
}
from
'./broadcast.controller'
import
{
BroadcastService
}
from
'./broadcast.service'
import
{
BroadcastService
}
from
'./broadcast.service'
import
{
WsModule
}
from
'../ws/ws.module'
;
import
{
HttpModule
}
from
'@nestjs/axios'
;
import
{
HttpModule
}
from
'@nestjs/axios'
;
@
Module
({
@
Module
({
imports
:
[
WsModule
,
HttpModule
],
imports
:
[
HttpModule
],
controllers
:
[
BroadcastController
],
controllers
:
[
BroadcastController
],
providers
:
[
BroadcastService
]
providers
:
[
BroadcastService
]
})
})
...
...
src/modules/broadcast/broadcast.service.ts
View file @
210a462
...
@@ -2,7 +2,7 @@ import { HttpService } from '@nestjs/axios'
...
@@ -2,7 +2,7 @@ import { HttpService } from '@nestjs/axios'
import
{
Inject
,
Injectable
}
from
'@nestjs/common'
import
{
Inject
,
Injectable
}
from
'@nestjs/common'
import
{
AxiosResponse
}
from
'axios'
import
{
AxiosResponse
}
from
'axios'
import
{
ConfigService
}
from
'nestjs-config'
import
{
ConfigService
}
from
'nestjs-config'
import
{
Command
,
Events
,
RESPONSE_CODE
}
from
'../../common/enums'
import
{
Command
,
Events
,
RESPONSE_CODE
,
WsMessageType
}
from
'../../common/enums'
import
{
EventEmitter2
}
from
'@nestjs/event-emitter'
import
{
EventEmitter2
}
from
'@nestjs/event-emitter'
@
Injectable
()
@
Injectable
()
export
class
BroadcastService
{
export
class
BroadcastService
{
...
@@ -15,6 +15,11 @@ export class BroadcastService {
...
@@ -15,6 +15,11 @@ export class BroadcastService {
)
{
)
{
this
.
webHook
=
this
.
config
.
get
(
'env'
).
AppWebhook
this
.
webHook
=
this
.
config
.
get
(
'env'
).
AppWebhook
}
}
async
send
(
message
:
WsTypes
.
MessageBody
<
Command
,
WsMessageType
>
):
Promise
<
CommonTypes
.
IResData
>
{
const
success
=
this
.
eventEmitter
.
emit
(
Events
.
OnMessageToSendClient
,
message
)
return
{
code
:
success
?
RESPONSE_CODE
.
SUCCESS
:
RESPONSE_CODE
.
NOSUCCESS
,
data
:
{
success
}
}
}
// // 广播消息
// // 广播消息
async
onMessage
(
param
:
any
):
Promise
<
CommonTypes
.
IResData
>
{
async
onMessage
(
param
:
any
):
Promise
<
CommonTypes
.
IResData
>
{
if
(
param
?.
code
==
RESPONSE_CODE
.
SUCCESS
&&
param
?.
data
?.
command
===
Command
.
RemoveLog
)
{
if
(
param
?.
code
==
RESPONSE_CODE
.
SUCCESS
&&
param
?.
data
?.
command
===
Command
.
RemoveLog
)
{
...
...
src/modules/device/device.controller.ts
View file @
210a462
...
@@ -50,7 +50,6 @@ export class DeviceController {
...
@@ -50,7 +50,6 @@ export class DeviceController {
@
Post
(
'/add'
)
@
Post
(
'/add'
)
@
ApiOperation
({
summary
:
'添加设备'
})
@
ApiOperation
({
summary
:
'添加设备'
})
async
addDevice
(@
Body
()
param
:
AddDeviceInfoDto
):
Promise
<
CommonTypes
.
IResponseBase
>
{
async
addDevice
(@
Body
()
param
:
AddDeviceInfoDto
):
Promise
<
CommonTypes
.
IResponseBase
>
{
// console.log(param)
return
await
this
.
deviceService
.
addDevice
(
param
)
return
await
this
.
deviceService
.
addDevice
(
param
)
}
}
/**
/**
...
@@ -62,7 +61,6 @@ export class DeviceController {
...
@@ -62,7 +61,6 @@ export class DeviceController {
@
Post
(
'/addInfo'
)
@
Post
(
'/addInfo'
)
@
ApiOperation
({
summary
:
'添加设备信息'
})
@
ApiOperation
({
summary
:
'添加设备信息'
})
async
addDeviceInfo
(@
Body
()
param
:
UpdateDeviceInfoDto
):
Promise
<
CommonTypes
.
IResData
>
{
async
addDeviceInfo
(@
Body
()
param
:
UpdateDeviceInfoDto
):
Promise
<
CommonTypes
.
IResData
>
{
// console.log(param)
return
await
this
.
deviceService
.
addDeviceInfo
(
param
)
return
await
this
.
deviceService
.
addDeviceInfo
(
param
)
}
}
...
@@ -84,8 +82,8 @@ export class DeviceController {
...
@@ -84,8 +82,8 @@ export class DeviceController {
* @param param - 包含设备状态的DTO对象
* @param param - 包含设备状态的DTO对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/
*/
@
OnEvent
(
Events
.
OnConnected
)
@
Post
(
'/upsertStatus'
)
@
Post
(
'/upsertStatus'
)
@
OnEvent
(
Events
.
OnConnected
)
@
ApiOperation
({
summary
:
'更新设备状态'
})
@
ApiOperation
({
summary
:
'更新设备状态'
})
async
upsertDeviceStatus
(@
Body
()
param
:
DeviceStatusDto
):
Promise
<
void
|
CommonTypes
.
IResData
>
{
async
upsertDeviceStatus
(@
Body
()
param
:
DeviceStatusDto
):
Promise
<
void
|
CommonTypes
.
IResData
>
{
return
await
this
.
deviceService
.
upsertDeviceStatus
(
param
).
catch
(
error
=>
{
return
await
this
.
deviceService
.
upsertDeviceStatus
(
param
).
catch
(
error
=>
{
...
@@ -93,8 +91,8 @@ export class DeviceController {
...
@@ -93,8 +91,8 @@ export class DeviceController {
this
.
eventEmitter
.
emit
(
Events
.
OnConnectError
,
out
)
this
.
eventEmitter
.
emit
(
Events
.
OnConnectError
,
out
)
})
})
}
}
@
OnEvent
(
Events
.
OnLogFileRemoved
)
@
Post
(
'/upsertFileRemovedTime'
)
@
Post
(
'/upsertFileRemovedTime'
)
@
OnEvent
(
Events
.
OnLogFileRemoved
)
@
ApiOperation
({
summary
:
'更新设备状态'
})
@
ApiOperation
({
summary
:
'更新设备状态'
})
async
upsertFileRemovedTime
(@
Body
()
param
:
DeviceStatusDto
):
Promise
<
void
|
CommonTypes
.
IResData
>
{
async
upsertFileRemovedTime
(@
Body
()
param
:
DeviceStatusDto
):
Promise
<
void
|
CommonTypes
.
IResData
>
{
return
await
this
.
deviceService
.
upsertFileRemovedTime
(
param
)
return
await
this
.
deviceService
.
upsertFileRemovedTime
(
param
)
...
@@ -114,8 +112,8 @@ export class DeviceController {
...
@@ -114,8 +112,8 @@ export class DeviceController {
}
}
@
Get
(
'/task'
)
@
Get
(
'/task'
)
@
OnEvent
(
Events
.
OnTaskStart
)
@
OnEvent
(
Events
.
On
Daily
TaskStart
)
@
ApiOperation
({
summary
:
'日任务'
})
@
ApiOperation
({
summary
:
'
每
日任务'
})
async
task
():
Promise
<
void
|
CommonTypes
.
IResData
>
{
async
task
():
Promise
<
void
|
CommonTypes
.
IResData
>
{
return
await
this
.
deviceService
.
removeFilesTask
()
return
await
this
.
deviceService
.
removeFilesTask
()
}
}
...
@@ -124,11 +122,4 @@ export class DeviceController {
...
@@ -124,11 +122,4 @@ export class DeviceController {
async
addAll
(
devices
:
Array
<
any
>
):
Promise
<
void
|
CommonTypes
.
IResData
>
{
async
addAll
(
devices
:
Array
<
any
>
):
Promise
<
void
|
CommonTypes
.
IResData
>
{
// return this.deviceService.addAll(devices)
// 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';
...
@@ -2,13 +2,10 @@ import { Module } from '@nestjs/common';
import
{
DeviceController
}
from
'./device.controller'
;
import
{
DeviceController
}
from
'./device.controller'
;
import
{
DeviceService
}
from
'./device.service'
;
import
{
DeviceService
}
from
'./device.service'
;
import
{
PrismaModule
}
from
'nestjs-prisma'
;
import
{
PrismaModule
}
from
'nestjs-prisma'
;
import
{
WsModule
}
from
'../ws/ws.module'
;
import
{
WsService
}
from
'../ws/ws.service'
;
// import { EventEmitter2 } from '@nestjs/event-emitter';
@
Module
({
@
Module
({
imports
:
[
PrismaModule
],
imports
:
[
PrismaModule
],
controllers
:
[
DeviceController
],
controllers
:
[
DeviceController
],
providers
:
[
DeviceService
,
WsService
],
providers
:
[
DeviceService
],
exports
:
[
DeviceService
],
exports
:
[
DeviceService
],
})
})
export
class
DeviceModule
{}
export
class
DeviceModule
{}
src/modules/device/device.service.ts
View file @
210a462
...
@@ -3,8 +3,7 @@ import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } f
...
@@ -3,8 +3,7 @@ import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } f
// import { InjectRepository } from '@nestjs/typeorm';
// import { InjectRepository } from '@nestjs/typeorm';
// import { Device as DeviceEntity } from '../entities/Device'
// import { Device as DeviceEntity } from '../entities/Device'
import
{
PrismaService
}
from
'nestjs-prisma'
import
{
PrismaService
}
from
'nestjs-prisma'
import
{
Command
,
RESPONSE_CODE
,
WsMessageType
,
WsStatus
}
from
'../../common/enums'
import
{
Command
,
Events
,
RESPONSE_CODE
,
WsMessageType
,
WsStatus
}
from
'../../common/enums'
import
{
WsService
}
from
'../ws/ws.service'
import
{
EventEmitter2
}
from
'@nestjs/event-emitter'
import
{
EventEmitter2
}
from
'@nestjs/event-emitter'
@
Injectable
()
@
Injectable
()
...
@@ -13,7 +12,7 @@ export class DeviceService implements OnModuleInit {
...
@@ -13,7 +12,7 @@ export class DeviceService implements OnModuleInit {
@
Inject
(
PrismaService
)
@
Inject
(
PrismaService
)
private
readonly
prisma
:
PrismaService
,
// private connection: Connection,
private
readonly
prisma
:
PrismaService
,
// private connection: Connection,
@
Inject
(
EventEmitter2
)
@
Inject
(
EventEmitter2
)
private
readonly
wsService
:
WsService
private
readonly
eventEmitter
:
EventEmitter2
)
{}
)
{}
async
onModuleInit
()
{
async
onModuleInit
()
{
this
.
resetAllDeviceStatus
()
this
.
resetAllDeviceStatus
()
...
@@ -119,7 +118,7 @@ export class DeviceService implements OnModuleInit {
...
@@ -119,7 +118,7 @@ export class DeviceService implements OnModuleInit {
data
:
user_fields
.
map
((
item
:
number
)
=>
({
device_id
,
field_id
:
item
}))
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))
// await this.addDeviceInfo(Object.assign({ device_id: id },deviceInfo))
})
})
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'添加设备成功'
}
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'添加设备成功'
}
...
@@ -128,8 +127,6 @@ export class DeviceService implements OnModuleInit {
...
@@ -128,8 +127,6 @@ export class DeviceService implements OnModuleInit {
async
addDeviceInfo
(
deviceInfo
:
DeviceTypes
.
IDeviceSaves
):
Promise
<
CommonTypes
.
IResData
>
{
async
addDeviceInfo
(
deviceInfo
:
DeviceTypes
.
IDeviceSaves
):
Promise
<
CommonTypes
.
IResData
>
{
const
now
=
new
Date
()
const
now
=
new
Date
()
const
{
device_id
,
...
data
}
=
deviceInfo
const
{
device_id
,
...
data
}
=
deviceInfo
console
.
log
(
'device_id'
,
device_id
)
const
{
device_info
,
log_config
,
user_fields
,
sn
}
=
data
const
{
device_info
,
log_config
,
user_fields
,
sn
}
=
data
await
this
.
prisma
.
$transaction
(
async
prisma
=>
{
await
this
.
prisma
.
$transaction
(
async
prisma
=>
{
if
(
sn
)
{
if
(
sn
)
{
...
@@ -147,7 +144,7 @@ export class DeviceService implements OnModuleInit {
...
@@ -147,7 +144,7 @@ export class DeviceService implements OnModuleInit {
data
:
user_fields
.
map
((
item
:
number
)
=>
({
device_id
,
field_id
:
item
}))
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
:
'添加设备信息成功'
}
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'添加设备信息成功'
}
}
}
...
@@ -184,10 +181,11 @@ export class DeviceService implements OnModuleInit {
...
@@ -184,10 +181,11 @@ export class DeviceService implements OnModuleInit {
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'设备信息更新成功'
}
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'设备信息更新成功'
}
}
}
async
upsertDeviceStatus
(
data
:
DeviceStatus
.
IDeviceStatus
):
Promise
<
CommonTypes
.
IResData
>
{
async
upsertDeviceStatus
(
data
:
DeviceStatus
.
IDeviceStatus
):
Promise
<
CommonTypes
.
IResData
>
{
const
now
=
new
Date
()
await
this
.
prisma
.
device_status
.
upsert
({
await
this
.
prisma
.
device_status
.
upsert
({
where
:
{
device_id
:
data
.
device_id
},
where
:
{
device_id
:
data
.
device_id
},
create
:
{
device_id
:
data
.
device_id
,
status
:
WsStatus
.
Offline
},
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
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
}
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
:
'设备状态更新成功'
}
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'设备状态更新成功'
}
}
}
...
@@ -213,7 +211,7 @@ export class DeviceService implements OnModuleInit {
...
@@ -213,7 +211,7 @@ export class DeviceService implements OnModuleInit {
await
this
.
prisma
.
$transaction
(
async
prisma
=>
{
await
this
.
prisma
.
$transaction
(
async
prisma
=>
{
const
{
id
}
=
await
prisma
.
device
.
create
({
data
:
{
sn
:
el
.
设备编号
},
select
:
{
id
:
true
}
})
const
{
id
}
=
await
prisma
.
device
.
create
({
data
:
{
sn
:
el
.
设备编号
},
select
:
{
id
:
true
}
})
await
prisma
.
device_info
.
create
({
data
:
{
device_id
:
id
,
mobile
:
el
.
手机号
,
merchant_name
:
el
.
最近使用人所在门店
||
''
,
user
:
el
.
保管人
,
created_at
:
new
Date
(),
updated_at
:
new
Date
()
}
})
await
prisma
.
device_info
.
create
({
data
:
{
device_id
:
id
,
mobile
:
el
.
手机号
,
merchant_name
:
el
.
最近使用人所在门店
||
''
,
user
:
el
.
保管人
,
created_at
:
new
Date
(),
updated_at
:
new
Date
()
}
})
await
prisma
.
device_status
.
create
({
data
:
{
device_id
:
id
,
status
:
WsStatus
.
Offline
}
})
await
prisma
.
device_status
.
create
({
data
:
{
device_id
:
id
,
status
:
WsStatus
.
Offline
,
last_log_remove_time
:
new
Date
()
}
})
await
prisma
.
log_config
.
create
({
data
:
{
device_id
:
id
,
log_saved_days
:
7
}
})
await
prisma
.
log_config
.
create
({
data
:
{
device_id
:
id
,
log_saved_days
:
7
}
})
await
prisma
.
field_relation
.
createMany
({
await
prisma
.
field_relation
.
createMany
({
data
:
[
data
:
[
...
@@ -228,14 +226,21 @@ export class DeviceService implements OnModuleInit {
...
@@ -228,14 +226,21 @@ export class DeviceService implements OnModuleInit {
}
}
async
removeFilesTask
():
Promise
<
CommonTypes
.
IResData
>
{
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'
>
)
[]
>
`
const
results
:
DeviceTypes
.
TRemoveLogsResultByTask
[]
=
await
this
.
prisma
.
$queryRaw
<
DeviceTypes
.
TRemoveLogsResultByTask
[]
>
`
SELECT d.device_id, c.log_saved_days
SELECT d.device_id, c.log_saved_days
FROM device_info d
FROM device_info d
JOIN log_config c ON c.device_id = d.device_id
JOIN log_config c ON c.device_id = d.device_id
WHERE c.log_saved_days >= TIMESTAMPDIFF(DAY, d.last_log_remove_time, NOW());`
JOIN device_status s ON s.device_id = d.device_id
for
(
const
{
device_id
,
log_saved_days
}
of
results
)
{
WHERE c.log_saved_days < TIMESTAMPDIFF(DAY, s.last_log_remove_time, NOW()) AND s.status=1`
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
}
}
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
:
'每日日志删除任务完成'
}
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'每日日志删除任务完成'
}
}
}
...
...
src/modules/ws/ws.gateway.ts
View file @
210a462
...
@@ -3,11 +3,12 @@ import { from, Observable } from 'rxjs'
...
@@ -3,11 +3,12 @@ import { from, Observable } from 'rxjs'
import
{
map
}
from
'rxjs/operators'
import
{
map
}
from
'rxjs/operators'
import
{
Server
,
Socket
}
from
'socket.io'
import
{
Server
,
Socket
}
from
'socket.io'
import
{
WsService
}
from
'./ws.service'
import
{
WsService
}
from
'./ws.service'
import
{
Inject
,
Logger
,
Module
,
UseInterceptors
}
from
'@nestjs/common'
import
{
Inject
,
Logger
,
Module
,
UseInterceptors
,
UsePipes
}
from
'@nestjs/common'
import
{
WsMessageType
,
WsStatus
,
WsAccess
,
Command
,
WsAccessCode
}
from
'../../common/enums'
import
{
WsMessageType
,
WsStatus
,
WsAccess
,
Command
,
WsAccessCode
,
Events
}
from
'../../common/enums'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
JwtService
,
TokenExpiredError
}
from
'@nestjs/jwt'
import
{
JwtService
,
TokenExpiredError
}
from
'@nestjs/jwt'
import
{
AuthService
}
from
'../auth/auth.service'
import
{
AuthService
}
from
'../auth/auth.service'
import
{
OnEvent
}
from
'@nestjs/event-emitter'
/**
/**
* WebSocket 网关
* WebSocket 网关
...
@@ -63,48 +64,34 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
...
@@ -63,48 +64,34 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
*/
*/
handleConnection
(
client
:
Socket
):
WsTypes
.
IWsResponse
<
WsStatus
,
WsAccess
>
{
handleConnection
(
client
:
Socket
):
WsTypes
.
IWsResponse
<
WsStatus
,
WsAccess
>
{
const
auth
=
client
.
handshake
?.
auth
??
client
.
handshake
?.
headers
const
auth
=
client
.
handshake
?.
auth
??
client
.
handshake
?.
headers
const
ValidateData
:
WsTypes
.
LoginValidate
<
WsAccess
>
=
{
isValidate
:
true
,
errMsg
:
WsAccess
.
IsOnline
,
errorCode
:
WsAccessCode
.
IsOnline
}
if
(
!
auth
)
{
if
(
!
auth
)
{
ValidateData
.
isValidate
=
false
return
this
.
handleInvalidAuth
(
client
,
WsAccess
.
NotAllowed
,
WsAccessCode
.
NotAllowed
)
ValidateData
.
errMsg
=
WsAccess
.
NotAllowed
ValidateData
.
errorCode
=
WsAccessCode
.
NotAllowed
}
}
const
{
token
,
deviceId
}
=
auth
const
{
token
,
deviceId
}
=
auth
// 注册用户
if
(
!
token
)
{
if
(
!
token
)
{
ValidateData
.
isValidate
=
false
return
this
.
handleInvalidAuth
(
client
,
WsAccess
.
InValidToken
,
WsAccessCode
.
InValidToken
)
ValidateData
.
errMsg
=
WsAccess
.
InValidToken
ValidateData
.
errorCode
=
WsAccessCode
.
InValidToken
}
}
if
(
!
deviceId
)
{
if
(
!
deviceId
)
{
ValidateData
.
isValidate
=
false
return
this
.
handleInvalidAuth
(
client
,
WsAccess
.
InvalidDeviceId
,
WsAccessCode
.
InvalidDeviceId
)
ValidateData
.
errMsg
=
WsAccess
.
InvalidDeviceId
ValidateData
.
errorCode
=
WsAccessCode
.
InvalidDeviceId
}
}
const
verify
=
this
.
authService
.
verifyToken
(
String
(
token
))
const
verify
=
this
.
authService
.
verifyToken
(
String
(
token
))
if
(
!
verify
.
isPass
)
{
if
(
!
verify
.
isPass
)
{
ValidateData
.
isValidate
=
false
const
errorCode
=
verify
.
isExpired
?
WsAccessCode
.
TokenExpired
:
WsAccessCode
.
InValidToken
if
(
verify
.
isExpired
)
{
return
this
.
handleInvalidAuth
(
client
,
WsAccess
.
TokenExpired
,
errorCode
)
ValidateData
.
errMsg
=
WsAccess
.
TokenExpired
ValidateData
.
errorCode
=
WsAccessCode
.
TokenExpired
}
else
{
ValidateData
.
errMsg
=
WsAccess
.
InValidToken
ValidateData
.
errorCode
=
WsAccessCode
.
InValidToken
}
}
return
this
.
wsService
.
login
(
client
,
token
,
deviceId
)
}
}
if
(
!
ValidateData
.
isValidate
)
{
const
msg
=
`
${
ValidateData
.
errMsg
}
token->
${
token
}
deviceId->
${
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)
Logger.error(msg)
client
.
emit
(
WsMessageType
.
Private
,
ValidateData
)
client.emit(WsMessageType.Private, { isValidate: false, errMsg, errorCode })
const
resData
:
WsTypes
.
IWsResponse
<
WsStatus
,
WsAccess
>
=
{
status
:
WsStatus
.
Offline
,
message
:
ValidateData
.
errMsg
,
device_id
:
deviceId
}
client.disconnect()
client.disconnect()
return
resData
return {
status: WsStatus.Offline,
message: errMsg,
device_id: client.handshake.auth?.deviceId
}
}
return
this
.
wsService
.
login
(
client
,
token
,
deviceId
)
}
}
/**
/**
...
@@ -133,7 +120,13 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
...
@@ -133,7 +120,13 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* @param payload
* @param payload
*/
*/
@OnEvent(Events.OnMessageToSendClient)
public send(payload: WsTypes.MessageBody<Command, WsMessageType>): Promise<CommonTypes.IResData> {
public send(payload: WsTypes.MessageBody<Command, WsMessageType>): Promise<CommonTypes.IResData> {
return this.wsService[{ [WsMessageType.Private]: 'sendPrivateMessage', [WsMessageType.System]: 'sendPublicMessage' }[payload.event]](payload)
return this.wsService[{ [WsMessageType.Private]: 'sendPrivateMessage', [WsMessageType.System]: 'sendPublicMessage' }[payload.event]](payload)
}
}
@OnEvent(Events.OnConnectError)
async onConnectError(out: WsTypes.WsConnError): Promise<void> {
return this.wsService.onConnectError(out)
}
}
}
src/modules/ws/ws.module.ts
View file @
210a462
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
{
JwtModule
,
JwtService
}
from
'@nestjs/jwt'
import
{
AuthModule
}
from
'../auth/auth.module'
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
({
@
Module
({
imports
:
[
AuthModule
],
imports
:
[
AuthModule
],
providers
:
[
WsGateway
,
WsService
],
providers
:
[
WsGateway
,
WsService
]
exports
:
[
WsGateway
]
})
})
export
class
WsModule
{}
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
{
Server
,
Socket
}
from
'socket.io'
import
{
Logger
}
from
'@nestjs/common'
import
{
Logger
}
from
'@nestjs/common'
import
{
RESPONSE_CODE
,
WsAccess
,
Events
,
WsMessageType
,
WsStatus
,
Command
}
from
'../../common/enums'
import
{
RESPONSE_CODE
,
WsAccess
,
Events
,
WsMessageType
,
WsStatus
,
Command
}
from
'../../common/enums'
...
@@ -25,11 +25,7 @@ export class WsService {
...
@@ -25,11 +25,7 @@ export class WsService {
login
(
client
:
Socket
,
token
:
string
,
deviceId
:
number
):
WsTypes
.
IWsResponse
<
WsStatus
,
WsAccess
>
{
login
(
client
:
Socket
,
token
:
string
,
deviceId
:
number
):
WsTypes
.
IWsResponse
<
WsStatus
,
WsAccess
>
{
const
clientIsOnline
:
Socket
=
this
.
findClientByDeviceId
(
deviceId
)
const
clientIsOnline
:
Socket
=
this
.
findClientByDeviceId
(
deviceId
)
// 处理同一设备号在多处登录
// 处理同一设备号在多处登录
if
(
clientIsOnline
)
{
this
.
handleDuplicateLogin
(
clientIsOnline
,
deviceId
)
clientIsOnline
.
emit
(
WsMessageType
.
System
,
`设备->
${
deviceId
}
已在别处上线, 此客户端 [
${
clientIsOnline
.
id
}
] 下线处理`
)
clientIsOnline
?.
disconnect
()
Logger
.
warn
(
`设备->
${
deviceId
}
重复登录, [
${
clientIsOnline
.
id
}
] 先登录的设备下线处理`
)
}
// 保存工号
// 保存工号
this
.
clientIds
.
set
(
deviceId
,
client
.
id
)
this
.
clientIds
.
set
(
deviceId
,
client
.
id
)
const
message
=
`Device->
${
deviceId
}
[
${
client
.
id
}
] Has Connected, OnLine Number:
${
this
.
allClients
.
size
}
`
const
message
=
`Device->
${
deviceId
}
[
${
client
.
id
}
] Has Connected, OnLine Number:
${
this
.
allClients
.
size
}
`
...
@@ -44,6 +40,19 @@ export class WsService {
...
@@ -44,6 +40,19 @@ export class WsService {
return
resData
return
resData
}
}
/**
* 处理重复登录
* @param clientIsOnline 已经在线的客户端
* @param deviceId 设备ID
*/
private
handleDuplicateLogin
(
clientIsOnline
:
Socket
,
deviceId
:
number
)
{
if
(
clientIsOnline
)
{
clientIsOnline
.
emit
(
WsMessageType
.
Private
,
`设备->
${
deviceId
}
已在别处上线, 此客户端 [
${
clientIsOnline
.
id
}
] 下线处理`
)
clientIsOnline
.
disconnect
()
Logger
.
warn
(
`设备->
${
deviceId
}
重复登录, [
${
clientIsOnline
.
id
}
] 先登录的设备下线处理`
)
}
}
private
findClientByDeviceId
(
deviceId
:
number
):
Socket
{
private
findClientByDeviceId
(
deviceId
:
number
):
Socket
{
return
this
.
allClients
?.
get
(
this
.
clientIds
.
get
(
deviceId
))
return
this
.
allClients
?.
get
(
this
.
clientIds
.
get
(
deviceId
))
}
}
...
@@ -51,7 +60,6 @@ export class WsService {
...
@@ -51,7 +60,6 @@ export class WsService {
private
get
allClients
():
Map
<
string
,
Socket
>
{
private
get
allClients
():
Map
<
string
,
Socket
>
{
return
this
.
server
?.
sockets
?.
sockets
return
this
.
server
?.
sockets
?.
sockets
}
}
/**
/**
* 登出
* 登出
* @param client client
* @param client client
...
@@ -68,8 +76,7 @@ export class WsService {
...
@@ -68,8 +76,7 @@ export class WsService {
}
}
return
{
data
:
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'登出成功'
}
}
return
{
data
:
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'登出成功'
}
}
}
}
@
OnEvent
(
Events
.
OnConnectError
)
async
onConnectError
(
out
:
WsTypes
.
WsConnError
):
Promise
<
void
>
{
async
onConnError
(
out
:
WsTypes
.
WsConnError
):
Promise
<
void
>
{
const
{
device_id
,
message
}
=
out
const
{
device_id
,
message
}
=
out
const
client
:
Socket
=
this
.
findClientByDeviceId
(
device_id
)
const
client
:
Socket
=
this
.
findClientByDeviceId
(
device_id
)
if
(
client
)
{
if
(
client
)
{
...
@@ -102,7 +109,7 @@ export class WsService {
...
@@ -102,7 +109,7 @@ export class WsService {
Logger
.
log
(
'Websocket Send Private Error->'
,
payload
)
Logger
.
log
(
'Websocket Send Private Error->'
,
payload
)
throw
new
HttpException
({
status
:
HttpStatus
.
BAD_REQUEST
,
message
:
`发送失败`
,
error
:
'send error'
},
HttpStatus
.
BAD_REQUEST
)
throw
new
HttpException
({
status
:
HttpStatus
.
BAD_REQUEST
,
message
:
`发送失败`
,
error
:
'send error'
},
HttpStatus
.
BAD_REQUEST
)
}
}
Logger
.
log
(
payload
)
Logger
.
log
(
payload
)
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'发送成功'
}
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'发送成功'
}
}
}
...
@@ -123,7 +130,7 @@ export class WsService {
...
@@ -123,7 +130,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
)
{
onMessage
(
message
:
any
)
{
this
.
emit
(
Events
.
OnMessage
,
message
)
this
.
emit
(
Events
.
OnMessage
,
message
)
}
}
}
}
src/tasks/tasks.service.ts
View file @
210a462
...
@@ -5,14 +5,13 @@ import { Events } from '../common/enums'
...
@@ -5,14 +5,13 @@ import { Events } from '../common/enums'
@
Injectable
()
@
Injectable
()
export
class
TasksService
{
export
class
TasksService
{
private
readonly
logger
=
new
Logger
(
TasksService
.
name
)
constructor
(
constructor
(
@
Inject
(
EventEmitter2
)
@
Inject
(
EventEmitter2
)
private
eventEmitter
:
EventEmitter2
private
eventEmitter
:
EventEmitter2
)
{}
)
{}
@
Cron
(
'0 10 0 * * *'
)
@
Cron
(
'0 10 0 * * *'
)
handleCron
()
{
handleCron
()
{
this
.
eventEmitter
.
emit
(
Events
.
OnTaskStart
)
this
.
eventEmitter
.
emit
(
Events
.
On
Daily
TaskStart
)
Logger
.
warn
(
'============开始每日定时任务============='
)
Logger
.
warn
(
'============开始每日定时任务============='
)
}
}
...
...
src/typings/device.d.ts
View file @
210a462
declare
namespace
DeviceTypes
{
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
>
...
@@ -15,12 +15,14 @@ declare namespace DeviceTypes {
...
@@ -15,12 +15,14 @@ declare namespace DeviceTypes {
device_status
:
DeviceStatus
.
Status
device_status
:
DeviceStatus
.
Status
fields
:
IFields
[]
fields
:
IFields
[]
}
}
interface
IDeviceSaves
extends
CommonTypes
.
IDeviceId
,
Partial
<
CommonTypes
.
ISn
>
{
interface
IDeviceSaves
extends
CommonTypes
.
IDeviceId
,
Partial
<
CommonTypes
.
ISn
>
{
device_info
?:
Partial
<
TDeviceInfo
>
,
device_info
?:
Partial
<
TDeviceInfo
>
log_config
?:
Partial
<
ConfigTypes
.
ILogConfig
>
,
log_config
?:
Partial
<
ConfigTypes
.
ILogConfig
>
user_fields
?:
Array
<
Number
>
user_fields
?:
Array
<
Number
>
}
}
interface
IFields
{
interface
IFields
{
field
?:
FieldTypes
.
TFieldRequird
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
...
@@ -39,10 +39,10 @@ POST http://localhost:3000/broadcast/cmd HTTP/1.1
{
{
"event":"private",
"event":"private",
"device_id":"10000
69
",
"device_id":"10000
70
",
"data":{
"data":{
"command":"getLog",
"command":"getLog",
"days":
7
,
"days":
2
,
"interval":1000,
"interval":1000,
"force":true
"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