export const getOrphanedFiles = internalQuery({
args: {},
handler: async (ctx) => {
const ONE_HOUR_MS = 1000 * 60 * 60;
const cutoffTimeMs = Date.now() - ONE_HOUR_MS;
const orphanedFiles = await ctx.db
.query("files")
.withIndex("by_is_uploaded_created_at", q =>
q.eq("isUploaded", false).lte("createdAt", cutoffTimeMs)
)
.take(100);
return orphanedFiles;
},
});
export const deleteFile = internalMutation({
args: {
fileId: v.id("files"),
},
handler: async (ctx, args) => {
await ctx.db.delete(args.fileId);
},
});
export const purgeOrphanedFiles = internalAction({
args: {},
handler: async (ctx) => {
const orphanedFiles = await ctx.runQuery(internal.files.getOrphanedFiles);
for (const file of orphanedFiles) {
try {
const command = new DeleteObjectCommand({
Bucket: ${process.env.PROJECT_NAME!}-${process.env.ENV_SUFFIX!}-${process.env.AWS_REGION!}-s3-${process.env.AWS_PRIVATE_S3_BUCKET_NAME!},
Key: file._id,
});
await s3Client.send(command);
await ctx.runMutation(internal.files.deleteFile, {
fileId: file._id,
});
} catch (error) {
console.error(Failed to purge orphaned file ${file._id}: ${error});
}
}
},
});
is there a cleaner way of writing this so i dont have to have multiple function declared