diff --git a/README.md b/README.md index b900045..531e711 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,10 @@ pool.query(` ); `); +pool.on("error", (err) => { + console.error("Postgres error", err); +}); + io.adapter(createAdapter(pool)); io.listen(3000); ``` diff --git a/lib/index.ts b/lib/index.ts index 1b9cd5e..185bbfe 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -80,6 +80,7 @@ export interface PostgresAdapterOptions { channelPrefix: string; /** * The name of the table for payloads over the 8000 bytes limit or containing binary data + * @default "socket_io_attachments" */ tableName: string; /** @@ -107,6 +108,11 @@ export interface PostgresAdapterOptions { * @default 30000 */ cleanupInterval: number; + /** + * Handler for errors. If undefined, it will terminate the process when an error occurs (see https://nodejs.org/api/events.html#error-events). + * @default undefined + */ + errorHandler: (err: any) => void | undefined } /** @@ -135,6 +141,7 @@ export class PostgresAdapter extends Adapter { public heartbeatTimeout: number; public payloadThreshold: number; public cleanupInterval: number; + public errorHandler: (err: any) => void; private readonly pool: any; private client: any; @@ -164,6 +171,8 @@ export class PostgresAdapter extends Adapter { this.heartbeatTimeout = opts.heartbeatTimeout || 10000; this.payloadThreshold = opts.payloadThreshold || 8000; this.cleanupInterval = opts.cleanupInterval || 30000; + const defaultErrorHandler = (err: any) => debug(err); + this.errorHandler = opts.errorHandler || defaultErrorHandler; this.initSubscription(); this.publish({ @@ -198,7 +207,7 @@ export class PostgresAdapter extends Adapter { try { await this.onEvent(msg.payload); } catch (err) { - this.emit("error", err); + this.errorHandler(err); } }); @@ -213,7 +222,7 @@ export class PostgresAdapter extends Adapter { this.client = client; } catch (err) { - this.emit("error", err); + this.errorHandler(err); debug("error while initializing client, scheduling reconnection..."); this.scheduleReconnection(); } @@ -391,7 +400,7 @@ export class PostgresAdapter extends Adapter { `DELETE FROM ${this.tableName} WHERE created_at < now() - interval '${this.cleanupInterval} milliseconds'` ); } catch (err) { - this.emit("error", err); + this.errorHandler(err); } this.scheduleCleanup(); }, this.cleanupInterval); @@ -429,7 +438,7 @@ export class PostgresAdapter extends Adapter { this.scheduleHeartbeat(); } catch (err) { - this.emit("error", err); + this.errorHandler(err); } }