fix(backend): avoid duplicate key errors during complex matching by upserting MusicFile by s3Key

This commit is contained in:
Geert Rademakes 2025-08-13 16:48:34 +02:00
parent 1560e614dc
commit fe3a7abf32

View File

@ -361,16 +361,17 @@ class BackgroundJobService {
const fileBuffer = await s3Service.getFileContent(s3File.key); const fileBuffer = await s3Service.getFileContent(s3File.key);
const metadata = await audioMetadataService.extractMetadata(fileBuffer, filename); const metadata = await audioMetadataService.extractMetadata(fileBuffer, filename);
const musicFile = new MusicFile({ // Reuse existing MusicFile document if present to avoid duplicate key errors
originalName: filename, let musicFile = await MusicFile.findOne({ s3Key: s3File.key });
s3Key: s3File.key, if (!musicFile) {
s3Url: `${process.env.S3_ENDPOINT}/${process.env.S3_BUCKET_NAME}/${s3File.key}`, musicFile = new MusicFile({ s3Key: s3File.key });
contentType: guessContentType(filename), }
size: s3File.size, musicFile.originalName = filename;
...metadata, musicFile.s3Key = s3File.key;
}); musicFile.s3Url = `${process.env.S3_ENDPOINT}/${process.env.S3_BUCKET_NAME}/${s3File.key}`;
musicFile.contentType = guessContentType(filename);
processedFiles.push(musicFile); musicFile.size = s3File.size;
Object.assign(musicFile, metadata);
// Try complex matching // Try complex matching
const matchResult = await songMatchingService.matchMusicFileToSongs(musicFile, { const matchResult = await songMatchingService.matchMusicFileToSongs(musicFile, {
@ -402,7 +403,7 @@ class BackgroundJobService {
stillUnmatched++; stillUnmatched++;
} }
// Save immediately for real-time availability // Save immediately for real-time availability (create or update)
await musicFile.save(); await musicFile.save();
processedFiles.push(musicFile); processedFiles.push(musicFile);