Created
September 23, 2017 19:22
-
-
Save wertlex/3b021d2d5469692ebb434cc7c15e56fd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mongoose = require('mongoose'); | |
async function withTempDb(dbName, action) { | |
const mongoUri = `mongodb://localhost:27017/${dbName}`; | |
const opts = {useMongoClient: true, promiseLibrary: global.Promise }; | |
const conn = mongoose.createConnection(mongoUri, opts); | |
const onceOpen = new Promise( resolve => conn.once('open', resolve )); | |
await onceOpen; | |
let result; | |
try { | |
result = await action(conn); | |
} finally { | |
await conn.dropDatabase(); | |
await conn.close(); | |
} | |
return result; | |
} | |
withTempDb('dummy', () => console.log('Sync ok')); | |
withTempDb('correct', async db => { | |
const collection = db.collection('languages'); | |
await collection.insert({name: 'JS'}); | |
console.log('correct async okay'); | |
}); | |
withTempDb('tempDB-incorrect', async db => { | |
const collection = db.collection('languages'); | |
collection.insert({name: 'JS'}); | |
console.log('not waiting for insert result here...'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment