简体   繁体   English

有没有办法在 knex.js PostgreSQL 上使用“听”?

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


i have a table in PostgreSQL database called "posts". 我在 PostgreSQL 数据库中有一个名为“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:所以我创建了这个 notify_changes_of_posts_Table 函数像这样:

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

and also i created the event trigger Like so:我还创建了事件触发器,如下所示:

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

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.请注意,服务器 Nodejs 使用 knex.js 工具连接到数据库。

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.所以为了获得通知,我需要使用“ LISTEN ”,但我不知道如何实现,我查看了 knex.js 的官方文档,找不到与此主题相关的任何信息。

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提前谢谢你们<3

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM