How does Cyclr handle events?
To make code impact our methods, we need to choose when we want the code to execute.
We might want code to be executed before the request is made. Perhaps changing a parameter or the request body using a calculation.
Or, we might want code to be executed after the request. Perhaps reformatting the JSON response, or merging data.
We might even want some code to be executed when we get an error from the API, or during the authentication process.
For all of these situations, we use event handlers. An event handler is a Javascript function that you can declare to run in response to a certain event.
For instance:
function before_action() {
method_request_headers.newheader = "1";
return true;
}
This piece of code is running during the before_action event handler. This means that any code inside the function will be executed before the request is made to the API.
In the example above, we are making a brand new header called ‘newheader’ and assigning it the value of “1”.
You can also see we are returning true for the event handler. This is required in almost every event handler.
You can see the full list of Cyclr’s event handlers in our Documentation.
Cyclr Objects
The code example above showed how you can assign a header using ‘method_request_headers’. You can assign, overwrite or delete properties from ‘method_request_headers’ like any JS object.
Likewise, if you wish to access other areas of your request, you have access to:
method_request– to access the request body.method_request_headers– to access the headers.method_request_parameters– to access your QueryString parameters.method_request_MergeFields– to access all the MergeFields.
You can access different objects within different event handlers. For instance, it wouldn’t make sense for you to access the ‘method_response’ object in a ‘before_action’ handler, because you haven’t even made your request yet or received any data.
You can find all available global objects for different event handlers in our documentation. Some of the most used ones would be: