|
| 1 | +const StorageInterface = require('./interface'); |
| 2 | +const { Client } = require('pg'); |
| 3 | + |
| 4 | +class PostgresBacking extends StorageInterface { |
| 5 | + |
| 6 | + constructor(label) { |
| 7 | + super(label); |
| 8 | + this.tableName = 'faux_redis_' + this.label.toLowerCase().replace(/[^a-z0-9_]/g, '_'); |
| 9 | + this.client = new Client({ connectionString: process.env.DATABASE_URL }); |
| 10 | + this.queryCreateTableIfNeeded = ` |
| 11 | + CREATE TABLE IF NOT EXISTS ${this.tableName} ( |
| 12 | + namespace TEXT, |
| 13 | + key TEXT, |
| 14 | + value TEXT, |
| 15 | + PRIMARY KEY (namespace, key) |
| 16 | + );`; |
| 17 | + |
| 18 | + this.querySetValue = ` |
| 19 | + INSERT INTO ${this.tableName} (namespace, key, value) |
| 20 | + VALUES ($1::text, $2::text, $3::text) |
| 21 | + ON CONFLICT (namespace, key) |
| 22 | + DO UPDATE SET value=$3::text`; |
| 23 | + |
| 24 | + this.queryGetValue = ` |
| 25 | + SELECT value FROM ${this.tableName} WHERE namespace=$1::text AND key=$2::text`; |
| 26 | + |
| 27 | + this.queryRemoveValue = ` |
| 28 | + DELETE FROM ${this.tableName} WHERE namespace=$1::text AND key=$2::text`; |
| 29 | + |
| 30 | + this.queryGetKeys = ` |
| 31 | + SELECT key FROM ${this.tableName} WHERE namespace=$1::text`; |
| 32 | + } |
| 33 | + |
| 34 | + async initialize() { |
| 35 | + await this.client.connect(); |
| 36 | + return this.client.query(this.queryCreateTableIfNeeded); |
| 37 | + } |
| 38 | + |
| 39 | + async set(ns, key, value) { |
| 40 | + if (value === undefined) throw new Error("Tried to store undefined"); |
| 41 | + const result = await this.client.query(this.querySetValue, [ns, key, value]); |
| 42 | + if (result.rowCount !== 1) throw new Error('Failure in postgres set'); |
| 43 | + } |
| 44 | + |
| 45 | + async get(ns, key) { |
| 46 | + const result = await this.client.query(this.queryGetValue, [ns, key]); |
| 47 | + if (result.rowCount !== 1) throw new ReferenceError(key); |
| 48 | + return result.rows[0].value; |
| 49 | + } |
| 50 | + |
| 51 | + async has(ns, key) { |
| 52 | + const result = await this.client.query(this.queryGetValue, [ns, key]); |
| 53 | + return result.rowCount === 1; |
| 54 | + } |
| 55 | + |
| 56 | + async remove(ns, key) { |
| 57 | + const result = await this.client.query(this.queryRemoveValue, [ns, key]); |
| 58 | + return result.rowCount === 1; |
| 59 | + } |
| 60 | + |
| 61 | + async keys(ns, regex) { |
| 62 | + const result = await this.client.query(this.queryGetKeys, [ns]); |
| 63 | + const keys = result.rows.map(r => r.key); |
| 64 | + return regex ? keys.filter(x => x.match(regex)) : keys; |
| 65 | + } |
| 66 | + |
| 67 | + async shutdown() { |
| 68 | + await this.client.end(); |
| 69 | + this.client = null; |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +module.exports = PostgresBacking; |
0 commit comments