Skip to content

Commit

Permalink
Adiciona timeout de 5s na conexão
Browse files Browse the repository at this point in the history
  • Loading branch information
Phenome committed Sep 18, 2024
1 parent aeda6b2 commit 95249f2
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions web/src/lib/mongo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,29 @@ if (!url) {
}
const client = isDeno ? new MongoClient() : new MongoClient(url)

function connectClientWithTimeout(timeout = 5000) {
return new Promise((resolve) => {
const timeoutTimer = setTimeout(() => {
resolve(false)
}, timeout)
client
.connect(isDeno ? url : undefined)
.then(
() => {
resolve(true)
},
() => {
resolve(false)
}
)
.finally(() => {
clearTimeout(timeoutTimer)
})
})
}

async function getCollection(dbName: string, collection: string) {
const success = await client
.connect(isDeno ? url : undefined)
.then(() => true)
.catch(() => false)
if (!success) {
if (!(await connectClientWithTimeout())) {
return null
}
return client[isDeno ? 'database' : 'db'](dbName).collection(
Expand Down

0 comments on commit 95249f2

Please sign in to comment.