-
-
Save ivawzh/4cea04cd92b907470e3df637a04199df to your computer and use it in GitHub Desktop.
Javascript singleton in ES6
This file contains hidden or 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
TCL: ------------------------------------- | |
TCL: main -> db1 === db2 true | |
TCL: main -> db1 === db3 true | |
TCL: ------------------------------------- |
This file contains hidden or 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
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() |
This file contains hidden or 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
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 | |
} |
This file contains hidden or 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
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