PgCache() function
Class decorator turning an @imqueue service into a PostgreSQL-invalidated cache: method results are memoised in redis, and PostgreSQL itself tells the service when to drop them.
It installs a change-notify trigger on every table the service's cacheWith() and cacheBy() decorators declare a dependency on, and subscribes to one LISTEN/NOTIFY channel per table. When a row changes, the matching cached results are invalidated by tag — so a cache entry lives exactly as long as the data behind it is unchanged, rather than for a guessed TTL.
import { PgCache, cacheWith } from '@imqueue/pg-cache';
@PgCache({
postgres: process.env.DB_URL!,
redis: { host: 'localhost', port: 6379 },
})
class UserService extends IMQService {
@cacheWith({ channels: ['users'] })
public async list(): Promise<User[]> { ... }
}
Applied to the class, it wraps start(): the subscription and the triggers are established there, after any existing start() implementation has run. So the cache is inert until the service is started, and a service that never calls start() is never cached.
Awaiting start() is enough — it does not resolve until the triggers exist and the channels are subscribed, so a row changed immediately afterwards cannot go unnoticed. That costs a few tens of milliseconds at boot. If the setup fails, or is not confirmed within PgCacheOptions.invalidationTimeout, the service still caches and reports the failure loudly; pass PgCacheOptions.requireInvalidation to have it run uncached instead.
Works both as a standard (TC39) decorator and as a legacy (experimentalDecorators) one, matching @imqueue/rpc, so it can be applied in either compilation mode.
Redis is resolved in order: options.redisCache, then options.redis, then a cache property already on the service. If none is available start() throws.
Signature:
export declare function PgCache(options: PgCacheOptions): ClassDecorator;
Parameters
|
Parameter |
Type |
Description |
|---|---|---|
|
options |
PostgreSQL and redis connection details, plus the cache-key prefix, publication and trigger-definition overrides |
Returns:
the class decorator to apply, which augments the class with PgCacheable
Read this page as plain markdown — no HTML, no navigation. For pasting into an LLM, or for an agent to fetch.