Created
September 16, 2019 19:43
-
-
Save craftdelivery/ca49197d08019e20031c4fc8cad1c74c to your computer and use it in GitHub Desktop.
pg_notify combine updated and previous values in json payload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pg from 'pg' | |
import EventEmitter from 'events' | |
import util from 'util' | |
/* | |
initialize postgres client... | |
*/ | |
function PgEmitter() { | |
EventEmitter.call(this) | |
} | |
util.inherits(PgEmitter, EventEmitter) | |
const pgEmitter = new PgEmitter; | |
pgclient.on('notification', (msg) => { | |
let payload = JSON.parse(msg.payload) | |
pgEmitter.emit(msg.channel, payload) | |
}) | |
pgclient.query('LISTEN notify_foo') | |
pgEmitter.on('notify_foo', payload => { | |
// handle event... | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- combines old and new values into a single json stringified payload | |
CREATE OR REPLACE FUNCTION notify_foo() | |
RETURNS trigger AS | |
$BODY$ | |
DECLARE | |
payload jsonb; | |
BEGIN | |
payload := json_build_object( | |
'oldRow', OLD, | |
'newRow', NEW | |
); | |
PERFORM pg_notify('notify_foo', payload::text); | |
RETURN NULL; | |
END; | |
$BODY$ | |
LANGUAGE plpgsql VOLATILE; | |
CREATE TRIGGER notify_foo | |
AFTER UPDATE | |
ON "bar" | |
FOR EACH ROW | |
EXECUTE PROCEDURE notify_foo(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment