JavaScript Codehooks
Codehooks are small JavaScript functions that executes inside the scope of your database. As their name indicates, your "code" “hooks” into data REST verbs (like POST
and PUT
) and let you perform custom logic, network calls and much more.
The generic format of a Codehook looks like this:
var beforePOST = function(req, res) {
res.end();
}
You'll find the code editor for the Codehooks under your Collection settings (Codehook tab), shown in the screen shot below:
Network calls from a Codehook
Codehooks can perform network calls by using the request
API. You can use this API to call any HTTP based API, including Slack.
We’ve also made it even simpler by providing a pre defined slack
API call. All you need to do in the Codehook is to call:
slack(options, callback);
The options parameter contains data for the Slack message. The example below shows how we hook into a POST
operation and send a message to Slack about the event:
function beforePOST(req, res){
var slackhookurl = "https://hooks.slack.com/services/IUYERKJ/KJH678JHG/987sdfkhj8976sdf";
var who = req.hint['#usersession'].email || 'API';
var slackopt = {
"message": `${who} created a new Customer: ${req.body.name} :smile:`,
"slackhookurl": slackhookurl,
"channel": "#projectx"
}
slack(slackopt, function(body){
res.end();
});
}
Set up your Slack URL
In order to call Slack from your Codehook, you must create an Incoming Webhook URL. Visit this url to get started https://api.slack.com/incoming-webhooks. Click on the link highlighted in the screen shot below:
Follow the instructions and generate a new Webhook URL from Slack and apply this in your code to connect properly.
After a successful connection your Slack gets populated with useful data events like the example below:
This blog post has hopefully given you an idea of how you can integrate events from your database and send them to Slack. Codehooks are a powerful tool that lets you create custom logic and perform networked integration with ease.
Read more about Codehooks in the docs here: https://restdb.io/docs/codehooks