diff --git a/lib/RateLimiterPostgres.js b/lib/RateLimiterPostgres.js index 82b5555..48cdd74 100644 --- a/lib/RateLimiterPostgres.js +++ b/lib/RateLimiterPostgres.js @@ -54,11 +54,15 @@ class RateLimiterPostgres extends RateLimiterStoreAbstract { } } + _getTableIdentifier() { + return this.schemaName ? `"${this.schemaName}"."${this.tableName}"` : `"${this.tableName}"`; + } + clearExpired(expire) { return new Promise((resolve) => { const q = { name: 'rlflx-clear-expired', - text: `DELETE FROM "${this.schemaName}"."${this.tableName}" WHERE expire < $1`, + text: `DELETE FROM ${this._getTableIdentifier()} WHERE expire < $1`, values: [expire], }; this._query(q) @@ -152,7 +156,7 @@ class RateLimiterPostgres extends RateLimiterStoreAbstract { } _getCreateTableStmt() { - return `CREATE TABLE IF NOT EXISTS "${this.schemaName}"."${this.tableName}" ( + return `CREATE TABLE IF NOT EXISTS ${this._getTableIdentifier()} ( key varchar(255) PRIMARY KEY, points integer NOT NULL DEFAULT 0, expire bigint @@ -197,7 +201,7 @@ class RateLimiterPostgres extends RateLimiterStoreAbstract { } set schemaName(value) { - this._schemaName = typeof value === 'undefined' ? 'public' : value; + this._schemaName = value; } get tableCreated() { @@ -262,18 +266,18 @@ class RateLimiterPostgres extends RateLimiterStoreAbstract { const expireQ = forceExpire ? ' $3 ' : ` CASE - WHEN "${this.schemaName}"."${this.tableName}".expire <= $4 THEN $3 - ELSE "${this.schemaName}"."${this.tableName}".expire + WHEN ${this._getTableIdentifier()}.expire <= $4 THEN $3 + ELSE ${this._getTableIdentifier()}.expire END `; return this._query({ name: forceExpire ? 'rlflx-upsert-force' : 'rlflx-upsert', text: ` - INSERT INTO "${this.schemaName}"."${this.tableName}" VALUES ($1, $2, $3) + INSERT INTO ${this._getTableIdentifier()} VALUES ($1, $2, $3) ON CONFLICT(key) DO UPDATE SET points = CASE - WHEN ("${this.schemaName}"."${this.tableName}".expire <= $4 OR 1=${forceExpire ? 1 : 0}) THEN $2 - ELSE "${this.schemaName}"."${this.tableName}".points + ($2) + WHEN (${this._getTableIdentifier()}.expire <= $4 OR 1=${forceExpire ? 1 : 0}) THEN $2 + ELSE ${this._getTableIdentifier()}.points + ($2) END, expire = ${expireQ} RETURNING points, expire;`, @@ -290,7 +294,7 @@ class RateLimiterPostgres extends RateLimiterStoreAbstract { this._query({ name: 'rlflx-get', text: ` - SELECT points, expire FROM "${this.schemaName}"."${this.tableName}" WHERE key = $1 AND (expire > $2 OR expire IS NULL);`, + SELECT points, expire FROM ${this._getTableIdentifier()} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`, values: [rlKey, Date.now()], }) .then((res) => { @@ -312,7 +316,7 @@ class RateLimiterPostgres extends RateLimiterStoreAbstract { return this._query({ name: 'rlflx-delete', - text: `DELETE FROM "${this.schemaName}"."${this.tableName}" WHERE key = $1`, + text: `DELETE FROM ${this._getTableIdentifier()} WHERE key = $1`, values: [rlKey], }) .then(res => res.rowCount > 0);