Skip to content

Instantly share code, notes, and snippets.

@ivawzh
Created October 4, 2018 14:54
Show Gist options
  • Save ivawzh/4cea04cd92b907470e3df637a04199df to your computer and use it in GitHub Desktop.
Save ivawzh/4cea04cd92b907470e3df637a04199df to your computer and use it in GitHub Desktop.
Javascript singleton in ES6
TCL: -------------------------------------
TCL: main -> db1 === db2 true
TCL: main -> db1 === db3 true
TCL: -------------------------------------
import { resetCollection, getDatabase } from './mongo'
import { test } from './test'
async function main() {
const db1 = await getDatabase()
const db2 = await getDatabase()
const db3 = await test()
console.log('TCL: -------------------------------------');
console.log('TCL: main -> db1 === db2', db1 === db2);
console.log('TCL: main -> db1 === db3', db1 === db3);
console.log('TCL: -------------------------------------');
}
main()
import { MongoClient } from 'mongodb'
const databaseName = 'foo'
let _singletonClient = null
export async function getDatabase() {
const client = await getClient()
const mongoDb = client.db(databaseName)
return mongoDb
}
export async function getClient() {
if (!_singletonClient) { _singletonClient = await connectClient() }
return _singletonClient
}
export async function resetCollection(collectionName: string) {
const db = await getDatabase()
await db.createCollection(collectionName)
const collection = db.collection(collectionName)
await collection.drop()
return collection
}
async function connectClient() {
console.log('-------------------------- Initiating MongoDB connection')
const uri = 'mongodb://localhost:27017'
const mongoClient = await MongoClient.connect(uri, { useNewUrlParser: true })
return mongoClient
}
import { resetCollection, getDatabase } from './mongo'
export async function test() {
const db = await getDatabase()
return db
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment