file.service.ts
5.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import { Inject, Injectable, Logger } from '@nestjs/common'
import { tar } from 'compressing'
import { ConfigService } from 'nestjs-config'
import * as fs from 'fs'
import * as path from 'path'
import { DocTypes, RESPONSE_CODE } from '../../common/enums'
import { PrismaService } from 'nestjs-prisma'
import { join } from 'path'
const normalizeLogName = (name: string) => {
const ext = path.extname(name)
const base = name.slice(0, name.length - ext.length)
return base.replace(/_\d{10,}$/, '').replace(/@\d+@\d{10,}(?:-\d+)?$/, '')
}
@Injectable()
export class FileService {
/**
* 文件服务的构造函数。
*
* @param configService - 配置服务的实例,用于获取配置信息。
* @param prisma - PrismaService的实例,用于数据库操作。
*/
constructor(
private readonly configService: ConfigService,
@Inject(PrismaService)
private readonly prisma: PrismaService // private connection: Connection,
) {}
/**
* 获取所有文件的方法。
*
* @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,
type,
originalname: {
contains: filename
},
filename: {
contains: filename
}
}
const files: FileTypes.IFile<DocTypes | string>[] = await this.prisma.file.findMany({ skip, take, where, orderBy: { created_at: 'desc' } })
const total: number = await this.prisma.file.count({
where
})
return { total, data: files }
}
/**
* 保存文件到数据库的方法。
*
* @param file - 要保存的文件对象,包含文件名、路径、创建时间等信息。
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/
async save(file: FileTypes.FileUpload<DocTypes>): Promise<CommonTypes.IResData> {
const { filename, created_at, destination } = file
await this.prisma.$transaction(async prisma => {
const where =
file.type === DocTypes.Log
? {
device_id: file.device_id,
type: file.type,
OR: [
{ filename },
{ filename: { startsWith: `${normalizeLogName(file.originalname)}@${file.device_id}@` } },
{ filename: { startsWith: `${normalizeLogName(file.originalname)}@${file.device_id}.` } },
{
AND: [{ filename: { startsWith: `${normalizeLogName(file.originalname)}_` } }, { filename: { contains: `@${file.device_id}@` } }]
}
]
}
: {
device_id: file.device_id,
type: file.type,
originalname: file.originalname
}
const files: Pick<FileTypes.IFile<DocTypes>, 'id' | 'destination' | 'filename'>[] = await prisma.file.findMany({
where,
select: { id: true, destination: true, filename: true },
orderBy: { created_at: 'desc' }
})
const currentPath = join(destination, filename)
if (files?.length) {
const [keep, ...stales] = files
for (const { id, destination: dest, filename: fname } of stales) {
const origin_path = join(dest, fname)
try {
fs.existsSync(origin_path) && fs.unlinkSync(origin_path)
} catch (err) {
Logger.error('删除文件失败', err)
}
await prisma.file.delete({ where: { id } })
}
const keepPath = join(keep.destination, keep.filename)
try {
keepPath !== currentPath && fs.existsSync(keepPath) && fs.unlinkSync(keepPath)
} catch (err) {
Logger.error('删除文件失败', err)
}
await prisma.file.update({ where: { id: keep.id }, data: { ...file } })
} else {
await prisma.file.create({ data: file })
}
await prisma.device_status.update({ where: { device_id: file.device_id }, data: { last_log_upload_time: created_at } })
})
return { code: RESPONSE_CODE.SUCCESS, message: '文件保存成功', data: { path: file.path } }
}
/**
* 从数据库中移除文件。
*
* @param id - 要移除的文件的唯一标识符。
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/
async remove(id: number): Promise<CommonTypes.IResData> {
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 { code: RESPONSE_CODE.SUCCESS, message: '删除成功' }
}
async downloadAll() {
const uploadDir = this.configService.get('file').root
const tarStream = new tar.Stream()
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)
})
}
removeFileTask() {}
}