Commit 31ca4c8e by yixinjj

新增文件上传指令响应

1 parent 85d8752f
import { resolve } from 'path'
import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
import { ScheduleModule } from '@nestjs/schedule'
import { ConfigModule, ConfigService } from 'nestjs-config'
import { MailerModule } from '@nest-modules/mailer'
import { StatusMonitorModule } from 'nest-status-monitor'
import statusMonitorConfig from './config/statusMonitor'
import { LoggerMiddleware } from './common/middleware/logger.middleware'
import { TasksModule } from './tasks/tasks.module'
import { AudioModule } from './jobs/audio/audio.module'
import { AuthModule } from './modules/auth/auth.module'
import { HelloModule } from './modules/hello/hello.module'
// import { TasksModule } from './tasks/tasks.module'
// import { AudioModule } from './jobs/audio/audio.module'
// import { AuthModule } from './modules/auth/auth.module'
// import { HelloModule } from './modules/hello/hello.module'
import { DeviceModule } from './modules/device/device.module'
import { ExceptionModule } from './modules/exception/exception.module'
import { RoleGuardModule } from './modules/role-guard/role-guard.module'
import { EmailModule } from './modules/email/email.module'
// import { RoleGuardModule } from './modules/role-guard/role-guard.module'
// import { EmailModule } from './modules/email/email.module'
// import { UsersModule } from './modules/users/users.module'
import { FileModule } from './modules/file/file.module'
import { WsModule } from './modules/ws/ws.module'
// import { WsGateway } from './modules/ws/ws.gateway';
import { SseModule } from './modules/sse/sse.module'
import { LogConfigModule } from './modules/config/config.module';
// import { SseModule } from './modules/sse/sse.module'
import { LogConfigModule } from './modules/config/config.module'
import { BroadcastModule } from './modules/broadcast/broadcast.module'
import { EventEmitterModule } from '@nestjs/event-emitter';
import { EventEmitterModule } from '@nestjs/event-emitter'
@Module({
imports: [
ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')),
......@@ -40,26 +39,23 @@ import { EventEmitterModule } from '@nestjs/event-emitter';
EventEmitterModule.forRoot(),
// TasksModule,
// AudioModule,
AuthModule,
HelloModule,
// AuthModule,
// HelloModule,
ExceptionModule,
RoleGuardModule,
EmailModule,
// RoleGuardModule,
// EmailModule,
// UsersModule,
FileModule,
SseModule,
// SseModule,
WsModule,
DeviceModule,
BroadcastModule,
LogConfigModule
],
]
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
// 为 hello 路由添加中间件
consumer
.apply(LoggerMiddleware)
.exclude({ path: 'hello', method: RequestMethod.POST })
.forRoutes('hello')
consumer.apply(LoggerMiddleware).exclude({ path: 'hello', method: RequestMethod.POST }).forRoutes('hello')
}
}
......@@ -41,9 +41,9 @@ export enum WsAccess {
InValidToken = '无效token',
InvalidDeviceId = '无效设备id',
IsOnline = '通过验证,设备上线',
IsOffline = '设备下线',
IsOffline = '设备下线'
}
export enum WsConnEvents {
Connection='connection',
export enum WsConnEvents {
Connection = 'connection'
}
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common'
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common'
import { Response, Request } from 'express'
import { BodyResponse } from '../utils'
......@@ -11,7 +11,9 @@ export class ExceptionsFilter implements ExceptionFilter {
// 获取响应体
const response = ctx.getResponse<Response>()
const request = ctx.getRequest<Request>()
console.log(1,exception)
Logger.error(exception)
console.log(exception)
// 获取状态码,判断是HTTP异常还是服务器异常
const statusCode = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR
const msg = exception instanceof HttpException? exception.message : '服务器异常'
......
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common'
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, Logger } from '@nestjs/common'
import { Request, Response } from 'express'
import { BodyResponse } from '../utils'
@Catch(HttpException)
......@@ -8,7 +8,8 @@ export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
const response = ctx.getResponse<Response>()
const request = ctx.getRequest<Request>()
const status = exception.getStatus()
console.log(2,exception)
Logger.error(exception)
console.log(exception)
const exceptionRes: any = exception.getResponse()
const { message } = exceptionRes
......
import { ArgumentsHost, Catch, ExceptionFilter,HttpStatus } from '@nestjs/common'
import { ArgumentsHost, Catch, ExceptionFilter,HttpStatus, Logger } from '@nestjs/common'
import { ValidationError } from 'class-validator';
import { Request, Response } from 'express'
import { BodyResponse } from '../utils'
......@@ -8,7 +8,7 @@ export class ValidateExceptionFilter implements ExceptionFilter<ValidationError>
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const status = HttpStatus.BAD_REQUEST;
console.log(1,exception)
Logger.error(exception)
// response
// .status(status)
// .json({
......
import { ArgumentMetadata,BadRequestException, HttpException, HttpStatus, Injectable, PipeTransform, Type } from '@nestjs/common'
import { ArgumentMetadata,BadRequestException, HttpException, HttpStatus, Injectable, Logger, PipeTransform, Type } from '@nestjs/common'
import { plainToClass } from 'class-transformer'
import { validate } from 'class-validator'
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, metadata: ArgumentMetadata) {
console.log(value)
const { metatype } = metadata
if (!metatype || !this.toValidate(metatype)) {
return value
}
const object = plainToClass(metatype, value)
const errors = await validate(object)
let errors = await validate(object)
if (errors.length > 0) {
if(!errors[0].constraints && errors[0].children?.length){
errors = errors[0].children
}
const msg = Object.values(errors[0]?.constraints)[0]; // 只需要取第一个错误信息并返回即可
// Logger.error(`Validation failed: ${msg}`);
Logger.error(`Validation failed: ${msg}`);
throw new BadRequestException(`参数验证失败: ${msg}`);
// const errObj = {}
// errors.forEach(err => {
......
......@@ -6,9 +6,10 @@ export default {
storage: diskStorage({
destination: join(__dirname, `../uploads/${new Date().toLocaleDateString()}`),
filename: (req, file, cb) => {
const deviceId = req.body.deviceId;
// const name=file.originalname.split('.');
// const filename = `${name[0]}-${new Date().getTime()}.${name.pop()}`//${file.mimetype.split('/')[1]}`;
const path = `${file.originalname.split('.').shift()}-${Date.now()}-${Math.round(Math.random() * 1e10)}${extname(file.originalname)}`
const path = `${file.originalname.split('.').shift()}@${deviceId}@${Date.now()}-${Math.round(Math.random() * 1e10)}${extname(file.originalname)}`
return cb(null, path);
},
}),
......
import { ApiProperty } from '@nestjs/swagger'
import { WsMessageType } from '../common/enums'
import { IsDefined, IsNotEmpty, IsNumber, IsString, ValidateIf, ValidateNested } from 'class-validator'
import { Type } from 'class-transformer'
class DataDto {
@ApiProperty({
type: String,
description: '命令类型'
})
@IsString({ message: '命令为必填参数' })
@IsNotEmpty({ message: '命令不能为空' })
readonly order: string
@ApiProperty({
description: '下发的参数',
})
readonly payload: any
}
export class BroadcastDto {
@ApiProperty({
type: WsMessageType,
description: '事件类型: private-私有消息,system-系统消息',
default: WsMessageType.Private
})
@IsNotEmpty({ message: '事件类型不能为空' })
readonly event: WsMessageType
@ValidateIf(o => o.event === WsMessageType.Private)
@IsDefined({ message: '发送私有消息时,device_id是必填的' })
@IsNumber({},{ message: 'device_id必须是数字'})
@ApiProperty({
type: Number,
description: '设备号,私发信息必填',
default: ''
})
readonly device_id: number
@IsNotEmpty({ message: '消息不能为空' })
@ApiProperty({ description: '要发送的数据' })
@ValidateNested()
@Type(() => DataDto)
readonly data: DataDto
}
export * from './broadcast.dto'
export * from './config.dto'
export * from './device.dto'
export * from './response.dto'
import { Controller,Post,Body ,UseInterceptors} from '@nestjs/common'
import { Controller, Post, Body, UseInterceptors, UsePipes } from '@nestjs/common'
import { BroadcastService } from './broadcast.service'
import { TransformInterceptor } from '../../common/interceptors'
import { WsGateway } from '../ws/ws.gateway';
import { WsGateway } from '../ws/ws.gateway'
import { BroadcastDto } from '../../dto'
import { ValidationPipe } from '../../common/pipes'
@Controller('broadcast')
@UseInterceptors(TransformInterceptor)
@UsePipes(new ValidationPipe()) // 使用管道验证
export class BroadcastController {
constructor(private readonly broadcastService: BroadcastService,
constructor(
private readonly broadcastService: BroadcastService,
private readonly wsGateway: WsGateway
){}
) {}
//写一个message方法 接收params参数 然后调用broadcastService的message方法
@Post('/message')
async message(@Body() params):Promise<any>{
async message(@Body() params: BroadcastDto): Promise<any> {
return this.wsGateway.send(params)
}
}
import { Controller, Get, Post, Body, UseInterceptors, Query, UsePipes } from '@nestjs/common'
import { DeviceService } from './device.service'
import { TransformInterceptor } from '../../common/interceptors'
import { AddDeviceDto, AddDeviceInfoDto } from '../../dto/device.dto'
import { AddDeviceDto, AddDeviceInfoDto } from '../../dto'
import { PagesPipe, ValidationPipe } from '../../common/pipes'
import { OnEvent } from '@nestjs/event-emitter'
import { WsConnEvents } from '../../common/enums'
......
import { Controller, Post, UploadedFile, UseInterceptors, Get, Res } from '@nestjs/common'
import { Response } from 'express'
import { Controller, Post, UploadedFile, UseInterceptors, Get, Res, Req } from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import { FileService } from './file.service'
import { Response, Request } from 'express'
import { FileMimeTypeFilter } from '../../common/filters'
import { UploadFile } from '../../common/decorators'
......@@ -10,9 +10,9 @@ export class FileController {
constructor(private readonly fileService: FileService) {}
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
@UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain') })
upload(@UploadedFile() file: Express.Multer.File) {
@UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain'), limits: { fileSize: 1024 * 1024 * 100 } })
upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request) {
console.log(req.body.deviceId)
this.fileService.upload(file)
return file
}
......
import { Injectable } from '@nestjs/common';
import { tar } from 'compressing';
import { ConfigService } from 'nestjs-config';
import * as fs from 'fs';
import * as path from 'path';
@Injectable()
export class FileService {
......@@ -16,4 +18,14 @@ export class FileService {
await tarStream.addEntry(uploadDir);
return { filename: 'hello-world.tar', tarStream };
}
moveFile(sourcePath: string, destinationPath: string): Promise<void> {
return new Promise((resolve, reject) => {
const rs = fs.createReadStream(sourcePath);
const ws = fs.createWriteStream(destinationPath);
rs.on('error', reject);
ws.on('error', reject);
ws.on('finish', resolve);
rs.pipe(ws);
});
}
}
......@@ -110,7 +110,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
this.wsService.resetClients()
}
public send(payload: WsTypes.MessageBody): Promise<any> {
public send(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>,WsMessageType>): Promise<any> {
if (payload.event === WsMessageType.Private) {
return this.wsService.sendPrivateMessage(payload)
} else {
......
......@@ -76,7 +76,7 @@ export class WsService {
* @param messagePath 发布地址
* @param response 响应数据
*/
async sendPublicMessage(payload: WsTypes.MessageBody) {
async sendPublicMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>) {
console.log('websocket send', payload)
const res = this.server?.emit(WsMessageType.System, payload.data)
if (!res) {
......@@ -91,14 +91,14 @@ export class WsService {
* @param response 响应数据
* @param deviceId 接收者设备号
*/
async sendPrivateMessage(payload: WsTypes.MessageBody) {
async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>) {
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.server.sockets.sockets.get(this.clientIds.get(payload.device_id))
const res = client?.emit(WsMessageType.Private, payload.data)
if (!res) {
Logger.log('websocket send error', payload)
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败,客户端:${payload.device_id}不在线`, error: 'send error' }, HttpStatus.BAD_REQUEST)
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败,客户端:(设备号->${payload.device_id}) 不在线`, error: 'send error' }, HttpStatus.BAD_REQUEST)
}
}
}
/**
* 公共命名空间声明
*/
declare module CommonTypes {
/**
* 公共命名空间声明
* 定义一个基本的响应对象接口
*/
declare module CommonTypes{
type IResponseBase = {
/**
* 定义一个基本的响应对象接口
* 状态码
*/
type IResponseBase = {
/**
* 状态码
*/
code?: number
/**
* 响应信息
*/
msg?: string | string[]
code?: number
/**
* 响应信息
*/
msg?: string | string[]
/**
* 请求接口路径
*/
url?: string ,
error?: any,
/**
* 时间戳
*/
timestamp?: number
}
/**
* 定义一个基本的分页对象接口
* 请求接口路径
*/
interface IPageBase {
/**
* 页码
*/
pageIndex?: number
/**
* 当前页条数
*/
pageSize?: number
}
url?: string
error?: any
/**
* 扩展分页对象接口,包括总条数
* 时间戳
*/
interface IPagenation extends IPageBase {
/**
* 总条数
*/
total?: number
}
timestamp?: number
}
/**
* 定义一个基本的分页对象接口
*/
interface IPageBase {
/**
* 响应数据接口,继承自分页对象接口,包含业务数据
* 页码
*/
interface IResData<T = any> extends IPageBase {
/**
* 业务数据
*/
data?: T
/**
* 总条数
*/
total?: number
}
pageIndex?: number
/**
* 全局响应体接口,继承自分页对象、响应基本对象和响应数据接口
* 当前页条数
*/
interface IResponse<T> extends IPagenation, IResponseBase {
/**
* 业务数据
*/
data?: T
}
pageSize?: number
}
/**
* 扩展分页对象接口,包括总条数
*/
interface IPagenation extends IPageBase {
/**
* 扩展分页对象接口,用于传入查询参数,包含附加属性
* 总条数
*/
interface IPageIn extends IPageBase {
[key: string]: any
}
total?: number
}
/**
* 响应数据接口,继承自分页对象接口,包含业务数据
*/
interface IResData<T = any> extends IPageBase {
/**
* 定义一个基本的查询对象接口
* 业务数据
*/
interface IQueryBase {
/**
* 跳过数量
*/
skip?: number
/**
* 获取数量
*/
take?: number
}
data?: T
/**
* 定义一个响应体生成函数类型
*
* @param result - 响应数据
* @param msg - 消息
* @param code - 状态码
* @param url - 路径
* @returns 返回给前端的响应体
* 总条数
*/
type TBodyResponse = (result: IResData, msg?: 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>>
total?: number
}
/**
* 全局响应体接口,继承自分页对象、响应基本对象和响应数据接口
*/
interface IResponse<T> extends IPagenation, IResponseBase {
/**
* 业务数据
*/
data?: T
}
/**
* 扩展分页对象接口,用于传入查询参数,包含附加属性
*/
// interface IPageIn extends IPageBase {
// [key: string]: any
// }
type IPageIn = IPageBase & TObj
/**
* 定义一个基本的查询对象接口
*/
interface IQueryBase {
/**
* 跳过数量
*/
skip?: number
/**
* 获取数量
*/
take?: number
}
/**
* 定义一个响应体生成函数类型
*
* @param result - 响应数据
* @param msg - 消息
* @param code - 状态码
* @param url - 路径
* @returns 返回给前端的响应体
*/
type TBodyResponse = (result: IResData, msg?: 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 TObj = { [key: string]: any }
}
......@@ -6,9 +6,9 @@ declare module WsTypes {
}
type WsMsgType = 'private' | 'system'
type MessageBody<T = WsMsgType> = {
type MessageBody<U,T = WsMsgType> = {
event: T
data: any
data: U
} & (T extends 'private' ? IPrivateData : Partial<IPrivateData>)
interface IPrivateData {
......@@ -26,4 +26,10 @@ declare module WsTypes {
message: U
}
type LoginValidate<T> = { isValidate: boolean; errMsg: T }
type MessageData<T, U = CommonTypes.TObj> = {
order: T | string
payload: U
}
type WsMessageData<T> = MessageData<T>
}
......@@ -27,15 +27,16 @@
// eventSource.onmessage = ({ data }) => {
// console.log(111,data)
// };
// const fileInput = document.querySelector('#fileInput');
// // const chunkSize = 20 * 1024;
// fileInput.onchange = async function () {
const fileInput = document.querySelector('#fileInput');
// const chunkSize = 20 * 1024;
fileInput.onchange = async function () {
// const file = fileInput.files[0];
// console.log(file);
// const data = new FormData();
// data.append('file', file);
// axios.post('http://localhost:3000/file/upload', data);
const file = fileInput.files[0];
console.log(file);
const data = new FormData();
data.append('file', file);
axios.post('http://localhost:3000/file/upload', data);
}
// const chunks = [];
// let startPos = 0;
// while(startPos < file.size) {
......@@ -52,26 +53,26 @@
// }
const socket = io('http://192.168.1.129:8080', {
auth: { token: '123456', deviceId: 12 },
});
socket.on('connect', function () {
console.log('Connected');
console.log(socket)
//socket.emit('private', { test: 'test' });
// socket.emit('system', 0, response =>
// console.log('Identity:', response),
// );
});
socket.on('private', function (data) {
console.log('event', data);
});
socket.on('system', function (data) {
console.log('消息', data);
});
socket.on('disconnect', function () {
console.log('Disconnected');
});
// const socket = io('http://192.168.1.129:8080', {
// auth: { token: '123456', deviceId: 12 },
// });
// socket.on('connect', function () {
// console.log('Connected');
// console.log(socket)
// //socket.emit('private', { test: 'test' });
// // socket.emit('system', 0, response =>
// // console.log('Identity:', response),
// // );
// });
// socket.on('private', function (data) {
// console.log('event', data);
// });
// socket.on('system', function (data) {
// console.log('消息', data);
// });
// socket.on('disconnect', function () {
// console.log('Disconnected');
// });
</script>
</body>
......
......@@ -21,23 +21,26 @@
# POST http://localhost:3000/broadcast/message HTTP/1.1
# content-type: application/json
# {
# "event":"private",
# "device_id":1,
# "data":{
# "message":"hello limin"
# }
# }
POST http://localhost:3000/broadcast/message HTTP/1.1
content-type: application/json
{
"event":"private",
"device_id":12,
"data":{
"order":"logs",
"payload":{
"message":"log message"
}
}
}
# 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]
# }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!