1
0
Fork 0
mirror of https://github.com/seejohnrun/haste-server.git synced 2024-11-24 21:41:21 +00:00
haste-server/lib/document_stores/mongodb.js

111 lines
3.3 KiB
JavaScript
Raw Normal View History

2021-12-21 22:13:50 +00:00
const { MongoClient } = require("mongodb"),
winston = require("winston");
2016-06-10 20:43:43 +00:00
const MongoDocumentStore = function (options) {
2016-06-10 20:43:43 +00:00
this.expire = options.expire;
this.connectionUrl = process.env.DATABASE_URL || options.connectionUrl;
this.connectionName = process.env.DATABASE_NAME || options.connectionName;
2016-06-10 20:43:43 +00:00
};
MongoDocumentStore.prototype.set = function (key, data, callback, skipExpire) {
2021-12-21 22:13:50 +00:00
const now = Math.floor(new Date().getTime() / 1000);
2016-06-10 20:43:43 +00:00
2021-12-21 22:13:50 +00:00
this.safeConnect((err, db, client) => {
if (err) return callback(false);
2021-12-21 22:13:50 +00:00
db.collection("entries").updateOne(
{
entry_id: key,
$or: [{ expiration: -1 }, { expiration: { $gt: now } }],
},
{
$set: {
entry_id: key,
value: data,
expiration:
this.expire && !skipExpire ? this.expire + now : -1,
},
},
{
upsert: true,
},
(err /*, existing*/) => {
client.close();
2016-06-10 20:43:43 +00:00
2021-12-21 22:13:50 +00:00
if (err) {
winston.error("error persisting value to mongodb", {
error: err,
});
return callback(false);
}
callback(true);
}
);
2016-06-10 20:43:43 +00:00
});
};
MongoDocumentStore.prototype.get = function (key, callback, skipExpire) {
2021-12-21 22:13:50 +00:00
const now = Math.floor(new Date().getTime() / 1000);
2016-06-10 20:43:43 +00:00
2021-12-21 22:13:50 +00:00
this.safeConnect((err, db, client) => {
if (err) return callback(false);
2021-12-21 22:13:50 +00:00
db.collection("entries").findOne(
{
entry_id: key,
$or: [{ expiration: -1 }, { expiration: { $gt: now } }],
},
(err, entry) => {
if (err) {
winston.error("error persisting value to mongodb", {
error: err,
});
client.close();
return callback(false);
}
2016-06-10 20:43:43 +00:00
2021-12-21 22:13:50 +00:00
callback(entry === null ? false : entry.value);
2016-06-10 20:43:43 +00:00
2021-12-21 22:13:50 +00:00
if (
entry !== null &&
entry.expiration !== -1 &&
this.expire &&
!skipExpire
) {
db.collection("entries").updateOne(
{
entry_id: key,
},
{
$set: {
expiration: this.expire + now,
},
},
() => {
client.close();
}
);
}
2016-06-10 20:43:43 +00:00
}
2021-12-21 22:13:50 +00:00
);
2016-06-10 20:43:43 +00:00
});
};
MongoDocumentStore.prototype.safeConnect = function (callback) {
2021-12-21 22:13:50 +00:00
MongoClient.connect(
this.connectionUrl,
{ useUnifiedTopology: true },
(err, client) => {
if (err) {
winston.error("error connecting to mongodb", { error: err });
callback(err);
} else {
callback(undefined, client.db(this.connectionName), client);
}
2016-06-10 20:43:43 +00:00
}
2021-12-21 22:13:50 +00:00
);
2016-06-10 20:43:43 +00:00
};
module.exports = MongoDocumentStore;