UNPKG

@notross/mongo-singleton

Version:

A lightweight, zero-fuss way to get a single shared MongoDB connection across your Node.js codebase.

66 lines 1.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useClient = void 0; const mongo_singleton_1 = require("./mongo-singleton"); class State { constructor() { this._clients = {}; this.add = this.addClient.bind(this); this.set = this.setClient.bind(this); this.get = this.getClient.bind(this); this.clients = this._clients; } addClient(clientId, client) { if (this._clients[clientId]) { console.warn(`A client with ID ${clientId} already exists.`); } else { this.setClient({ [clientId]: client }); } } setClient(client) { this._clients = { ...this._clients, ...client }; this.clients = this._clients; } getClient(clientId) { return this._clients[clientId]; } getClients() { return this._clients; } } const state = new State(); class Stateful { constructor(clientId, props) { this.set = this.update.bind(this); this.get = this.getClient.bind(this); this.clientId = clientId; this.client = state.get(clientId) || this.createClient(props); } createClient(props) { const client = new mongo_singleton_1.MongoSingleton(props); state.add(this.clientId, client); this.update(client); return client; } getClient() { return state.get(this.clientId); } update(value) { if (typeof value === 'function') { value = value(this.getClient()); } state.set({ [this.clientId]: value }); this.client = value; } } const useClient = (clientId, props) => { const { client } = new Stateful(clientId, props); return { client, collection: client.collection, db: client.db, }; }; exports.useClient = useClient; //# sourceMappingURL=singletons.js.map