( db: Db, filepath: string, collectionPrefix: string )
| 23 | } |
| 24 | |
| 25 | async function _processFileForRefresh( |
| 26 | db: Db, |
| 27 | filepath: string, |
| 28 | collectionPrefix: string |
| 29 | ): Promise<string | null> { |
| 30 | const collectionName = getCollectionNameFromJsonFile(filepath); |
| 31 | const filename = filepath.split('/').pop(); |
| 32 | |
| 33 | if (!collectionName || !filename) { |
| 34 | console.warn(`Could not determine collection or filename for ${filepath}. Skipping.`); |
| 35 | return null; |
| 36 | } |
| 37 | |
| 38 | const indexName = getIndexName(filename); |
| 39 | if (indexName === null) { |
| 40 | console.warn(`Could not extract index name from filename ${filename}. Skipping index entry.`); |
| 41 | return null; |
| 42 | } |
| 43 | |
| 44 | console.log(`Refreshing collection '${collectionName}' from ${filepath}...`); |
| 45 | |
| 46 | let data: any; |
| 47 | try { |
| 48 | data = JSON.parse(readFileSync(filepath, 'utf8')); |
| 49 | } catch (err) { |
| 50 | console.error(` Error parsing JSON from ${filepath}:`, err); |
| 51 | return null; |
| 52 | } |
| 53 | |
| 54 | const updatedData = Array.isArray(data) |
| 55 | ? data.map((record: any) => ({ ...record, updated_at: new Date().toISOString() })) |
| 56 | : []; |
| 57 | |
| 58 | const collection: Collection = db.collection(collectionName); |
| 59 | |
| 60 | try { |
| 61 | await collection.drop(); |
| 62 | console.log(` Dropped existing collection '${collectionName}'.`); |
| 63 | } catch (err) { |
| 64 | if (!(err instanceof MongoServerError && err.codeName === 'NamespaceNotFound')) { |
| 65 | console.error(` Error dropping collection '${collectionName}':`, err); |
| 66 | return null; |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | if (updatedData.length === 0) { |
| 71 | console.log(` No data found in '${collectionName}' — collection dropped and left empty.`); |
| 72 | return null; |
| 73 | } |
| 74 | |
| 75 | try { |
| 76 | const insertResult = await collection.insertMany(updatedData); |
| 77 | console.log(` Inserted ${insertResult.insertedCount} documents into '${collectionName}'.`); |
| 78 | } catch (err) { |
| 79 | console.error(` Error inserting documents into '${collectionName}':`, err); |
| 80 | return null; |
| 81 | } |
| 82 |
no test coverage detected