Commit c1df7f76 by yixinjj

处理文件路径

1 parent 6f0cee25
import { PipeTransform, Injectable } from '@nestjs/common' import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'
@Injectable() @Injectable()
export class PagesPipe implements PipeTransform<CommonTypes.IPageIn> { export class PagesPipe implements PipeTransform<CommonTypes.IPageIn> {
async transform(value: CommonTypes.IPageIn) { async transform(value: CommonTypes.IPageIn) {
const { pageIndex=1, pageSize =10 } = value const { pageIndex = 1, pageSize = 10 } = value
const skip = (pageIndex - 1) * pageSize const skip = (pageIndex - 1) * pageSize
value.skip = +skip < 0 ? 0 : skip value.skip = +skip < 0 ? 0 : skip
value.take = +pageSize value.take = +pageSize
return value return value
} }
} }
@Injectable()
export class FilePathPipe implements PipeTransform<Express.Multer.File> {
async transform(file: Express.Multer.File) {
file.path = file.path.split(process.env.STATIC_PATH).pop().replace(/\\/g, '/')
return file
}
}
@Injectable()
export class ParseDeviceIdPipe implements PipeTransform<any, any> {
transform(value: any, metadata: ArgumentMetadata): any {
// 创建一个新对象,以避免直接修改原始值
const transformedValue = { ...value }
// 检查 device_id 是否存在并且是字符串类型
if (typeof transformedValue.device_id === 'string') {
const deviceId = parseInt(transformedValue.device_id, 10)
// 检查转换后的值是否是有效的数字
if (isNaN(deviceId)) {
throw new BadRequestException('device_id must be a valid number')
}
// 更新 device_id 字段为数字类型
transformedValue.device_id = deviceId
}
// 返回转换后的值,其中 device_id 是数字类型,其他字段保持不变
return transformedValue
}
}
@Injectable()
export class ParseIdPipe implements PipeTransform<any, any> {
transform(value: any, metadata: ArgumentMetadata): any {
// 创建一个新对象,以避免直接修改原始值
const transformedValue = { ...value }
// 检查 id 是否存在并且是字符串类型
if (typeof transformedValue.id === 'string') {
const id = parseInt(transformedValue.id, 10)
// 检查转换后的值是否是有效的数字
if (isNaN(id)) {
throw new BadRequestException('id must be a valid number')
}
// 更新 id 字段为数字类型
transformedValue.id = id
}
// 返回转换后的值,其中 id 是数字类型,其他字段保持不变
return transformedValue
}
}
...@@ -2,7 +2,7 @@ import { Controller, Post, Body, UseInterceptors, Get, UsePipes, Param, Query } ...@@ -2,7 +2,7 @@ import { Controller, Post, Body, UseInterceptors, Get, UsePipes, Param, Query }
import { ConfigService } from './config.service' import { ConfigService } from './config.service'
import { TransformInterceptor } from '../../common/interceptors' import { TransformInterceptor } from '../../common/interceptors'
import { LogConfigDto } from '../../dto/config.dto' import { LogConfigDto } from '../../dto/config.dto'
import { PagesPipe, ValidationPipe } from '../../common/pipes' import { PagesPipe, ParseDeviceIdPipe, ValidationPipe } from '../../common/pipes'
import { ApiOperation, ApiTags } from '@nestjs/swagger' import { ApiOperation, ApiTags } from '@nestjs/swagger'
@ApiTags('设备配置信息') @ApiTags('设备配置信息')
...@@ -14,6 +14,7 @@ export class ConfigController { ...@@ -14,6 +14,7 @@ export class ConfigController {
@Get() @Get()
@UsePipes(new PagesPipe()) @UsePipes(new PagesPipe())
@UsePipes(new ParseDeviceIdPipe())
@ApiOperation({ summary: '根据设备号获取配置' }) @ApiOperation({ summary: '根据设备号获取配置' })
async findAll(@Query() params: LogConfigDto): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> { async findAll(@Query() params: LogConfigDto): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> {
return this.configService.findAll(params) return this.configService.findAll(params)
......
...@@ -9,7 +9,7 @@ export class ConfigService { ...@@ -9,7 +9,7 @@ export class ConfigService {
) {} ) {}
async findAll({ device_id, skip, take }: ConfigTypes.LogConfigQuery): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> { async findAll({ device_id, skip, take }: ConfigTypes.LogConfigQuery): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> {
const where: any = { const where: any = {
device_id: +device_id device_id
} }
const result: ConfigTypes.LogConfigResult[] = await this.prisma.log_config.findMany({ const result: ConfigTypes.LogConfigResult[] = await this.prisma.log_config.findMany({
skip, skip,
......
...@@ -98,14 +98,15 @@ export class DeviceController { ...@@ -98,14 +98,15 @@ export class DeviceController {
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象 * @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/ */
@Post('/offlineAll') @Post('/offlineAll')
@ApiOperation({ summary: '修改所有设备状态为离线' })
@OnEvent(Events.OnOfflineAll) @OnEvent(Events.OnOfflineAll)
@ApiOperation({ summary: '修改所有设备状态为离线' })
async resetAllDeviceStatus(): Promise<void | CommonTypes.IResponseBase> { async resetAllDeviceStatus(): Promise<void | CommonTypes.IResponseBase> {
return await this.deviceService.resetAllDeviceStatus() return await this.deviceService.resetAllDeviceStatus()
} }
@Get('/task') @Get('/task')
@OnEvent(Events.OnTaskStart) @OnEvent(Events.OnTaskStart)
@ApiOperation({ summary: '日任务' })
async task(): Promise<void | CommonTypes.IResData> { async task(): Promise<void | CommonTypes.IResData> {
return await this.deviceService.removeFilesTask() return await this.deviceService.removeFilesTask()
} }
......
...@@ -7,7 +7,7 @@ import { UploadFile } from '../../common/decorators' ...@@ -7,7 +7,7 @@ import { UploadFile } from '../../common/decorators'
import { DocTypes } from '../../common/enums' import { DocTypes } from '../../common/enums'
import { FileDeleteDto, FileQueryDto } from '../../dto' import { FileDeleteDto, FileQueryDto } from '../../dto'
import { ApiOperation, ApiTags } from '@nestjs/swagger' import { ApiOperation, ApiTags } from '@nestjs/swagger'
import { PagesPipe } from '../../common/pipes' import { FilePathPipe, PagesPipe, ParseDeviceIdPipe, ParseIdPipe } from '../../common/pipes'
@ApiTags('文件管理') @ApiTags('文件管理')
@UsePipes(new ValidationPipe()) @UsePipes(new ValidationPipe())
@Controller('file') @Controller('file')
...@@ -27,12 +27,13 @@ export class FileController { ...@@ -27,12 +27,13 @@ export class FileController {
* @returns 返回上传的文件对象 * @returns 返回上传的文件对象
*/ */
@Post('upload') @Post('upload')
@UsePipes(new FilePathPipe())
@ApiOperation({ summary: '文件上传' }) @ApiOperation({ summary: '文件上传' })
@UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain'), limits: { fileSize: 1024 * 1024 * 100 } }) @UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain'), limits: { fileSize: 1024 * 1024 * 100 } })
upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request): FileTypes.FileUpload<DocTypes> { upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request): FileTypes.FileUpload<DocTypes> {
const { fieldname, encoding, destination, stream, buffer, ...o } = file const { fieldname, encoding, destination, stream, buffer, path, ...o } = file
const bodyData: Pick<FileTypes.FileUpload<DocTypes>, 'device_id' | 'type'> = { device_id: Number(req.body.deviceId), type: req.body.type } const bodyData: Pick<FileTypes.FileUpload<DocTypes>, 'device_id' | 'type'> = { device_id: Number(req.body.deviceId), type: req.body.type }
const f: FileTypes.FileUpload<DocTypes> = Object.assign({ created_at: new Date() }, bodyData, o) const f: FileTypes.FileUpload<DocTypes> = Object.assign({ created_at: new Date(), path: `${req.protocol}://${req.get('Host')}${path}` }, bodyData, o)
this.fileService.save(f) this.fileService.save(f)
return f return f
} }
...@@ -44,8 +45,9 @@ export class FileController { ...@@ -44,8 +45,9 @@ export class FileController {
* @returns 返回该设备下所有指定类型的文件 * @returns 返回该设备下所有指定类型的文件
*/ */
@Get('list') @Get('list')
@ApiOperation({ summary: '获取文件列表' })
@UsePipes(new PagesPipe()) @UsePipes(new PagesPipe())
@UsePipes(new ParseDeviceIdPipe())
@ApiOperation({ summary: '获取文件列表' })
async findAll(@Query() params: FileQueryDto): Promise<CommonTypes.IResData<FileTypes.IFile<DocTypes | string>[]>> { async findAll(@Query() params: FileQueryDto): Promise<CommonTypes.IResData<FileTypes.IFile<DocTypes | string>[]>> {
return await this.fileService.findAll(params) return await this.fileService.findAll(params)
} }
...@@ -57,9 +59,10 @@ export class FileController { ...@@ -57,9 +59,10 @@ export class FileController {
* @returns 返回删除结果 * @returns 返回删除结果
*/ */
@Get('delete') @Get('delete')
@UsePipes(new ParseIdPipe())
@ApiOperation({ summary: '根据ID删除文件' }) @ApiOperation({ summary: '根据ID删除文件' })
async remove(@Query() { id }: FileDeleteDto): Promise<CommonTypes.IResData> { async remove(@Query() { id }: FileDeleteDto): Promise<CommonTypes.IResData> {
return await this.fileService.remove(+id) return await this.fileService.remove(id as number)
} }
/** /**
......
...@@ -28,7 +28,7 @@ export class FileService { ...@@ -28,7 +28,7 @@ export class FileService {
*/ */
async findAll({ device_id, type, filename, skip, take }: FileTypes.FindeFiles<DocTypes>): Promise<CommonTypes.IResData<FileTypes.IFile<DocTypes | string>[]>> { async findAll({ device_id, type, filename, skip, take }: FileTypes.FindeFiles<DocTypes>): Promise<CommonTypes.IResData<FileTypes.IFile<DocTypes | string>[]>> {
const where = { const where = {
device_id: device_id ? +device_id : undefined, device_id,
type, type,
originalname: { originalname: {
contains: filename contains: filename
......
...@@ -34,23 +34,23 @@ ...@@ -34,23 +34,23 @@
# POST http://localhost:3000/broadcast/cmd HTTP/1.1 POST http://localhost:3000/broadcast/cmd HTTP/1.1
# content-type: application/json content-type: application/json
# { {
# "event":"private", "event":"private",
# "device_id":1000001, "device_id":1000000,
# "data":{ "data":{
# "command":"getStorage", "command":"getStorage",
# "payload":{ "payload":{
# "key":"userInfo" "key":"recordList"
# } }
# } }
# } }
http://localhost:3000/file/list?device_id=1000000 # http://localhost:3000/file/list?device_id=1000000
# http://localhost:3000/config?device_id=2 # http://localhost:3000/config?device_id=1000000
# http://localhost:3000/file/delete?id=50
# POST http://localhost:3000/config/add HTTP/1.1 # POST http://localhost:3000/config/add HTTP/1.1
# content-type: application/json # content-type: application/json
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!