@datorama/sdk
v0.70.15
Published
Datorama Javascript SDK
Downloads
644
Maintainers
Keywords
Readme
SDK
Usage
Basic Setup
The Datorama SDK for JavaScript doesn't have any standalone files that need to be downloaded or installed, instead you simply need to include a short piece of regular JavaScript in your HTML that will asynchronously load the SDK into your pages. The async load means that it does not block loading other elements of your page.
<script>
window.datoAsyncInit = function() {
DA.init();
};
(function(d, s, id){
var js, dajs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://cdn.jsdelivr.net/npm/@datorama/sdk";
dajs.parentNode.insertBefore(js, dajs);
}(document, 'script', 'datorama-jssdk'));
</script>
This code will load and initialize the SDK.
The method DA.init()
is used to initialize and setup the SDK.
All other SDK methods must be called after this one, because they won't exist until you do.
Consuming the SDK
There are two options to consumes the SDK:
- By injecting the following JS snippet into the
body
:
<script>
(function(d, s, id){
var js, dajs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://cdn.jsdelivr.net/npm/@datorama/sdk";
dajs.parentNode.insertBefore(js, dajs);
}(document, 'script', 'datorama-jssdk'));
</script>
The src
attribute is point to the latest version of the SDK, stored in a CDN.
It's recommended to consume a specific version of the SDK,
to avoid from breaking changes in future release. Just add an @ sign followed by the version number.
For example:
https://cdn.jsdelivr.net/npm/@datorama/[email protected]
- You can consume the SDK as a module, using ES6 imports, requireJS or any other module system.
Installing with NPM:
$ npm install @datorama/sdk --save
Installing with Yarn:
$ yarn add @datorama/sdk
init
Options
| Function | Default Value | Description |
| ------ | ------ | ------ |
| token | undefined
| An optional API token (TBD) |
| logger | undefined
| A custom logger implementation. Use this to print debug logs. |
| promiseBased | false
| Whether you'd like to work with promises, rather than callbacks |
Debugging
Pass a custom logger implementation to the init
function.
In the following example, we're using console.log to print debug messages:
DA.init({
logger: {
log: console.log
}
});
Events
You can subscribe to different events from the SDK, such as the APP events.
All events are asynchronous. When subscribing to an event, pass a callback function as the last parameter. This function will be invoked once the event has emitted.
The callback functions should be in the style of node callback (AKA "nodeback"):
function myCallback(error, data): void {
}
APP API
| Function | Description | | ------ | ------ | | onLoad | Subscribe to the loaded event. | | install | Finish installation |
onLoad event
Use the onLoad
event to notify when the application has loaded.
DA.init();
DA.app.onLoad(function (error, data) {
console.log(`Run mode: ${data.mode}`); // print INSTALL / RUN
console.log(`App configuration: ${data.config}`); // print the app stored configuration
console.log(`App: ${data.metadata}`); // print the app instance properties
console.log(`Params: ${data.params}`); // print context parameters (accountId, workspaceId, userId)
})
send install
event
Use the install
function to finish the installation of your application.
The function received an optional configuration object for this application instance.
You can use the same config later, in the RUN mode.
const myCustomConfig = {
installDate: new Date()
};
// save a custom configuration in the app instance,
// and complete the installation.
DA.app.install({
config: myCustomConfig
})
You can retrieve the same configuration later, by subscribing to the onLoad
event (Run mode only):
DA.app.loaded(function (error, data) {
console.log('The app installed at: ' + data.config.installDate);
});
REST API
In order to fetch data from Datorama, use the api service.
Example:
// GET request
DA.api.get("/v1/resource", function(error, response) {
if (error) {
console.log("Error: " + error);
}
else {
console.log(response.data);
}
});
// POST request
DA.api.post("/v1/resource", "POST", {name: 'your_name'}, function(error, response){
});
// PUT request
DA.api.put("/v1/resource", "PUT", {name: 'your_name'}, function(error, response){
});
The above methods are just a shorthand for the request
method`:
// as arguments
DA.api.request(path: string, method: "GET" | "POST" | "PATCH", params: {}, callback);
// or as a single object
DA.api.request({
path: string,
method: "GET" | "POST" | "PATCH",
params: {}
}, callback);
Promise Based API
By default, subscription to different asynchronous APIs can be done by passing a callback function, as mentioned earlier. However, working with Promises can be slightly easier when chaining multiple APIs calls, into one.
In order to activate this feature, just set promiseBased = true
in the init
function.
From now on, you can avoid passing a callback function, and use the Promise API.
In the following example, we instantiate the SDK with the promiseBased
flag set to true
, and subscribing to the onLoad
event, as we seen earlier, but with a Promise:
DA.init({
promiseBased: true
});
DA.app.onLoad().then(function(data){
// app loaded successfully!
}, function(error){
// something went wrong :(
});
The real strange of promise shine when chaining multiple asynchronous calls:
const requests = [DA.api.get('first_request'), DA.api.get('second_request')];
Promise.all(requests).then(function(response){
console.log(response[0]); // print the response of the first_request
console.log(response[1]); // print the response of the second_request
}).catch(function(error){
// something went wrong :(
});
Mix callbacks and Promises:
When you choose to work with promises, you can still working with callbacks as well, as long as you pass the callback function. Consider the following example:
DA.init({
promiseBased: true
});
// using promise
DA.api.get('v1/get/1').then(function(response){
console.log('hello from the promise!');
});
// using callback
DA.api.get('v1/get/2', function(error, response){
console.log('hello from the callback!');
});
Cross Browser Compatability
Promises are a great option when working with many asynchronous calls. Under the hood, the SDK is using the native browser implementation for Promises, which supports only evergreen browsers. If you wish to support legacy browsers (IE11), just add a Promise polyfill: https://github.com/paulmillr/es6-shim
More on Promises and browser compatabillity: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Working with Mock Data
It's possible to work with mock data, when the SDK running inside Datorama, and even when it's standalone. Any options you set in the mock, will override the default parameters.
The mock should be used only when:
- You want to test your code before the deployment to datorama. Make sure this is only activated in your DEV environment.
- You want to provide mock for the
requests
you already have in your app - for the demo mode.
Mock Interface:
The SDK init
function expose a mock
parameter which provides the following interface:
| Field | Description |
| ------ | ------ |
| appLoad | Override the onLoad
response. |
| requests | Provides a mock data for API requests. |
Mocking appLoad
Use the appLoad
when you want to override the received app configuration you get via DA.app.onLoad
.
DA.init({
mock: {
appLoad: {
mode: 'RUN' | 'INSTALL' | 'DEMO', // the the app mode to install
config: {}, // override the saved configuration
params: {}, // override the app's params (workspaceId, accountId, userId)
metadata: {} // override the app instance
}
}
});
Example
DA.init({
mock: {
appLoad: {
mode: 'INSTALL',
config: {
firstName: 'Amit'
}
}
}
});
DA.app.onLoad(function(err, data){
console.log(data.mode); // print to the console: 'INSTALL'
console.log(data.config); // print to the console: {firstName: 'Amit'}
})
Mocking HTTP Requests
Mocking HTTP requests can be done via the requests
field, in the mock
configuration object.
This is useful for simulate HTTP calls - it means you don't have to change your code in order to test your application, or the best option - you can use the mock to provide a demo to your users, without changing your code!
Let's see it in action:
DA.init({
mock: {
requests: {
'v1/get/my/data': {
success: {
status: 200,
data: 'here is your data'
}
}
}
}
});
DA.api.get('v1/get/my/data', function(err, data){
console.log(data); // print to the console: here is your data
});
Set mock for different HTTP methods (such as POST and PUT), can be done in the same way:
DA.init({
mock: {
requests: {
'v1/post/my/data POST {id: 1}': {
success: {
status: 200,
data: 'success'
}
},
'v1/put/my/data PUT {id: 1, field: 'new_value'}': {
success: {
status: 200,
data: 'success'
}
}
}
}
});
This is all you need in order to set a mock.
More Advnaced Examples
Sometimes you want to mock complex request body, and use them in your POST/PUT methods. Using the string convention (as mentioned above) is not always comfterble. It's possible to use a complex object as the request key, rather then a string. Let's see it in action:
DA.init({
// we store the requests in JS map, so we'll be able to use a key object
var requestsMock = new Map();
// define our mocks
requestsMock.set({
path: 'v1/post/my/data',
method: 'POST',
params: {
id: 1,
firstName: 'Amit',
lastName: 'Bh',
location: {
city: 'Shoham',
zipCode: 123456
}
}
}, {
success: {
status: 200,
data: 'success'
}
});
mock: {
requests: requestsMock
}
});
Fail Response
Sometimes, you want to simulate failed API requests. In order to achive this behaviour, you can use the error
field:
DA.init({
mock: {
requests: {
'v1/post/my/data POST {id: 1}': {
error: {
status: 500,
data: 'Something went wrong :('
}
}
}
}
});
This will make your request to fail, with the status code of 500
, and the following body:
Something went wrong :(
Development
Install
$ npm install
Build Dev
$ npm start
Build Production
$ npm run build
To update the version see instructions here: https://datorama.atlassian.net/wiki/spaces/APPS/pages/811106334/Publishing+a+New+APP+SDK+Version