Commit 6f0cee25 by yixinjj

add file list method

1 parent e29eb7bc
import { ApiProperty } from '@nestjs/swagger'
import { Transform } from 'class-transformer'
import { isString, Matches } from 'class-validator'
import { IsOptional, isString, Matches, registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'
// 自定义验证装饰器
export function IsNumberOrNumberString(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
name: 'isNumberOrNumberString',
target: object.constructor,
propertyName: propertyName,
constraints: [],
options: validationOptions,
validator: {
validate(value: any, args: ValidationArguments) {
// 如果值为空(null, undefined, ''),则验证通过
if (value === null || value === undefined || value === '') {
return true
}
// 尝试将值转换为数字,如果转换成功或原本就是数字,则验证通过
// 注意:这里使用了 Number.isNaN 来检查转换结果是否为 NaN,从而排除非数字字符串
return !Number.isNaN(Number(value))
},
defaultMessage(args: ValidationArguments): string {
// 这里可以返回自定义的错误消息
return `${args.property} must be a number or a numeric string`
}
}
})
}
}
export class BaseDto {
@ApiProperty({
type: Number,
......@@ -9,6 +37,8 @@ export class BaseDto {
required: false,
default: 0
})
@IsOptional()
@IsNumberOrNumberString()
device_id?: number
@ApiProperty({
type: Number,
......@@ -16,6 +46,8 @@ export class BaseDto {
required: false,
default: 10
})
@IsOptional()
@IsNumberOrNumberString()
pageSize?: number
@ApiProperty({
......@@ -24,5 +56,7 @@ export class BaseDto {
required: false,
default: 1
})
@IsOptional()
@IsNumberOrNumberString()
pageIndex?: number
}
import { IsNumber, IsNotEmpty, ValidateIf, IsInt, Matches, isString, } from 'class-validator'
import { IsNumber, IsNotEmpty, ValidateIf, IsInt, Matches, isString, IsEnum, IsDefined, isEnum, IsOptional, } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger'
import { Transform } from 'class-transformer'
import { DocTypes } from '../common/enums'
import { BaseDto } from './base.dto'
export class FileQueryDto extends BaseDto {
@ApiProperty({
type: String,
description: '文件名称',
required: false,
default: ''
})
filename?: string
@ApiProperty({
type: String,
description: '文件类型',
required: false,
default: ''
})
@IsOptional() // 允许为空
@IsEnum(DocTypes) // 非空时必须为 DocTypes 枚举中的一个值
type?: DocTypes
}
export class FileDeleteDto {
export class FileDto {
@ApiProperty({
type: Number,
description: '文件记录表主键Id',
......@@ -15,4 +37,4 @@ export class FileDto {
@IsNotEmpty({ message: 'id不能为空' })
id: number | string
}
}
\ No newline at end of file
......@@ -4,9 +4,10 @@ import { FileService } from './file.service'
import { Response, Request } from 'express'
import { FileMimeTypeFilter } from '../../common/filters'
import { UploadFile } from '../../common/decorators'
import { DocTypes } from 'src/common/enums'
import { FileDto } from '../../dto'
import { DocTypes } from '../../common/enums'
import { FileDeleteDto, FileQueryDto } from '../../dto'
import { ApiOperation, ApiTags } from '@nestjs/swagger'
import { PagesPipe } from '../../common/pipes'
@ApiTags('文件管理')
@UsePipes(new ValidationPipe())
@Controller('file')
......@@ -28,12 +29,25 @@ export class FileController {
@Post('upload')
@ApiOperation({ summary: '文件上传' })
@UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain'), limits: { fileSize: 1024 * 1024 * 100 } })
upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request): FileTypes.IFile<DocTypes> {
upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request): FileTypes.FileUpload<DocTypes> {
const { fieldname, encoding, destination, stream, buffer, ...o } = file
const bodyData: Pick<FileTypes.IFile<DocTypes>, 'device_id' | 'type'> = { device_id: Number(req.body.deviceId), type: req.body.type }
const fi: FileTypes.IFile<DocTypes> = Object.assign({ created_at: new Date() }, bodyData, o)
this.fileService.save(fi)
return fi
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)
this.fileService.save(f)
return f
}
/**
* 获取所有文件的方法
* 该方法接收一个文件类型和一个设备ID和文件名,并返回该设备下所有指定类型的文件
* @param params - 包含文件类型和设备ID的对象
* @returns 返回该设备下所有指定类型的文件
*/
@Get('list')
@ApiOperation({ summary: '获取文件列表' })
@UsePipes(new PagesPipe())
async findAll(@Query() params: FileQueryDto): Promise<CommonTypes.IResData<FileTypes.IFile<DocTypes | string>[]>> {
return await this.fileService.findAll(params)
}
/**
......@@ -44,7 +58,7 @@ export class FileController {
*/
@Get('delete')
@ApiOperation({ summary: '根据ID删除文件' })
async remove(@Query() { id }: FileDto): Promise<CommonTypes.IResData> {
async remove(@Query() { id }: FileDeleteDto): Promise<CommonTypes.IResData> {
return await this.fileService.remove(+id)
}
......
......@@ -5,6 +5,7 @@ import * as fs from 'fs'
import * as path from 'path'
import { DocTypes, RESPONSE_CODE } from '../../common/enums'
import { PrismaService } from 'nestjs-prisma'
import { Doc } from 'prettier'
@Injectable()
export class FileService {
......@@ -21,12 +22,35 @@ export class FileService {
) {}
/**
* 获取所有文件的方法。
*
* @returns 一个 Promise,成功时解析为包含所有文件的 CommonTypes.IResData 对象。
*/
async findAll({ device_id, type, filename, skip, take }: FileTypes.FindeFiles<DocTypes>): Promise<CommonTypes.IResData<FileTypes.IFile<DocTypes | string>[]>> {
const where = {
device_id: device_id ? +device_id : undefined,
type,
originalname: {
contains: filename
},
filename: {
contains: filename
}
}
const files: FileTypes.IFile<DocTypes | string>[] = await this.prisma.file.findMany({ skip, take, where })
const total: number = await this.prisma.file.count({
where
})
return { total, data: files }
}
/**
* 保存文件到数据库的方法。
*
* @param file - 要保存的文件对象,包含文件名、路径、创建时间等信息。
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/
async save(file: FileTypes.IFile<DocTypes>): Promise<CommonTypes.IResData> {
async save(file: FileTypes.FileUpload<DocTypes>): Promise<CommonTypes.IResData> {
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 } })) || {}
......
declare namespace FileTypes {
interface IFile<T> extends CommonTypes.IDeviceId, Pick<CommonTypes.ITime,'created_at'> {
interface IFile<T> extends CommonTypes.IId, CommonTypes.IDeviceId, Pick<CommonTypes.ITime, 'created_at'> {
originalname: string
mimetype: string
filename: string
path: string
size: number,
size: number
type: T
}
type FileUpload<T> = Omit<IFile<T>, 'id'>
type FindeFiles<T = any> = Partial<Pick<IFile<T>, 'filename' | 'type' | 'device_id'>> & CommonTypes.IQueryBase
}
......@@ -34,22 +34,21 @@
POST http://localhost:3000/broadcast/cmd HTTP/1.1
content-type: application/json
{
"event":"private",
"device_id":1000001,
"data":{
"command":"getStorage",
"payload":{
"key":"userInfo"
}
}
}
# http://localhost:3000/file/delete?id=16
# POST http://localhost:3000/broadcast/cmd HTTP/1.1
# content-type: application/json
# {
# "event":"private",
# "device_id":1000001,
# "data":{
# "command":"getStorage",
# "payload":{
# "key":"userInfo"
# }
# }
# }
http://localhost:3000/file/list?device_id=1000000
# http://localhost:3000/config?device_id=2
# POST http://localhost:3000/config/add HTTP/1.1
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!