hostr/lib/mongo.js

38 lines
1.2 KiB
JavaScript
Raw Normal View History

2015-08-22 13:35:06 +01:00
import mongodb from 'mongodb-promisified';
const MongoClient = mongodb().MongoClient;
import debugname from 'debug';
const debug = debugname('hostr:mongo');
2016-06-06 15:37:00 +01:00
/* eslint no-param-reassign: ["error", { "props": false }] */
2015-08-23 22:12:32 +01:00
const configuredClient = new Promise((resolve, reject) => {
2015-08-22 13:35:06 +01:00
debug('Connecting to Mongodb');
2015-08-30 18:35:05 +02:00
return MongoClient.connect(process.env.MONGO_URL).then((client) => {
2015-08-22 13:35:06 +01:00
debug('Successfully connected to Mongodb');
client.Users = client.collection('users');
client.Files = client.collection('files');
client.Transactions = client.collection('transactions');
client.Logins = client.collection('logins');
client.Remember = client.collection('remember');
client.Reset = client.collection('reset');
2016-06-06 15:37:00 +01:00
client.Remember.ensureIndex({ created: 1 }, { expireAfterSeconds: 2592000 });
client.Files.ensureIndex({ owner: 1, status: 1, time_added: -1 });
2015-09-02 17:51:31 +02:00
client.ObjectId = client.objectId = mongodb().ObjectId;
2015-08-22 13:35:06 +01:00
return resolve(client);
}).catch((e) => {
2015-08-23 22:12:32 +01:00
reject(e);
2015-08-22 13:35:06 +01:00
});
}).catch((e) => {
debug(e);
});
2016-06-06 15:37:00 +01:00
export default function mongo() {
2015-08-23 22:12:32 +01:00
return function* dbMiddleware(next) {
2015-08-22 13:35:06 +01:00
try {
this.db = yield configuredClient;
} catch (e) {
debug(e);
}
yield next;
2015-08-23 22:12:32 +01:00
};
2015-08-22 13:35:06 +01:00
}