2.0.3 • Published 7 years ago

streamlive-sdk-js v2.0.3

Weekly downloads
2
License
MIT
Repository
-
Last release
7 years ago

StreamLive SDK

The StreamLive SDK is a collection of modules to help you write services for StreamLine using node.js. As such, you should add it to your dependencies using npm install streamlive-sdk-js --save.

Configuration

The SDK's behaviour can be configured by placing a file named config.json at the root of your project directory. It should contain simple keys and values, such as:

{
	"VAR_1": "config 1",
	"VAR_2": "config 2"
}

The possible values are detailed in their respective modules below — but you can extend it with your own configuration if you like.

Whenever possible, we recommend to use this configuration file over other options. This approach has the advantage of not requiring any extra work from you if you decide to publish your service on the Caldera servers.

You can interact with the configuration in your own code like this:

var conf = require('streamlive-sdk-js').conf;
var host = conf.get('HOST');

API

The API module lets you interact with the StreamLive API without hassle.

Instanciation

It works as a class that you instanciate like this:

var sdk = require('streamlive-sdk-js');
var api = new sdk.api();

The API needs to know the URL of the server it will communicate with. By default, it will look for a configuration option called SL_API_URL but you may also pass the url as an argument, for example var api = new sdk.api('https://streamlive-api-url');.

Promises

All the methods exposed by the API are asynchronous and return promises.

Tokens

Making API calls requires having a valid token. You can request one by using the requestToken() function like this:

api.requestToken();

To obtain a token, you need a Connector ID and secret provided by StreamLive. Define those in the configuration as SL_API_ID and SL_API_SECRET (or provide them as arguments to the requestToken function).

If you have obtained a token through another mean, for example one provided by a StreamLive webhook, you need to call api.setToken(token) to be abble to make subsequent calls. If you use api.requestToken(), this is taken care for you.

API calls

The API exposes the following functions:

  • getTemplates()
  • getFolders()
  • getFolderTree()
  • getWorkflows()
  • createForm(templateId, folderId, workflowId)
  • getForm(id)
  • getFormMeta(id)
  • getFormWorkflow(id)
  • updateForm(id, data)
  • addEvent(id, data)
  • updateFormWorkflow(id, data)
  • moveForm(id, folderId)
  • getActions()
  • createAction(aLabel, aUrl, aMenu)
  • delAction(id)
  • getDatasource(name)
  • setDatasource(name, data)
  • delDatasource(name)
  • getRateCount()
  • getRateLimit()
  • getRemainingHits()
  • getRatePercentage()
  • getTags()
  • addTags(tags, overwrite = false)
  • delTags(tags)

Here's an example where we retrieve a token, then make an API call:

var sdk = require('streamlive-sdk-js');
var api = new sdk.api();

//request a new token
api.requestToken()
.then(function(){
	//at this point, the token is set and ready to use.
	//make an api call
	return api.getFolders();
})
.then(function(folders){
	console.log(folders);//should print the list of folders
});

And here is another example where we already had a token, from a StreamLive webhook:

var sdk = require('streamlive-sdk-js');
var api = new sdk.api();

var token = '454.dfzf.45ze4f';//pretend you received this variable in a http call

api.setToken(token);
api.updateForm(formId, {
	atag: 'a value'
})
.then(function(){
	console.log("it worked!");
}, function(){
	console.log("didn't work :(");
});

Server

The server module helps you to get an HTTP server up and running, ready to receive requests from StreamLive or any other system. The module is a simple function, just call it to start the server.

var serverModule = require('streamlive-sdk-js').server;
var server = serverModule();

The server will listen on localhost on port 4000 by default. You can change that using the confiuration variables named HOST and PORT.

Receiving requests from StreamLive

Everything is already set up for you to receive StreamLive requests, all you need to do is decide what you want to do with it.

server.use('/submit', function(request, response){
	console.log(request.body);//contains the data from the request
	res.end('It works!');
});

This would make http://localhost:4000/submit the webhook for StreamLive. If you're not happy with the /submit part, you can change it using the SUBMIT_ROUTE configuration variable.

Since anyone can send data to this URL (at least once in production), it is important to ignore anything that is not from StreamLive. To do this, we're using signed JsonWebToken. The details are not very important, but in order for this to work, you will need a valid certificate (contact us for that). Then create a configuration variable called JWT_CERT_PATH containing the path to the certificate file.

If you'd rather not have this route set up for you, you can use the following options:

var serverModule = require('streamlive-sdk-js').server;
var server = serverModule(`{
	submit: false,		//disable the /submit route
	verifyJWT: false,	//keep the route, but disable the JWT verification
});

Both options are true by default.

Creating other routes

The object returned by the server function is an instance of connect. It has a lot of documentation, but basically you do this:

server.use('/route/name', function(request, response){
	//request contains all sorts of request information
	//response has an end() function to send the response
});

Connect is very simmilar to Express, which has a lot more documentations and plugins. In fact, express is built on top of connect.

Middleware

Middlewares for the server are simple layers that transform the incoming request before passing it on to the next middleware, until one of them ends the response. There are lot of open source middlewares that do different things; this SDK ships with 4 of them that come in handy when writting services.

JWT

The JWT middleware is used to ensure the incoming request on /submit comes from the StreamLive API. It is automatically set up when creating the server, but you can also use it stand-alone.

var middlewareJWT = require('streamlive-sdk-js').middleware.jwt;
server.use('/route', middlewareJWT('certificate'));

It takes a single argument indicating the RSA certificate that will be used to validate the incoming request. You can also provide the certificate as a base-64 encoded string in the JWT_CERT value of the configuration. You can also provide a path to the raw certificate file with the JWT_CERT_PATH value of the configuration. The SDk will try to load these options in the same order (first JWT_CERT, then JWT_CERT_PATH).

Method

You might want your route to only work when using HTTP POST, for example. That's where this middleware is useful:

var middlewareMethod = require('streamlive-sdk-js').middleware.method;
server.use('/route', middlewareMethod('POST'));//only allow POST requests on /route

If you need a lot of different routes with different methods, we recommend you use Express instead of the server shipped with the SDK, as it is a lot more powerfull when it comes to handling these sort of things.

Same host

A lot of services provide their own user interface. When that happens, it is often usefull to share some configuration information between the server and the UI.

An easy way to do this is to add a route like /config and have the server return the configuration variables that the UI needs. However, since we don't want this configuration to be publicly available, we want this route to be reserved for requests coming from the UI.

var middlewareHost = require('streamlive-sdk-js').middleware.hostName;
server.use('/route', middlewareHost('www.service-url.com'));

The host name middleware takes the full host name as argument without protocol or trailing slash. If none is provided, it falls back to using the VIRTUAL_HOST value from the configuration.

Logged In

Please note that this middleware will only work for services hosted on Caldera's servers. If you need the same functionality for a service hosted on a private server, please get in touch with us.

If a service offers a user interface, it can verify that the user accessing it is a StreamLive user. Use the loggedIn middleware to do this:

var middlewareLoggedIn = require('streamlive-sdk-js').middleware.loggedIn;
server.use('/route', middlewareLoggedIn());

This middleware will let the request pass through if the user is logged in or raise an error otherwise. The middleware does this by checking for a particular cookie, which means that you need to add a cookie parsing middleware before hand. The easiest way to do this is with the dedicated express.js package.

var cookieParser = require('cookie-parser');
var middlewareLoggedIn = require('streamlive-sdk-js').middleware.loggedIn;

server.use('/route', cookieParser());
server.use('/route', middlewareLoggedIn());

Once verified, you can access certain informations about the user through the request.jwt object. It contains information such as the user name, the workspace, etc.

If the user is not logged in, you might want to redirect him or her to the log in page. Here's an example of that:

var cookieParser = require('cookie-parser');
var middlewareLoggedIn = require('streamlive-sdk-js').middleware.loggedIn;

server.use('/route', cookieParser());
server.use('/route', middlewareLoggedIn());
server.use('/route', function checkLoginError(err, req, res, next){
	if (err.name == 'NotLoggedInError'){
		//after the log in, we want the user to be redirected back to us
		var redirectUrl = 'https://' + conf.get('VIRTUAL_HOST');
		//now redirect to the StreamLive login:
		res.redirect('https://app.streamlive.caldera.com/#/auth?r=' + encodeURIComponent(redirectUrl));
	}
	else{
		//there was another, unrelated error, so we let the server handle it
		next(err);
	}
});

By default, this middleware will also check that the user who originated the request belongs to the same workspace than the connector's one. If you want to disable this feature, you can set the checkWorkspace option to false:

server.use('/route', middlewareLoggedIn({
	checkWorkspace: false
}));

This middleware relies on the Request token middleware to properly work.

Request token

This middleware stores a JWT token and automatically refreshes it when it is about to be not valid anymore. It also takes care of setting and updating the token used by the given API object so that you never have to care about requesting tokens as it is automatically done for you.

The delayBeforeRenew option is used to refresh a token delayBeforeRenew milliseconds before it really expires to prevent issues when the token is about to expire.

var sdk = require('streamlive-sdk-js');
var api = new sdk.api();

server.use('/route', middlewareRequestToken(api, {
	delayBeforeRenew: 5*60*1000 // Defaults to 5 minutes
}));

The date stored in the JWT token is accessible from req.connectorJwt.

Persist

The last module in the SDK allows you to save data in a way that will survive a restart of your service. All your variables are stored in memory, so they will be lost if the service restarts — which is likely to happen.

The persist module simply takes an arbitrary javascript variable, and writes it to the disk. It also lets you read the same variable.

var dataToSave = {
	folder: "A folder",
	client: "Michel Michelson"
};
var persist = require('streamlive-sdk-js').persist;

//write the data
persist.set(dataToSave, function(err){
	if (err) console.log('Error persisting data');
});

//read the data
persist.get(function(err, data){
	if (err) console.log('Error reading data');
	else{
		//data now contains your variable
		console.log(data);
	}
});

The persist module uses the standard node.js pattern of not returning anything; instead, you provide a callback that is called with the result of the operation.

By default, the persistent file will be called persist.json and will be written at the root of your project. You can change this by using the PERSISTENT_STORAGE_DIR and PERSISTENT_STORAGE_FILE options.

Alternatives to persist

Persist is very minimal, and you may want to resort to a more robust solution like NeDB. You are perfectly free to do that, but make sure to always write the files that should be saved inside PERSISTENT_STORAGE_DIR — and to use the conf variable instead of hard-coding the path.

On the production server, your service might be moved around or re-installed, and any files written outside of PERSISTENT_STORAGE_DIR will be wiped in the process.

2.0.3

7 years ago

2.0.2

7 years ago

2.0.1

7 years ago

2.0.0

7 years ago

1.3.2

7 years ago

1.3.1

7 years ago

1.3.0

7 years ago

1.2.2

7 years ago

1.2.1

7 years ago

1.1.1

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago

0.10.1

7 years ago

0.10.0

7 years ago

0.9.0

7 years ago

0.8.0

7 years ago

0.7.0

7 years ago

0.6.1

7 years ago

0.6.0

7 years ago

0.5.1

7 years ago

0.5.0

7 years ago

0.4.1

7 years ago

0.4.0

7 years ago

0.3.0

7 years ago

0.2.0

8 years ago

0.1.0

8 years ago