- Updated the transaction processing logic to clear existing transactions and perform bulk upserts instead of inserts. - Enhanced the response to include counts of upserted and modified transactions.
49 lines
No EOL
1.4 KiB
JavaScript
49 lines
No EOL
1.4 KiB
JavaScript
import { getCollection } from '../../utils/db.js'
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
try {
|
|
const transactions = await readBody(event)
|
|
const collection = await getCollection('transactions')
|
|
|
|
// Clear existing transactions and upsert new ones
|
|
await collection.deleteMany({})
|
|
|
|
if (transactions.length > 0) {
|
|
// Convert transactions for MongoDB and use bulk upsert operations
|
|
const bulkOps = transactions.map(transaction => ({
|
|
replaceOne: {
|
|
filter: { _id: transaction.id },
|
|
replacement: {
|
|
...transaction,
|
|
_id: transaction.id,
|
|
id: undefined,
|
|
date: new Date(transaction.date),
|
|
endDate: transaction.endDate ? new Date(transaction.endDate) : null,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date()
|
|
},
|
|
upsert: true
|
|
}
|
|
}))
|
|
|
|
const result = await collection.bulkWrite(bulkOps)
|
|
|
|
return {
|
|
success: true,
|
|
insertedCount: result.upsertedCount,
|
|
modifiedCount: result.modifiedCount
|
|
}
|
|
}
|
|
|
|
return {
|
|
success: true,
|
|
insertedCount: 0
|
|
}
|
|
} catch (error) {
|
|
console.error('Error bulk updating transactions:', error)
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: 'Failed to bulk update transactions'
|
|
})
|
|
}
|
|
}) |