@notross/mongo-singleton
Version:
A lightweight, zero-fuss way to get a single shared MongoDB connection across your Node.js codebase.
62 lines • 1.75 kB
JavaScript
import { MongoSingleton } from './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 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;
}
}
export const useClient = (clientId, props) => {
const { client } = new Stateful(clientId, props);
return {
client,
collection: client.collection,
db: client.db,
};
};
//# sourceMappingURL=clients.js.map