Search code examples
node.jspostgresqlknex.js

Is there a way to use "Listen" on knex.js PostgreSQL?



i have a table in PostgreSQL database called "posts".

so what i want to do is watch the posts Table and get notification if any data is inserted.

so i created this notify_changes_of_posts_Table function Like so:

CREATE OR REPLACE FUNCTION notify_changes_of_posts_Table()
RETURNS trigger AS $$
BEGIN
  PERFORM pg_notify(
    'posts_changes',
    json_build_object(
      'operation', TG_OP,
      'record', row_to_json(NEW)
    )::text
  );

  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

and also i created the event trigger Like so:

CREATE TRIGGER posts_changes
AFTER INSERT 
ON posts
FOR EACH ROW
EXECUTE PROCEDURE notify_changes_of_posts_Table()

and my server connected to database like so:

const db = knex({
  client: 'pg',
  connection: {
    host : '127.0.0.1',
    user : 'postgres',
    password : 'admin',
    database : 'mydb'
  }
});

and Notice that the server Nodejs connecting to the database using the knex.js tool.

so in order to get the notifications i need to use " LISTEN " and i don't know how to achieve that i checked the official documentation of knex.js can't find any informations related to this topic.

so guys i'am confusing to finish this work here so if any one can help me here with codes or suggestions if i'am wrong because i'am very very confusing at this time.
Thank you in advance guys <3


Solution

  • may be this will help someone in the future :

    async function notify(){
    const connection = await db.client.acquireConnection();
    connection.query('LISTEN addedrecordp');
    connection.on('notification', (msg) => {
       console.log("got " + msg.channel + " payload " + msg.payload);
       
       })
    
    });
    
    await db.client.releaseConnection(connection);
    
    }