I am making a Slack bot in node. I have a website with a MySQL database, and whenever someone makes a new post, a new row is added to the database. I want to send a message in Slack when a new post is created, but I can't figure out how to trigger some code when a new line is added.
I am using Node, the MySQL plugin, and the Slack API, but that last part shouldn't matter.
I just need a code snippet that can trigger some other code whenever there is a new row in a specific table.
Thanks in advance!
The easiest solution is to track events by tailing MYSQL BIN logs https://www.npmjs.com/package/mysql-events
This npm package can track insert, update, and delete events.
Alternatively, you can setup MYSQL triggers for various events(INSERT in your case). But there is a limitation for the MYSQL triggers, you cannot trigger NodeJs code but it can only run SQL stored procedure or queries. You can create one postEventLog table and setup after insert trigger on it for each inserted row.
https://www.mysqltutorial.org/mysql-triggers/mysql-after-insert-trigger/
Then you can keep checking for new changes in the table at a specified interval.
In case, you don't want an extra table. Keep polling for new changes in the post table, if found new records then perform your custom logic for calling slack API/ notify the client.