Scripts / Monitor API calls in Node.JS node.js
Description

Adding an event script into every HTTP request your API makes will allow you to automatically log requests, handle problems with failure remediations, and more. This script allows us to capture usernames and what API key was used for the call as well as a timestamp to track exactly when this call occurred. Once we capture that information we are able to push that data into any popular database whether it be MySQL, Microsoft SQL Server, or Oracle.

To install this script, open the Scripts tab and drill down to the table (or view) endpoint associated with the API you would like to monitor. Don't forget that tracking the username, API key, and timestamp is just scratching the surface, you can also track things such as status codes and more!

Code
// To enable Node.js scripting, set the path to node in your DreamFactory .env file.
// This setting is commented out by default.
//
// DF_NODEJS_PATH=/usr/local/bin/node
//
// Use npm to install any dependencies. This script requires 'lodash.'
// Your scripts can call console.log to dump info to the log file in storage/logs.

var payload = {
    user_name: platform.session.user.email,
    api_key: platform.session.api_key,
    timestamp: (new Date()).toString()
};

platform.api.post("db/_table/TransactionHistory", {"resource": [payload]}, '', function(body, response){

    console.log(response.statusCode + " " + response.statusMessage);
    event.setResponse(JSON.parse(body), response.statusCode, 'applicaton/json');
});

Need API Advice?

Our team has advised thousands of companies around the world on API projects. Go to market faster by talking to the API experts.

jeanie

Ready to get started?