Skip to content

Commit

Permalink
Add retry logic to db writes
Browse files Browse the repository at this point in the history
  • Loading branch information
Yasamato committed Dec 4, 2024
1 parent 0c632da commit c5b26b6
Showing 1 changed file with 51 additions and 12 deletions.
63 changes: 51 additions & 12 deletions lib/db/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,29 +116,68 @@ export async function insert(
collection: string,
data: Record<string, any>
): Promise<string> {
const db = (await dbClient).db('index')
data.createdAt = new Date()
data.lastModified = new Date()
const { insertedId } = await db.collection(collection).insertOne(data)
return insertedId.toString()
let tries = 1
while (tries < 3) {
try {
const db = (await dbClient).db('index')
data.createdAt = new Date()
data.lastModified = new Date()
const { insertedId } = await db.collection(collection).insertOne(data)
return insertedId.toString()
} catch (error) {
console.error(
'#' +
tries.toString() +
': Failed to insert into collection ' +
collection
)
tries++
}
}
throw Error('Unable to insert entry into ' + collection + ' after 3 retires')
}

export async function updateOne(
collection: string,
query: Record<string, any>,
data: Record<string, any>
) {
const db = (await dbClient).db('index')
await db.collection(collection).updateOne(polluteId(query), {
$set: data,
$currentDate: { lastModified: true },
})
let tries = 1
while (tries < 3) {
try {
const db = (await dbClient).db('index')
await db.collection(collection).updateOne(polluteId(query), {
$set: data,
$currentDate: { lastModified: true },
})
} catch (error) {
console.error(
'#' + tries.toString() + ': Failed to update collection ' + collection
)
tries++
}
}
throw Error('Unable to update entry of ' + collection + ' after 3 retires')
}

export async function deleteOne(
collection: string,
query: Record<string, any>
) {
const db = (await dbClient).db('index')
await db.collection(collection).deleteOne(polluteId(query))
let tries = 1
while (tries < 3) {
try {
const db = (await dbClient).db('index')
await db.collection(collection).deleteOne(polluteId(query))
} catch (error) {
console.error(
'#' +
tries.toString() +
': Failed to delete from collection ' +
collection
)
tries++
}
}
throw Error('Unable to delete entry from ' + collection + ' after 3 retires')
}

0 comments on commit c5b26b6

Please sign in to comment.