forked from caub/mongo-lazy-connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (74 loc) · 2.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const {URL} = require('url');
const mongo = require('mongodb');
const NULL = Object.freeze(Object.create(null));
/**
*
* @param {*} url
* @param {*} opts
*/
module.exports = (url, opts) => {
let client;
let dbName;
try {
dbName = new URL(url).pathname.slice(1);
} catch (e) {
throw new Error('We expect the first argument to be a connection string url')
}
let close = () => Promise.resolve();
let connect = async () => {
return client || mongo(url, {useNewUrlParser: true, ...opts}).then(_client => {
client = _client;
close = () => {
client = null;
return _client.close();
};
return client;
});
};
return new Proxy(NULL, {
get(_, name) {
if (name === 'client') return client;
if (name === 'collection') {
return collName => client ? client.db(dbName).collection(collName) : new Proxy(NULL, {
get(_, funcName) {
if (funcName === 'find') {
const chain = (calls = []) => new Proxy(NULL, {
get(_, name) {
if (name === 'toArray' || name === 'then' || typeof name !== 'string') {
return async () => {
client = await connect();
const coll = client.db(dbName).collection(collName);
return calls.reduce((c, {name, args}) => typeof c[name] === 'function' ? c[name](...args) : c, coll).toArray();
};
}
return (...args) => chain(calls.concat({name, args}));
}
});
return (...args) => chain([{name: 'find', args}]);
}
return async (...args) => {
client = await connect();
const coll = client.db(dbName).collection(collName);
return coll[funcName](...args);
};
}
});
}
if (name === 'connect') {
return connect;
}
if (name === 'close') {
return close;
}
return async (...args) => {
if (client) {
client = await connect();
}
if (!client.db(dbName)[name]) {
throw new Error(`This Db method doesn't exists, valid ones are: http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html`)
}
return client.db(dbName)[name](...args);
};
}
});
};