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