59 lines
1.9 KiB
TypeScript
59 lines
1.9 KiB
TypeScript
import { eq, notInArray } from 'drizzle-orm'
|
|
import { useDB, schema } from '../db'
|
|
import { scanMusicFolder } from '../utils/fileScanner'
|
|
|
|
const { cards } = schema
|
|
|
|
export async function syncCardsWithDatabase(folderPath: string) {
|
|
const db = useDB()
|
|
const scannedCards = await scanMusicFolder(folderPath)
|
|
|
|
console.log(`📁 ${scannedCards.length} cards trouvées dans le dossier`)
|
|
|
|
// 1. Récupérer les cards existantes en DB
|
|
const existingCards = await db.select().from(cards).all()
|
|
const existingEsids = new Set(existingCards.map((t) => t.esid))
|
|
|
|
// 2. Identifier les nouvelles cards à ajouter
|
|
const cardsToInsert = scannedCards.filter((card) => !existingEsids.has(card.esid))
|
|
|
|
// 3. Identifier les cards à supprimer
|
|
const scannedEsids = new Set(scannedCards.map((t) => t.esid))
|
|
const cardsToDelete = existingCards.filter((t) => !scannedEsids.has(t.esid))
|
|
|
|
// 4. Insérer les nouvelles cards
|
|
if (cardsToInsert.length > 0) {
|
|
// Dans la fonction syncCardsWithDatabase
|
|
await db.insert(cards).values(
|
|
cardsToInsert.map((card) => ({
|
|
url_audio: card.url_audio,
|
|
url_image: card.url_image,
|
|
year: card.year,
|
|
month: card.month,
|
|
day: card.day,
|
|
hour: card.hour,
|
|
artist: card.artist,
|
|
title: card.title,
|
|
esid: card.esid,
|
|
slug: card.slug,
|
|
createdAt: card.createdAt,
|
|
suit: card.suit,
|
|
rank: card.rank
|
|
}))
|
|
)
|
|
console.log(`✅ ${cardsToInsert.length} cards ajoutées`)
|
|
}
|
|
|
|
// 5. Supprimer les cards obsolètes avec une requête distincte pour chaque esid
|
|
for (const cardToDelete of cardsToDelete) {
|
|
await db.delete(cards).where(eq(cards.esid, cardToDelete.esid))
|
|
console.log(`🗑️ ${cardsToDelete.length} cards supprimées`)
|
|
}
|
|
|
|
return {
|
|
added: cardsToInsert.length,
|
|
deleted: cardsToDelete.length,
|
|
total: scannedCards.length
|
|
}
|
|
}
|