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

66 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-08-26 04:54:58 +02:00
const winston = require('winston');
const postgres = require('pg');
2014-06-09 20:48:35 +02:00
class PostgresDocumentStore {
constructor(options){
this.expire = options.expire;
this.PostgresClient = new postgres.Client(options.clientOptions);
this.safeConnect();
this.PostgresClient.on('end', () => {
winston.debug('disconnected from pg!');
});
}
2014-06-09 20:48:35 +02:00
async set(key, data, skipExpire){
2020-08-28 04:39:03 +02:00
const now = Math.floor(Date.now() / 1000);
return await this.PostgresClient.query(
'INSERT INTO entries (key, value, expiration) VALUES ($1, $2, $3)',
[ key, data, (this.expire && !skipExpire) ? this.expire + now : null ]
)
.then(() => {
return true;
})
.catch(err => {
winston.error('failed to set postgres document', { key: key, error: err });
return false;
2020-08-28 04:39:03 +02:00
});
2014-06-09 20:48:35 +02:00
}
async get(key, skipExpire){
2020-08-28 04:39:03 +02:00
const now = Math.floor(Date.now() / 1000);
2014-06-09 20:48:35 +02:00
return await this.PostgresClient.query(
'SELECT id,value,expiration FROM entries WHERE key = $1 AND (expiration IS NULL OR expiration > $2)',
[ key, now ])
.then(async res => {
if (res.rows.length && this.expire && !skipExpire){
await this.PostgresClient.query(
'UPDATE entries SET expiration = $1 WHERE ID = $2',
[ this.expire + now, res.rows[0].id ]
);
}
return res.rows.length ? res.rows[0].value : null;
})
.catch(err => {
winston.error('error retrieving value from postgres', { error: err });
return null;
});
2020-08-28 04:39:03 +02:00
}
2014-06-09 20:48:35 +02:00
async safeConnect(){
return await this.PostgresClient.connect()
.then(() => {
winston.info('connected to postgres!');
return { error: null };
})
.catch(err => {
winston.error('failed connecting to postgres!', {error: err});
return { error: err };
});
}
}
2014-06-09 20:48:35 +02:00
2014-06-09 22:50:43 +02:00
module.exports = PostgresDocumentStore;