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 d7c547b0
authored
Sep 26, 2024
by
yixinjj
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
添加jwt认证
1 parent
2011043d
Hide whitespace changes
Inline
Side-by-side
Showing
24 changed files
with
259 additions
and
117 deletions
.env
src/app.module.ts
src/common/enums/index.ts
src/common/pipes/arguments.pipe.ts
src/common/pipes/ws.pipe.ts
src/dto/device.dto.ts
src/modules/auth/auth.controller.ts
src/modules/auth/auth.module.ts
src/modules/auth/auth.service.ts
src/modules/auth/jwt.strategy.ts
src/modules/auth/local.strategy.ts
src/modules/broadcast/broadcast.module.ts
src/modules/config/config.module.ts
src/modules/device/device.controller.ts
src/modules/device/device.module.ts
src/modules/device/device.service.ts
src/modules/fields/fields.module.ts
src/modules/file/file.module.ts
src/modules/ws/ws.gateway.ts
src/modules/ws/ws.module.ts
src/tasks/tasks.service.ts
src/typings/device.d.ts
src/typings/ws.d.ts
test.http
.env
View file @
d7c547b
...
@@ -8,4 +8,5 @@ DATABASE_URL="mysql://limin:limin1018@192.168.1.129:3306/app_admin?schema=public
...
@@ -8,4 +8,5 @@ DATABASE_URL="mysql://limin:limin1018@192.168.1.129:3306/app_admin?schema=public
QIWEI_WEBHOOK='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=8541005c-5f60-416b-821e-64b4d872cd77'
QIWEI_WEBHOOK='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=8541005c-5f60-416b-821e-64b4d872cd77'
SOCKET_PORT= 8080
SOCKET_PORT= 8080
APP_PORT= 3000
APP_PORT= 3000
STATIC_PATH= "public"
\ No newline at end of file
\ No newline at end of file
STATIC_PATH = "public"
JWT_SECRET = 'secretKey'
\ No newline at end of file
\ No newline at end of file
src/app.module.ts
View file @
d7c547b
...
@@ -8,7 +8,7 @@ import statusMonitorConfig from './config/statusMonitor'
...
@@ -8,7 +8,7 @@ import statusMonitorConfig from './config/statusMonitor'
import
{
LoggerMiddleware
}
from
'./common/middleware/logger.middleware'
import
{
LoggerMiddleware
}
from
'./common/middleware/logger.middleware'
import
{
TasksModule
}
from
'./tasks/tasks.module'
import
{
TasksModule
}
from
'./tasks/tasks.module'
// import { AudioModule } from './jobs/audio/audio.module'
// import { AudioModule } from './jobs/audio/audio.module'
//
import { AuthModule } from './modules/auth/auth.module'
import
{
AuthModule
}
from
'./modules/auth/auth.module'
// import { HelloModule } from './modules/hello/hello.module'
// import { HelloModule } from './modules/hello/hello.module'
import
{
DeviceModule
}
from
'./modules/device/device.module'
import
{
DeviceModule
}
from
'./modules/device/device.module'
// import { ExceptionModule } from './modules/exception/exception.module'
// import { ExceptionModule } from './modules/exception/exception.module'
...
@@ -26,6 +26,7 @@ import { HttpModule } from '@nestjs/axios'
...
@@ -26,6 +26,7 @@ import { HttpModule } from '@nestjs/axios'
import
{
FieldsModule
}
from
'./modules/fields/fields.module'
import
{
FieldsModule
}
from
'./modules/fields/fields.module'
import
{
WinstonModule
}
from
'nest-winston'
import
{
WinstonModule
}
from
'nest-winston'
import
winstonLogger
from
'./initor/winstion.config'
import
winstonLogger
from
'./initor/winstion.config'
import
{
JwtModule
}
from
'@nestjs/jwt'
@
Module
({
@
Module
({
imports
:
[
imports
:
[
...
@@ -46,11 +47,11 @@ import winstonLogger from './initor/winstion.config'
...
@@ -46,11 +47,11 @@ import winstonLogger from './initor/winstion.config'
// useFactory: (config: ConfigService) => config.get('email'),
// useFactory: (config: ConfigService) => config.get('email'),
// inject: [ConfigService]
// inject: [ConfigService]
// }),
// }),
ScheduleModule
.
forRoot
(),
ScheduleModule
.
forRoot
(),
EventEmitterModule
.
forRoot
(),
EventEmitterModule
.
forRoot
(),
DeviceModule
,
TasksModule
,
TasksModule
,
// AudioModule,
// AudioModule,
// AuthModule,
// HelloModule,
// HelloModule,
// ExceptionModule,
// ExceptionModule,
// RoleGuardModule,
// RoleGuardModule,
...
@@ -58,8 +59,8 @@ import winstonLogger from './initor/winstion.config'
...
@@ -58,8 +59,8 @@ import winstonLogger from './initor/winstion.config'
// UsersModule,
// UsersModule,
FileModule
,
FileModule
,
// SseModule,
// SseModule,
AuthModule
,
WsModule
,
WsModule
,
DeviceModule
,
BroadcastModule
,
BroadcastModule
,
LogConfigModule
,
LogConfigModule
,
FieldsModule
FieldsModule
...
...
src/common/enums/index.ts
View file @
d7c547b
...
@@ -42,17 +42,29 @@ export enum WsAccess {
...
@@ -42,17 +42,29 @@ export enum WsAccess {
InvalidDeviceId
=
'无效设备id'
,
InvalidDeviceId
=
'无效设备id'
,
IsOnline
=
'通过验证,设备上线'
,
IsOnline
=
'通过验证,设备上线'
,
IsOffline
=
'设备下线'
,
IsOffline
=
'设备下线'
,
ConnFailure
=
'设备连接失败,请检查设备号是否正确'
ConnFailure
=
'设备连接失败,请检查设备号是否正确'
,
TokenExpired
=
'token已过期,请重新登录'
}
export
enum
WsAccessCode
{
NotAllowed
=
901
,
InValidToken
=
902
,
InvalidDeviceId
=
903
,
IsOnline
=
904
,
IsOffline
=
905
,
ConnFailure
=
906
,
TokenExpired
=
907
}
}
export
enum
Events
{
export
enum
Events
{
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'
,
OnMessage
=
'client.mesage.received'
,
OnLogFileUploaded
=
'log.file.uploaded'
,
OnLogFileUploaded
=
'log.file.uploaded'
,
OnLogFileRemoved
=
'log.file.removed'
,
OnLogFileRemoved
=
'log.file.removed'
,
OnTaskStart
=
'task.start'
OnTaskStart
=
'task.start'
,
OnSendMessage
=
'client.message.send'
,
}
}
export
enum
DocTypes
{
export
enum
DocTypes
{
Log
=
'log'
,
Log
=
'log'
,
...
@@ -60,18 +72,18 @@ export enum DocTypes {
...
@@ -60,18 +72,18 @@ export enum DocTypes {
Video
=
'video'
,
Video
=
'video'
,
Other
=
'other'
Other
=
'other'
}
}
export
enum
Command
{
export
enum
Command
{
GetLog
=
'getLog'
,
GetLog
=
'getLog'
,
GetStorage
=
'getStorage'
,
GetStorage
=
'getStorage'
,
Message
=
'message'
,
Message
=
'message'
,
GetLogList
=
'getLogList'
,
GetLogList
=
'getLogList'
,
RemoveLog
=
'removeLog'
,
RemoveLog
=
'removeLog'
,
RemoveRecord
=
'removeRecord'
,
RemoveRecord
=
'removeRecord'
,
StopPolling
=
'stopPolling'
,
StopPolling
=
'stopPolling'
,
StartPolling
=
'startPolling'
,
StartPolling
=
'startPolling'
,
SetPollingInterval
=
'setPollingInterval'
SetPollingInterval
=
'setPollingInterval'
}
}
export
enum
LogFieldTypes
{
export
enum
LogFieldTypes
{
User
=
'user'
User
=
'user'
}
}
src/common/pipes/arguments.pipe.ts
View file @
d7c547b
import
{
PipeTransform
,
Injectable
,
ArgumentMetadata
,
BadRequestException
}
from
'@nestjs/common'
import
{
PipeTransform
,
Injectable
,
ArgumentMetadata
,
BadRequestException
}
from
'@nestjs/common'
import
{
Socket
}
from
'socket.io'
@
Injectable
()
@
Injectable
()
export
class
PagesPipe
implements
PipeTransform
<
CommonTypes
.
IPageIn
>
{
export
class
PagesPipe
implements
PipeTransform
<
CommonTypes
.
IPageIn
>
{
...
@@ -56,3 +57,4 @@ export class ParseIdPipe implements PipeTransform<any, any> {
...
@@ -56,3 +57,4 @@ export class ParseIdPipe implements PipeTransform<any, any> {
return
transformedValue
return
transformedValue
}
}
}
}
src/common/pipes/ws.pipe.ts
0 → 100644
View file @
d7c547b
import
{
ArgumentMetadata
,
Injectable
,
PipeTransform
}
from
"@nestjs/common"
import
{
Socket
}
from
"socket.io"
import
{
WsAccess
,
WsAccessCode
}
from
"../enums"
import
{
TokenExpiredError
}
from
"@nestjs/jwt"
@
Injectable
()
export
class
WsConnParamPipe
implements
PipeTransform
<
any
,
any
>
{
transform
(
client
:
Socket
,
metadata
:
ArgumentMetadata
):
any
{
// 创建一个新对象,以避免直接修改原始值
const
transformedValue
=
{
...
client
}
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
}
const
{
token
,
deviceId
}
=
auth
// 注册用户
if
(
!
token
)
{
ValidateData
.
isValidate
=
false
ValidateData
.
errMsg
=
WsAccess
.
InValidToken
ValidateData
.
errorCode
=
WsAccessCode
.
InValidToken
}
if
(
!
deviceId
)
{
ValidateData
.
isValidate
=
false
ValidateData
.
errMsg
=
WsAccess
.
InvalidDeviceId
ValidateData
.
errorCode
=
WsAccessCode
.
InvalidDeviceId
}
return
{
transformedValue
,
ValidateData
}
}
}
\ No newline at end of file
\ No newline at end of file
src/dto/device.dto.ts
View file @
d7c547b
import
{
IsString
,
IsNumber
,
IsNotEmpty
,
MaxLength
,
IsMobilePhone
,
IsOptional
}
from
'class-validator'
import
{
IsString
,
IsNumber
,
IsNotEmpty
,
MaxLength
,
IsMobilePhone
,
IsOptional
,
isNotEmpty
}
from
'class-validator'
import
{
ApiProperty
}
from
'@nestjs/swagger'
import
{
ApiProperty
}
from
'@nestjs/swagger'
import
{
BaseDto
}
from
'./base.dto'
import
{
BaseDto
}
from
'./base.dto'
...
@@ -28,6 +28,26 @@ export class DeviceQueryDto extends BaseDto {
...
@@ -28,6 +28,26 @@ export class DeviceQueryDto extends BaseDto {
mobile
?:
string
mobile
?:
string
}
}
export
class
DeviceFindOneDto
{
@
ApiProperty
({
type
:
String
,
description
:
'设备用户'
,
required
:
true
,
default
:
''
})
@
IsNotEmpty
({
message
:
'用户不能为空'
})
user
:
string
@
ApiProperty
({
type
:
String
,
description
:
'使用者手机号'
,
required
:
true
,
default
:
''
})
@
IsNotEmpty
({
message
:
'手机号不能为空'
})
mobile
:
string
}
export
class
AddDeviceDto
{
export
class
AddDeviceDto
{
@
ApiProperty
({
@
ApiProperty
({
type
:
String
,
type
:
String
,
...
...
src/modules/auth/auth.controller.ts
View file @
d7c547b
import
{
Controller
,
Get
,
Post
,
Request
,
UseGuards
}
from
'@nestjs/common'
;
import
{
Body
,
Controller
,
Get
,
Post
,
Request
,
UseGuards
,
UseInterceptors
,
UsePipes
,
ValidationPipe
}
from
'@nestjs/common'
import
{
AuthGuard
}
from
'@nestjs/passport'
;
import
{
AuthGuard
}
from
'@nestjs/passport'
import
{
AuthService
}
from
'./auth.service'
;
import
{
AuthService
}
from
'./auth.service'
import
{
RESPONSE_CODE
}
from
'../../common/enums'
import
{
ApiTags
}
from
'@nestjs/swagger'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
DeviceFindOneDto
}
from
'src/dto'
@
Controller
()
@
Controller
()
@
ApiTags
(
'权限管理'
)
@
Controller
(
'device'
)
@
UseInterceptors
(
TransformInterceptor
)
@
UsePipes
(
new
ValidationPipe
())
export
class
AuthController
{
export
class
AuthController
{
constructor
(
private
readonly
authService
:
AuthService
)
{}
constructor
(
private
readonly
authService
:
AuthService
)
{}
// 登录测试
// 登录测试
@
UseGuards
(
AuthGuard
(
'local'
))
// @UseGuards(AuthGuard('local'))
@
Post
(
'/auth/login'
)
@
Post
(
'login'
)
async
login
(@
Request
()
req
)
{
async
login
(@
Body
()
user
:
DeviceFindOneDto
):
Promise
<
CommonTypes
.
IResData
>
{
return
this
.
authService
.
login
(
req
.
user
);
const
result
:
CommonTypes
.
IResData
=
await
this
.
authService
.
validateUser
(
user
)
if
(
result
.
code
===
RESPONSE_CODE
.
SUCCESS
)
{
const
token
=
this
.
authService
.
getToken
(
user
)
result
.
data
.
token
=
token
}
return
result
}
}
// 测试登录后才可访问的接口,在需要的地方使用守卫,可保证必须携带token才能访问
// 测试登录后才可访问的接口,在需要的地方使用守卫,可保证必须携带token才能访问
@
UseGuards
(
AuthGuard
(
'jwt'
))
@
UseGuards
(
AuthGuard
(
'jwt'
))
@
Get
(
'me'
)
@
Get
(
'me'
)
getProfile
(@
Request
()
req
)
{
getProfile
(@
Request
()
req
)
{
return
req
.
user
;
return
req
.
user
}
}
}
}
src/modules/auth/auth.module.ts
View file @
d7c547b
import
{
Module
}
from
'@nestjs/common'
;
import
{
Module
}
from
'@nestjs/common'
import
{
AuthService
}
from
'./auth.service'
;
import
{
AuthService
}
from
'./auth.service'
import
{
PassportModule
}
from
'@nestjs/passport'
;
import
{
PassportModule
}
from
'@nestjs/passport'
import
{
JwtModule
}
from
'@nestjs/jwt'
;
import
{
JwtModule
,
JwtService
}
from
'@nestjs/jwt'
// import { UsersModule } from '../users/users.module';
// import { UsersModule } from '../users/users.module';
import
{
AuthController
}
from
'./auth.controller'
;
import
{
AuthController
}
from
'./auth.controller'
import
{
LocalStrategy
}
from
'./local.strategy'
;
import
{
LocalStrategy
}
from
'./local.strategy'
import
{
JwtStrategy
}
from
'./jwt.strategy'
;
import
{
JwtStrategy
}
from
'./jwt.strategy'
import
{
jwtConstants
}
from
'./constants'
;
import
{
jwtConstants
}
from
'./constants'
import
{
PrismaModule
,
PrismaService
}
from
'nestjs-prisma'
import
{
DeviceModule
}
from
'../device/device.module'
@
Module
({
@
Module
({
imports
:
[
imports
:
[
// UsersModule,
PassportModule
.
register
({
defaultStrategy
:
'jwt'
}),
PassportModule
,
JwtModule
.
register
({
JwtModule
.
register
({
secret
:
jwtConstants
.
secret
,
global
:
true
,
signOptions
:
{
expiresIn
:
'60s'
},
secret
:
process
.
env
.
JWT_SECRET
,
signOptions
:
{
expiresIn
:
'24h'
}
}),
}),
PrismaModule
,
DeviceModule
],
],
controllers
:
[
AuthController
],
controllers
:
[
AuthController
],
providers
:
[
AuthService
,
LocalStrategy
,
JwtStrategy
],
providers
:
[
AuthService
,
LocalStrategy
,
JwtStrategy
],
exports
:
[
AuthService
]
,
exports
:
[
AuthService
]
})
})
export
class
AuthModule
{}
export
class
AuthModule
{}
src/modules/auth/auth.service.ts
View file @
d7c547b
import
{
Injectable
}
from
'@nestjs/common'
;
import
{
Inject
,
Injectable
}
from
'@nestjs/common'
import
{
JwtService
}
from
'@nestjs/jwt'
;
import
{
JwtService
,
TokenExpiredError
}
from
'@nestjs/jwt'
import
{
DeviceService
}
from
'../device/device.service'
import
{
DeviceFindOneDto
}
from
'src/dto'
@
Injectable
()
@
Injectable
()
export
class
AuthService
{
export
class
AuthService
{
constructor
(
constructor
(
// private readonly usersService: UsersService,
private
readonly
deviceService
:
DeviceService
,
private
readonly
jwtService
:
JwtService
,
@
Inject
(
JwtService
)
private
readonly
jwtService
:
JwtService
)
{}
)
{}
async
validateUser
(
username
:
string
,
pass
:
string
):
Promise
<
any
>
{
async
validateUser
(
user
:
DeviceFindOneDto
):
Promise
<
CommonTypes
.
IResData
>
{
// const user = await this.usersService.find(username);
return
await
this
.
deviceService
.
findOne
(
user
)
const
user
=
{
name
:
'walker123'
,
password
:
'123321'
};
if
(
user
&&
user
.
password
)
{
const
{
password
,
...
result
}
=
user
;
return
result
;
}
return
null
;
}
}
async
login
(
user
:
any
):
Promise
<
any
>
{
getToken
({
user
,
mobile
}:
DeviceFindOneDto
):
string
{
const
payload
=
{
username
:
user
.
username
,
sub
:
user
.
userId
};
return
this
.
jwtService
.
sign
({
user
,
mobile
})
return
{
}
access_token
:
this
.
jwtService
.
sign
(
payload
),
verifyToken
(
token
:
string
)
{
};
let
res
:
{
isPass
:
boolean
;
error
:
any
;
data
:
any
;
isExpired
:
boolean
}
=
{
isPass
:
true
,
error
:
null
,
data
:
null
,
isExpired
:
false
}
try
{
const
verify
=
this
.
jwtService
.
verify
(
token
)
if
(
verify
)
{
res
.
data
=
verify
}
}
catch
(
error
)
{
res
=
{
isPass
:
false
,
error
,
data
:
null
,
isExpired
:
false
}
if
(
error
instanceof
TokenExpiredError
)
{
res
.
isExpired
=
true
}
}
return
res
}
}
}
}
src/modules/auth/jwt.strategy.ts
View file @
d7c547b
...
@@ -7,7 +7,7 @@ import { jwtConstants } from './constants';
...
@@ -7,7 +7,7 @@ import { jwtConstants } from './constants';
export
class
JwtStrategy
extends
PassportStrategy
(
Strategy
)
{
export
class
JwtStrategy
extends
PassportStrategy
(
Strategy
)
{
constructor
()
{
constructor
()
{
super
({
super
({
jwtFromRequest
:
ExtractJwt
.
fromHeader
(
'token'
),
jwtFromRequest
:
ExtractJwt
.
from
AuthHeaderAsBearerToken
(),
//ExtractJwt.from
Header('token'),
ignoreExpiration
:
false
,
ignoreExpiration
:
false
,
secretOrKey
:
jwtConstants
.
secret
,
secretOrKey
:
jwtConstants
.
secret
,
});
});
...
...
src/modules/auth/local.strategy.ts
View file @
d7c547b
...
@@ -2,6 +2,7 @@ import { Strategy } from 'passport-local';
...
@@ -2,6 +2,7 @@ import { Strategy } from 'passport-local';
import
{
PassportStrategy
}
from
'@nestjs/passport'
;
import
{
PassportStrategy
}
from
'@nestjs/passport'
;
import
{
Injectable
,
HttpException
,
HttpStatus
}
from
'@nestjs/common'
;
import
{
Injectable
,
HttpException
,
HttpStatus
}
from
'@nestjs/common'
;
import
{
AuthService
}
from
'./auth.service'
;
import
{
AuthService
}
from
'./auth.service'
;
import
{
DeviceFindOneDto
}
from
'../../dto'
;
@
Injectable
()
@
Injectable
()
export
class
LocalStrategy
extends
PassportStrategy
(
Strategy
)
{
export
class
LocalStrategy
extends
PassportStrategy
(
Strategy
)
{
...
@@ -9,16 +10,13 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
...
@@ -9,16 +10,13 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
super
();
super
();
}
}
async
validate
(
username
:
string
,
password
:
string
):
Promise
<
any
>
{
async
validate
(
user
:
DeviceFindOneDto
):
Promise
<
any
>
{
// tslint:disable-next-line
const
device
=
await
this
.
authService
.
validateUser
(
user
);
console
.
log
(
username
,
password
)
if
(
!
device
)
{
return
{
username
,
password
};
const
user
=
await
this
.
authService
.
validateUser
(
username
,
password
);
if
(
!
user
)
{
throw
new
HttpException
(
throw
new
HttpException
(
{
message
:
'authorized failed'
,
error
:
'please try again later.'
},
{
message
:
'authorized failed'
,
error
:
'please try again later.'
},
HttpStatus
.
BAD_REQUEST
);
HttpStatus
.
BAD_REQUEST
);
}
}
return
user
;
return
device
;
}
}
}
}
src/modules/broadcast/broadcast.module.ts
View file @
d7c547b
...
@@ -2,11 +2,10 @@ import { Module } from '@nestjs/common'
...
@@ -2,11 +2,10 @@ 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
{
WsModule
}
from
'../ws/ws.module'
;
import
{
WsService
}
from
'../ws/ws.service'
;
import
{
HttpModule
}
from
'@nestjs/axios'
;
import
{
HttpModule
}
from
'@nestjs/axios'
;
@
Module
({
@
Module
({
imports
:
[
WsModule
,
HttpModule
],
imports
:
[
WsModule
,
HttpModule
],
controllers
:
[
BroadcastController
],
controllers
:
[
BroadcastController
],
providers
:
[
BroadcastService
,
WsService
]
providers
:
[
BroadcastService
]
})
})
export
class
BroadcastModule
{}
export
class
BroadcastModule
{}
src/modules/config/config.module.ts
View file @
d7c547b
import
{
Module
}
from
'@nestjs/common'
import
{
Module
}
from
'@nestjs/common'
import
{
ConfigController
}
from
'./config.controller'
import
{
ConfigController
}
from
'./config.controller'
import
{
ConfigService
}
from
'./config.service'
import
{
ConfigService
}
from
'./config.service'
import
{
PrismaService
}
from
'nestjs-prisma'
import
{
Prisma
Module
,
Prisma
Service
}
from
'nestjs-prisma'
@
Module
({
@
Module
({
imports
:
[
PrismaModule
],
controllers
:
[
ConfigController
],
controllers
:
[
ConfigController
],
providers
:
[
ConfigService
,
PrismaService
]
providers
:
[
ConfigService
]
})
})
export
class
LogConfigModule
{}
export
class
LogConfigModule
{}
src/modules/device/device.controller.ts
View file @
d7c547b
import
{
Controller
,
Get
,
Post
,
Body
,
UseInterceptors
,
Query
,
UsePipes
,
Inject
}
from
'@nestjs/common'
import
{
Controller
,
Get
,
Post
,
Body
,
UseInterceptors
,
Query
,
UsePipes
,
Inject
}
from
'@nestjs/common'
import
{
DeviceService
}
from
'./device.service'
import
{
DeviceService
}
from
'./device.service'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
AddDeviceDto
,
AddDeviceInfoDto
,
DeviceQueryDto
,
DeviceStatusDto
}
from
'../../dto'
import
{
AddDeviceDto
,
AddDeviceInfoDto
,
Device
FindOneDto
,
Device
QueryDto
,
DeviceStatusDto
}
from
'../../dto'
import
{
PagesPipe
,
ValidationPipe
}
from
'../../common/pipes'
import
{
PagesPipe
,
ValidationPipe
}
from
'../../common/pipes'
import
{
OnEvent
,
EventEmitter2
}
from
'@nestjs/event-emitter'
import
{
OnEvent
,
EventEmitter2
}
from
'@nestjs/event-emitter'
import
{
WsAccess
,
Events
,
WsMessageType
,
Command
,
RESPONSE_CODE
}
from
'../../common/enums'
import
{
WsAccess
,
Events
,
WsMessageType
,
Command
,
RESPONSE_CODE
}
from
'../../common/enums'
...
@@ -34,10 +34,13 @@ export class DeviceController {
...
@@ -34,10 +34,13 @@ export class DeviceController {
@
Get
()
@
Get
()
@
UsePipes
(
new
PagesPipe
())
@
UsePipes
(
new
PagesPipe
())
@
ApiOperation
({
summary
:
'获取所有设备列表'
})
@
ApiOperation
({
summary
:
'获取所有设备列表'
})
findAll
(@
Query
()
params
:
DeviceQueryDto
):
Promise
<
CommonTypes
.
IResData
>
{
async
findAll
(@
Query
()
params
:
DeviceQueryDto
):
Promise
<
CommonTypes
.
IResData
>
{
return
this
.
deviceService
.
findAll
(
params
)
return
await
this
.
deviceService
.
findAll
(
params
)
}
}
async
finOne
(@
Query
()
params
:
DeviceFindOneDto
):
Promise
<
CommonTypes
.
IResData
>
{
return
await
this
.
deviceService
.
findOne
(
params
)
}
/**
/**
* 添加设备的方法
* 添加设备的方法
* 该方法接收一个包含设备信息的DTO对象,并返回添加后的设备信息
* 该方法接收一个包含设备信息的DTO对象,并返回添加后的设备信息
...
@@ -46,9 +49,9 @@ export class DeviceController {
...
@@ -46,9 +49,9 @@ export class DeviceController {
*/
*/
@
Post
(
'/add'
)
@
Post
(
'/add'
)
@
ApiOperation
({
summary
:
'添加设备'
})
@
ApiOperation
({
summary
:
'添加设备'
})
addDevice
(@
Body
()
param
:
AddDeviceDto
):
Promise
<
CommonTypes
.
IResponseBase
>
{
a
sync
a
ddDevice
(@
Body
()
param
:
AddDeviceDto
):
Promise
<
CommonTypes
.
IResponseBase
>
{
// console.log(param)
// console.log(param)
return
this
.
deviceService
.
addDevice
(
param
)
return
await
this
.
deviceService
.
addDevice
(
param
)
}
}
/**
/**
* 添加设备信息的方法
* 添加设备信息的方法
...
@@ -58,10 +61,11 @@ export class DeviceController {
...
@@ -58,10 +61,11 @@ export class DeviceController {
*/
*/
@
Post
(
'/addInfo'
)
@
Post
(
'/addInfo'
)
@
ApiOperation
({
summary
:
'添加设备信息'
})
@
ApiOperation
({
summary
:
'添加设备信息'
})
addDeviceInfo
(@
Body
()
param
:
AddDeviceInfoDto
):
Promise
<
CommonTypes
.
IResponseBase
>
{
a
sync
a
ddDeviceInfo
(@
Body
()
param
:
AddDeviceInfoDto
):
Promise
<
CommonTypes
.
IResponseBase
>
{
// console.log(param)
// console.log(param)
return
this
.
deviceService
.
addDeviceInfo
(
param
)
return
await
this
.
deviceService
.
addDeviceInfo
(
param
)
}
}
/**
/**
* 更新设备信息的方法
* 更新设备信息的方法
* 该方法接收一个包含设备信息的DTO对象,并返回更新后的设备信息
* 该方法接收一个包含设备信息的DTO对象,并返回更新后的设备信息
...
@@ -71,8 +75,8 @@ export class DeviceController {
...
@@ -71,8 +75,8 @@ export class DeviceController {
@
Post
(
'/updateInfo'
)
@
Post
(
'/updateInfo'
)
@
ApiOperation
({
summary
:
'修改设备信息'
})
@
ApiOperation
({
summary
:
'修改设备信息'
})
@
OnEvent
(
Events
.
OnLogFileRemoved
)
@
OnEvent
(
Events
.
OnLogFileRemoved
)
updateDeviceInfo
(@
Body
()
param
:
AddDeviceInfoDto
):
Promise
<
CommonTypes
.
IResponseBase
>
{
async
updateDeviceInfo
(@
Body
()
param
:
AddDeviceInfoDto
):
Promise
<
CommonTypes
.
IResponseBase
>
{
return
this
.
deviceService
.
updateDeviceInfo
(
param
)
return
await
this
.
deviceService
.
updateDeviceInfo
(
param
)
}
}
/**
/**
...
...
src/modules/device/device.module.ts
View file @
d7c547b
import
{
Module
}
from
'@nestjs/common'
;
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
{
Prisma
Servic
e
}
from
'nestjs-prisma'
;
import
{
Prisma
Modul
e
}
from
'nestjs-prisma'
;
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 { EventEmitter2 } from '@nestjs/event-emitter';
// import { EventEmitter2 } from '@nestjs/event-emitter';
@
Module
({
@
Module
({
imports
:
[
Ws
Module
],
imports
:
[
Prisma
Module
],
controllers
:
[
DeviceController
],
controllers
:
[
DeviceController
],
providers
:
[
DeviceService
,
PrismaService
,
WsService
],
providers
:
[
DeviceService
,
WsService
],
exports
:
[
DeviceService
],
})
})
export
class
DeviceModule
{}
export
class
DeviceModule
{}
src/modules/device/device.service.ts
View file @
d7c547b
...
@@ -4,19 +4,20 @@ import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } f
...
@@ -4,19 +4,20 @@ import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } f
// 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
,
RESPONSE_CODE
,
WsMessageType
,
WsStatus
}
from
'../../common/enums'
import
{
WsGateway
}
from
'../ws/ws.gateway'
import
{
WsService
}
from
'../ws/ws.service'
import
{
EventEmitter2
}
from
'@nestjs/event-emitter'
@
Injectable
()
@
Injectable
()
export
class
DeviceService
implements
OnModuleInit
{
export
class
DeviceService
implements
OnModuleInit
{
constructor
(
constructor
(
@
Inject
(
PrismaService
)
@
Inject
(
PrismaService
)
private
readonly
prisma
:
PrismaService
,
// private connection: Connection,
private
readonly
prisma
:
PrismaService
,
// private connection: Connection,
private
readonly
wsGateway
:
WsGateway
@
Inject
(
EventEmitter2
)
private
readonly
wsService
:
WsService
)
{}
)
{}
async
onModuleInit
()
{
async
onModuleInit
()
{
this
.
resetAllDeviceStatus
()
this
.
resetAllDeviceStatus
()
}
}
async
findAll
({
user
,
mobile
,
sn
,
skip
,
take
}:
DeviceTypes
.
IQueryDevices
):
Promise
<
CommonTypes
.
IResData
<
DeviceTypes
.
IDeviceInfo
[]
>>
{
async
findAll
({
user
,
mobile
,
sn
,
skip
,
take
}:
DeviceTypes
.
IQueryDevices
):
Promise
<
CommonTypes
.
IResData
<
DeviceTypes
.
IDeviceInfo
[]
>>
{
const
where
=
{
const
where
=
{
sn
:
{
sn
:
{
...
@@ -37,7 +38,7 @@ export class DeviceService implements OnModuleInit {
...
@@ -37,7 +38,7 @@ export class DeviceService implements OnModuleInit {
skip
,
skip
,
take
,
take
,
select
:
{
select
:
{
id
:
true
,
id
:
true
,
sn
:
true
,
sn
:
true
,
device_info
:
{
device_info
:
{
select
:
{
select
:
{
...
@@ -52,7 +53,7 @@ export class DeviceService implements OnModuleInit {
...
@@ -52,7 +53,7 @@ export class DeviceService implements OnModuleInit {
field
:
{
field
:
{
select
:
{
select
:
{
name
:
true
,
name
:
true
,
type
:
true
type
:
true
}
}
}
}
}
}
...
@@ -72,14 +73,14 @@ export class DeviceService implements OnModuleInit {
...
@@ -72,14 +73,14 @@ export class DeviceService implements OnModuleInit {
})
})
const
data
:
DeviceTypes
.
IDeviceInfo
[]
=
result
.
reduce
((
pre
:
DeviceTypes
.
IDeviceInfo
[],
cur
:
DeviceTypes
.
IDeviceResult
)
=>
{
const
data
:
DeviceTypes
.
IDeviceInfo
[]
=
result
.
reduce
((
pre
:
DeviceTypes
.
IDeviceInfo
[],
cur
:
DeviceTypes
.
IDeviceResult
)
=>
{
pre
.
push
({
pre
.
push
({
id
:
cur
.
id
,
id
:
cur
.
id
,
sn
:
cur
.
sn
,
sn
:
cur
.
sn
,
user
:
cur
.
device_info
?.
user
,
user
:
cur
.
device_info
?.
user
,
mobile
:
cur
.
device_info
?.
mobile
,
mobile
:
cur
.
device_info
?.
mobile
,
status
:
cur
.
device_info
?.
device_status
?.
status
,
status
:
cur
.
device_info
?.
device_status
?.
status
,
merchant_name
:
cur
.
device_info
?.
merchant_name
,
merchant_name
:
cur
.
device_info
?.
merchant_name
,
log_saved_days
:
cur
.
device_info
?.
log_config
?.
log_saved_days
,
log_saved_days
:
cur
.
device_info
?.
log_config
?.
log_saved_days
,
fields
:
cur
.
device_info
?.
log_config
?.
fields
?.
map
((
item
:
DeviceTypes
.
IFields
)
=>
({
name
:
item
.
field
.
name
,
type
:
item
.
field
.
type
}))
fields
:
cur
.
device_info
?.
log_config
?.
fields
?.
map
((
item
:
DeviceTypes
.
IFields
)
=>
({
name
:
item
.
field
.
name
,
type
:
item
.
field
.
type
}))
})
})
return
pre
return
pre
},
[])
},
[])
...
@@ -87,6 +88,13 @@ export class DeviceService implements OnModuleInit {
...
@@ -87,6 +88,13 @@ export class DeviceService implements OnModuleInit {
return
resBody
return
resBody
}
}
async
findOne
({
user
,
mobile
}:
Pick
<
CommonTypes
.
IUser
,
'mobile'
|
'user'
>
):
Promise
<
CommonTypes
.
IResData
<
DeviceTypes
.
TOneDeviceInfo
>>
{
const
deviceInfo
=
await
this
.
prisma
.
device_info
.
findFirstOrThrow
({
where
:
{
user
,
mobile
}
})
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
data
:
deviceInfo
}
}
async
addDevice
(
device
:
Omit
<
DeviceTypes
.
TDevice
,
'id'
>
):
Promise
<
CommonTypes
.
IResData
>
{
async
addDevice
(
device
:
Omit
<
DeviceTypes
.
TDevice
,
'id'
>
):
Promise
<
CommonTypes
.
IResData
>
{
await
this
.
prisma
.
$transaction
(
async
prisma
=>
{
await
this
.
prisma
.
$transaction
(
async
prisma
=>
{
const
{
id
}
=
await
prisma
.
device
.
create
({
data
:
device
,
select
:
{
id
:
true
}
})
const
{
id
}
=
await
prisma
.
device
.
create
({
data
:
device
,
select
:
{
id
:
true
}
})
...
@@ -167,7 +175,8 @@ export class DeviceService implements OnModuleInit {
...
@@ -167,7 +175,8 @@ export class DeviceService implements OnModuleInit {
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());`
WHERE c.log_saved_days >= TIMESTAMPDIFF(DAY, d.last_log_remove_time, NOW());`
for
(
const
{
device_id
,
log_saved_days
}
of
results
)
{
for
(
const
{
device_id
,
log_saved_days
}
of
results
)
{
await
this
.
wsGateway
.
send
({
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
)
}
}
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'每日日志删除任务完成'
}
return
{
code
:
RESPONSE_CODE
.
SUCCESS
,
message
:
'每日日志删除任务完成'
}
}
}
...
...
src/modules/fields/fields.module.ts
View file @
d7c547b
import
{
Module
}
from
'@nestjs/common'
;
import
{
Module
}
from
'@nestjs/common'
;
import
{
FieldsService
}
from
'./fields.service'
;
import
{
FieldsService
}
from
'./fields.service'
;
import
{
FieldsController
}
from
'./fields.controller'
;
import
{
FieldsController
}
from
'./fields.controller'
;
import
{
PrismaService
}
from
'nestjs-prisma'
;
import
{
Prisma
Module
,
Prisma
Service
}
from
'nestjs-prisma'
;
@
Module
({
@
Module
({
imports
:
[
PrismaModule
],
controllers
:
[
FieldsController
],
controllers
:
[
FieldsController
],
providers
:
[
FieldsService
,
PrismaService
],
providers
:
[
FieldsService
],
})
})
export
class
FieldsModule
{}
export
class
FieldsModule
{}
src/modules/file/file.module.ts
View file @
d7c547b
...
@@ -3,7 +3,7 @@ import { MulterModule } from '@nestjs/platform-express';
...
@@ -3,7 +3,7 @@ import { MulterModule } from '@nestjs/platform-express';
import
{
ConfigService
}
from
'nestjs-config'
;
import
{
ConfigService
}
from
'nestjs-config'
;
import
{
FileController
}
from
'./file.controller'
;
import
{
FileController
}
from
'./file.controller'
;
import
{
FileService
}
from
'./file.service'
;
import
{
FileService
}
from
'./file.service'
;
import
{
PrismaService
}
from
'nestjs-prisma'
;
import
{
Prisma
Module
,
Prisma
Service
}
from
'nestjs-prisma'
;
@
Module
({
@
Module
({
imports
:
[
imports
:
[
...
@@ -11,8 +11,9 @@ import { PrismaService } from 'nestjs-prisma';
...
@@ -11,8 +11,9 @@ import { PrismaService } from 'nestjs-prisma';
useFactory
:
(
config
:
ConfigService
)
=>
config
.
get
(
'file'
),
useFactory
:
(
config
:
ConfigService
)
=>
config
.
get
(
'file'
),
inject
:
[
ConfigService
],
inject
:
[
ConfigService
],
}),
}),
PrismaModule
],
],
controllers
:
[
FileController
],
controllers
:
[
FileController
],
providers
:
[
FileService
,
PrismaService
],
providers
:
[
FileService
],
})
})
export
class
FileModule
{}
export
class
FileModule
{}
src/modules/ws/ws.gateway.ts
View file @
d7c547b
...
@@ -3,9 +3,11 @@ import { from, Observable } from 'rxjs'
...
@@ -3,9 +3,11 @@ 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
{
Logger
,
Module
,
UseInterceptors
}
from
'@nestjs/common'
import
{
Inject
,
Logger
,
Module
,
UseInterceptors
}
from
'@nestjs/common'
import
{
WsMessageType
,
WsStatus
,
WsAccess
,
Command
}
from
'../../common/enums'
import
{
WsMessageType
,
WsStatus
,
WsAccess
,
Command
,
WsAccessCode
}
from
'../../common/enums'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
JwtService
,
TokenExpiredError
}
from
'@nestjs/jwt'
import
{
AuthService
}
from
'../auth/auth.service'
/**
/**
* WebSocket 网关
* WebSocket 网关
...
@@ -25,7 +27,10 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
...
@@ -25,7 +27,10 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
*
*
* @param wsService - 注入的 WebSocket 服务实例,用于处理 WebSocket 相关操作。
* @param wsService - 注入的 WebSocket 服务实例,用于处理 WebSocket 相关操作。
*/
*/
constructor
(
public
readonly
wsService
:
WsService
)
{}
constructor
(
public
readonly
wsService
:
WsService
,
private
readonly
authService
:
AuthService
)
{}
/**
/**
* WebSocket 服务器实例
* WebSocket 服务器实例
*/
*/
...
@@ -56,27 +61,41 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
...
@@ -56,27 +61,41 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* @param client client
* @param client client
* @param args
* @param args
*/
*/
handleConnection
(
client
:
Socket
,
...
args
:
any
[]
):
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
}
const
ValidateData
:
WsTypes
.
LoginValidate
<
WsAccess
>
=
{
isValidate
:
true
,
errMsg
:
WsAccess
.
IsOnline
,
errorCode
:
WsAccessCode
.
IsOnline
}
if
(
!
auth
)
{
if
(
!
auth
)
{
ValidateData
.
isValidate
=
false
ValidateData
.
isValidate
=
false
ValidateData
.
errMsg
=
WsAccess
.
NotAllowed
ValidateData
.
errMsg
=
WsAccess
.
NotAllowed
ValidateData
.
errorCode
=
WsAccessCode
.
NotAllowed
}
}
const
{
token
,
deviceId
}
=
auth
const
{
token
,
deviceId
}
=
auth
// 注册用户
// 注册用户
if
(
!
token
)
{
if
(
!
token
)
{
ValidateData
.
isValidate
=
false
ValidateData
.
isValidate
=
false
ValidateData
.
errMsg
=
WsAccess
.
InValidToken
ValidateData
.
errMsg
=
WsAccess
.
InValidToken
ValidateData
.
errorCode
=
WsAccessCode
.
InValidToken
}
}
if
(
!
deviceId
)
{
if
(
!
deviceId
)
{
ValidateData
.
isValidate
=
false
ValidateData
.
isValidate
=
false
ValidateData
.
errMsg
=
WsAccess
.
InvalidDeviceId
ValidateData
.
errMsg
=
WsAccess
.
InvalidDeviceId
ValidateData
.
errorCode
=
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
)
{
if
(
!
ValidateData
.
isValidate
)
{
const
msg
=
`
${
ValidateData
.
errMsg
}
token->
${
token
}
deviceId->
${
deviceId
}
}`
const
msg
=
`
${
ValidateData
.
errMsg
}
token->
${
token
}
deviceId->
${
deviceId
}
}`
client
.
emit
(
WsMessageType
.
Private
,
msg
)
Logger
.
error
(
msg
)
Logger
.
error
(
msg
)
client
.
emit
(
WsMessageType
.
Private
,
ValidateData
)
const
resData
:
WsTypes
.
IWsResponse
<
WsStatus
,
WsAccess
>
=
{
const
resData
:
WsTypes
.
IWsResponse
<
WsStatus
,
WsAccess
>
=
{
status
:
WsStatus
.
Offline
,
status
:
WsStatus
.
Offline
,
message
:
ValidateData
.
errMsg
,
message
:
ValidateData
.
errMsg
,
...
@@ -113,6 +132,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
...
@@ -113,6 +132,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
* 发送消息
* 发送消息
* @param payload
* @param payload
*/
*/
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
)
}
}
...
...
src/modules/ws/ws.module.ts
View file @
d7c547b
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
{
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'
// import { DeviceService } from '../device/device.service'
@
Module
({
@
Module
({
imports
:
[],
imports
:
[
AuthModule
],
providers
:
[
WsGateway
,
WsService
],
providers
:
[
WsGateway
,
WsService
],
exports
:
[
WsGateway
]
exports
:
[
WsGateway
]
})
})
...
...
src/tasks/tasks.service.ts
View file @
d7c547b
import
{
Inject
,
Injectable
,
Logger
}
from
'@nestjs/common'
;
import
{
Inject
,
Injectable
,
Logger
}
from
'@nestjs/common'
import
{
Cron
,
Interval
,
Timeout
}
from
'@nestjs/schedule'
;
import
{
Cron
,
Interval
,
Timeout
}
from
'@nestjs/schedule'
import
{
EventEmitter2
}
from
'@nestjs/event-emitter'
;
import
{
EventEmitter2
}
from
'@nestjs/event-emitter'
import
{
Events
}
from
'../common/enums'
;
import
{
Events
}
from
'../common/enums'
@
Injectable
()
@
Injectable
()
export
class
TasksService
{
export
class
TasksService
{
private
readonly
logger
=
new
Logger
(
TasksService
.
name
)
;
private
readonly
logger
=
new
Logger
(
TasksService
.
name
)
constructor
(
constructor
(
@
Inject
(
EventEmitter2
)
@
Inject
(
EventEmitter2
)
private
eventEmitter
:
EventEmitter2
private
eventEmitter
:
EventEmitter2
){}
)
{}
@
Cron
(
'0 10
*
* * *'
)
@
Cron
(
'0 10
0
* * *'
)
handleCron
()
{
handleCron
()
{
this
.
eventEmitter
.
emit
(
Events
.
OnTaskStart
)
this
.
eventEmitter
.
emit
(
Events
.
OnTaskStart
)
Logger
.
warn
(
'============开始
定时任务============='
);
Logger
.
warn
(
'============开始
每日定时任务============='
)
}
}
// @Interval(5000)
// @Interval(5000)
// handleInterval() {
// handleInterval() {
// }
// }
// @Timeout(5000)
// @Timeout(5000)
...
...
src/typings/device.d.ts
View file @
d7c547b
...
@@ -42,10 +42,13 @@ declare namespace DeviceTypes {
...
@@ -42,10 +42,13 @@ declare namespace DeviceTypes {
}
}
*/
*/
interface
IDeviceInfoInput
extends
IDeviceInfoBase
,
CommonTypes
.
IId
,
CommonTypes
.
IDeviceId
,
CommonTypes
.
ITime
{
interface
IDeviceInfoInput
extends
IDeviceInfoBase
,
CommonTypes
.
IId
,
CommonTypes
.
IDeviceId
,
CommonTypes
.
ITime
{
last_log_upload_time
?:
string
last_log_upload_time
?:
string
|
Date
last_log_remove_time
?:
string
last_log_remove_time
?:
string
|
Date
}
}
type
TOneDeviceInfo
=
Omit
<
IDeviceInfoInput
,
'sn'
>
type
UpdateDeviceInfo
=
CommonTypes
.
Optional
<
IDeviceInfoInput
,
'device_id'
>
type
UpdateDeviceInfo
=
CommonTypes
.
Optional
<
IDeviceInfoInput
,
'device_id'
>
/**
/**
* 表示设备结果的接口
* 表示设备结果的接口
...
...
src/typings/ws.d.ts
View file @
d7c547b
...
@@ -18,7 +18,8 @@ declare namespace WsTypes {
...
@@ -18,7 +18,8 @@ declare namespace WsTypes {
status
:
T
status
:
T
message
:
U
message
:
U
}
}
type
LoginValidate
<
T
>
=
{
isValidate
:
boolean
;
errMsg
:
T
}
type
LoginValidate
<
T
>
=
{
isValidate
:
boolean
;
errMsg
:
T
,
errorCode
:
number
}
type
MessageData
<
T
>
=
{
type
MessageData
<
T
>
=
{
command
:
T
command
:
T
days
?:
number
days
?:
number
...
...
test.http
View file @
d7c547b
...
@@ -39,7 +39,7 @@ POST http://localhost:3000/broadcast/cmd HTTP/1.1
...
@@ -39,7 +39,7 @@ POST http://localhost:3000/broadcast/cmd HTTP/1.1
{
{
"event":"private",
"event":"private",
"device_id":"10000
0
0",
"device_id":"10000
2
0",
"data":{
"data":{
"command":"stopPolling",
"command":"stopPolling",
"interval":1000,
"interval":1000,
...
...
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