mnml/ops/migrations/20190616170750_notifications.js
2019-06-16 17:47:45 +10:00

41 lines
852 B
JavaScript

const notify = `
CREATE OR REPLACE FUNCTION notify_event() RETURNS TRIGGER AS $$
DECLARE
record RECORD;
id UUID;
payload JSON;
BEGIN
IF (TG_OP = 'DELETE') THEN
id = OLD.id;
ELSE
id = NEW.id;
END IF;
payload = json_build_object(
'table', TG_TABLE_NAME,
'action', TG_OP,
'id', id
);
PERFORM pg_notify('events', payload::text);
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
`;
const trigger = table => `
CREATE TRIGGER notify_${table}_event
AFTER INSERT OR UPDATE OR DELETE ON ${table}
FOR EACH ROW EXECUTE PROCEDURE notify_event();
`;
exports.up = async knex => {
await knex.raw(notify);
await knex.raw(trigger('accounts'));
await knex.raw(trigger('games'));
await knex.raw(trigger('instances'));
};
exports.down = async () => {};