crystal icon indicating copy to clipboard operation
crystal copied to clipboard

Using Express, is a post hook for a mutation possible?

Open shanestillwell opened this issue 10 years ago • 3 comments

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.

shanestillwell avatar Nov 14 '16 04:11 shanestillwell

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!)

benjie avatar Nov 14 '16 09:11 benjie

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 avatar Nov 14 '16 14:11 calebmer

@calebmer @benjie thanks, looks like pg_notify is a viable solution for now.

shanestillwell avatar Nov 14 '16 23:11 shanestillwell