crystal
crystal copied to clipboard
Using Express, is a post hook for a mutation possible?
I'm using the Express setup of PostGraphQL and I'm wondering if there is a way to run something on the node.js server after a user has been created. E.g. I want to send an email.
registerPerson() ==> insert person in pg ==> queue email ==> respond to client.
You can do it with triggers within PostgreSQL (or within your mutation procedures). Something like:
CREATE FUNCTION queue_row_task() RETURNS TRIGGER AS $$
BEGIN
INSERT INTO job_queue (task_name, details)
VALUES(TG_ARGV[0], json_build_object('id', NEW.id));
-- or use NOTIFY/LISTEN:
-- PERFORM pg_notify(TG_ARGV[0], json_build_object('id', NEW.id));
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER send_welcome_email
AFTER INSERT ON person
FOR EACH ROW
EXECUTE PROCEDURE queue_row_task('person__send_welcome_email');
(This was written off the top of my head, so you'll need to do some sanity checks!)
You can also use pg-pubsub with Postgres LISTEN/NOTIFY commands to accomplish a similar thing. There’s a great example in the PostgREST docs :+1:
@calebmer @benjie thanks, looks like pg_notify is a viable solution for now.