1
0
Fork 0
mirror of https://github.com/SunRed/haste-server.git synced 2024-11-01 09:40:21 +01:00
haste-server/lib/document_stores/postgres.js

81 lines
2.2 KiB
JavaScript
Raw Normal View History

2020-08-28 04:39:03 +02:00
// /*global require,module,process*/
2014-06-09 20:48:35 +02:00
2020-08-26 04:54:58 +02:00
const postgres = require('pg');
const winston = require('winston');
2014-06-09 20:48:35 +02:00
// create table entries (id serial primary key, key varchar(255) not null, value text not null, expiration int, unique(key));
2014-06-09 20:48:35 +02:00
2014-06-09 22:50:43 +02:00
// A postgres document store
2020-08-28 04:39:03 +02:00
const PostgresDocumentStore = function (options){
this.expireJS = options.expire;
this.connectionUrl = process.env.DATABASE_URL || options.connectionUrl;
2014-06-09 22:50:43 +02:00
};
2014-06-09 20:48:35 +02:00
2014-06-09 22:50:43 +02:00
PostgresDocumentStore.prototype = {
2014-06-09 20:48:35 +02:00
2020-08-28 04:39:03 +02:00
// Set a given key
set: function (key, data, callback, skipExpire){
const now = Math.floor(Date.now() / 1000);
const that = this;
this.safeConnect(function (err, client, done){
if (err){ return callback(false); }
client.query('INSERT INTO entries (key, value, expiration) VALUES ($1, $2, $3)', [
key,
data,
that.expireJS && !skipExpire ? that.expireJS + now : null
], function (err){
if (err){
winston.error('error persisting value to postgres', { error: err });
return callback(false);
}
callback(true);
done();
});
});
},
2014-06-09 20:48:35 +02:00
2020-08-28 04:39:03 +02:00
// Get a given key's data
get: function (key, callback, skipExpire){
const now = Math.floor(Date.now() / 1000);
const that = this;
this.safeConnect(function (err, client, done){
if (err){ return callback(false); }
client.query('SELECT id,value,expiration from entries where KEY = $1 and (expiration IS NULL or expiration > $2)', [key, now],
function (err, result){
if (err){
winston.error('error retrieving value from postgres', { error: err });
return callback(false);
}
callback(result.rows.length ? result.rows[0].value : false);
if (result.rows.length && that.expireJS && !skipExpire){
client.query('UPDATE entries SET expiration = $1 WHERE ID = $2', [
that.expireJS + now,
result.rows[0].id
], function (err){
if (!err){
done();
}
});
} else {
done();
}
});
});
},
2014-06-09 20:48:35 +02:00
2020-08-28 04:39:03 +02:00
// A connection wrapper
safeConnect: function (callback){
postgres.connect(this.connectionUrl, function (err, client, done){
if (err){
winston.error('error connecting to postgres', { error: err });
callback(err);
} else {
callback(undefined, client, done);
}
});
}
2014-06-09 20:48:35 +02:00
2014-06-09 22:50:43 +02:00
};
2014-06-09 20:48:35 +02:00
2014-06-09 22:50:43 +02:00
module.exports = PostgresDocumentStore;