创建分享码和定期删除的逻辑修改

This commit is contained in:
raohaotian 2025-04-12 07:02:46 +08:00
parent f215539a0e
commit 1f67a2e22d
1 changed files with 35 additions and 16 deletions

View File

@ -106,24 +106,42 @@ export class ShareCodeService extends BaseService<Prisma.ShareCodeDelegate> {
throw new NotFoundException('文件不存在'); throw new NotFoundException('文件不存在');
} }
const { filename, filetype, size } = resource.meta as any as ResourceMeta const { filename, filetype, size } = resource.meta as any as ResourceMeta
// 生成分享码 // 生成分享码(修改的逻辑保证分享码的唯一性)
const code = this.generateCode(); let code = this.generateCode();
// 查找是否已有分享码记录 let existingShareCode;
const existingShareCode = await super.findUnique({ do {
where: { fileId }, // 查找是否已有相同 shareCode 或者相同 FileID 的分享码记录
}); existingShareCode = await super.findUnique({
where: {
OR: [
{ code },
{ fileId }
]
},
});
// 如果找到的是已经被删除的码,则可以使用并更新其他信息,否则重新生成
if (existingShareCode.deleteAt !== null) {
break
}
if (existingShareCode && existingShareCode.code === code) {
code = this.generateCode();
}
} while (existingShareCode && existingShareCode.code === code);
if (existingShareCode) { if (existingShareCode) {
// 更新现有记录,但保留原有文件名 // 更新现有记录,但保留原有文件名
await super.update({ await super.update({
where: { fileId }, where: { id: existingShareCode.id },
data: { data: {
code, code,
expiresAt, expiresAt,
canUseTimes, canUseTimes,
isUsed: false, isUsed: false,
fileId,
fileName: filename || "downloaded_file", fileName: filename || "downloaded_file",
uploadIp, uploadIp,
createdAt: new Date(),
deleteAt: null
}, },
}); });
} else { } else {
@ -218,24 +236,25 @@ export class ShareCodeService extends BaseService<Prisma.ShareCodeDelegate> {
} }
}) })
this.logger.log('需要清理的分享码:', shareCodes); this.logger.log('需要清理的分享码:', shareCodes);
//文件资源硬删除
shareCodes.forEach(code => { shareCodes.forEach(code => {
this.cleanupUploadFolder(code.fileId); this.cleanupUploadFolder(code.fileId);
}) })
const result = await super.deleteMany({ //数据库资源软删除
const result = await super.softDeleteByIds(
[...shareCodes.map(code => code.id)]
);
const deleteResource = await this.resourceService.updateMany({
where: { where: {
fileId: { fileId: {
in: shareCodes.map(code => code.fileId) in: shareCodes.map(code => code.fileId)
} }
}, },
}); data:{
const deleteResource = await this.resourceService.deleteMany({ deletedAt: new Date()
where: {
fileId: {
in: shareCodes.map(code => code.fileId)
}
} }
}) })
this.logger.log(`Cleaned up ${result.count} ${deleteResource.count} expired share codes`); this.logger.log(`Cleaned up ${result} ${deleteResource.count} expired share codes`);
} catch (error) { } catch (error) {
this.logger.error('Failed to cleanup expired share codes', error); this.logger.error('Failed to cleanup expired share codes', error);
} }