Skip to content

Instantly share code, notes, and snippets.

@LosantGists
Created September 13, 2016 21:16
Show Gist options
  • Save LosantGists/a45a0826933ed81db3693430a6ac8649 to your computer and use it in GitHub Desktop.
Save LosantGists/a45a0826933ed81db3693430a6ac8649 to your computer and use it in GitHub Desktop.
PubNub to Losant Integration Example
/*
Insert this code in your "Losant REST" PubNub Event Handler.
Make sure the channel name is "losant_rest"
*/
export default (request) => {
// we need this module to make our requests to the Losant API
const xhr = require('xhr');
// put all connection credentials here
const applicationId = 'MY_APPLICATION_ID';
const deviceId = 'MY_DEVICE_ID';
const accessKey = 'MY_ACCESS_KEY';
const accessSecret = 'MY_ACCESS_SECRET';
// settings for our first API call, which is to obtain an access token
const authUrl = `https://api.losant.com/auth/device`;
const authOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: {
deviceId: deviceId,
key: accessKey,
secret: accessSecret
}
};
// let's attempt to authenticate.
return xhr.fetch(authUrl, authOptions).then((authRes) => {
// get our auth token out of the response
const body = JSON.parse(authRes && authRes.body);
const token = body && body.token;
// to demonstrate how we can mutate a message while in flight, let's send our flipped random number
const flippedNumber = 1 - request.message;
// here are the settings for the API call to report our device's state
const stateUrl = `https://api.losant.com/applications/${applicationId}/devices/${deviceId}/state`;
const stateOptions = {
method: "POST",
headers: {
"Authorization": 'Bearer '+ token, // required to report our device's state
"Content-Type": "application/json",
"Accept": "application/json"
},
body: {
data: {
randNumInverted: flippedNumber, // our mutated message
source: "rest" // here is a static value we're adding on to our request
}
}
};
// make the call!
return xhr.fetch(stateUrl, stateOptions);
}).then((stateRes) => {
console.log('send state response ok.',stateRes);
// all done!
return request.ok();
})
.catch((err) => {
console.log('send state error!',err);
return request.abort();
});
}
/*
Insert this code in your "Losant Webhook" PubNub Event Handler.
Make sure the channel name is "losant_webhook"
*/
export default (request) => {
// we need this module to make our request to the webhook
const xhr = require('xhr');
// put the URL for the webhook you created earlier here
const webhookUrl = "MY_WEBHOOK_URL";
const options = {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: {
randNum: request.message, // this is our random number from the original message
source: 'webhook' // here is a static value we're adding on to our request
}
};
// send our data to Losant via webhook
return xhr.fetch(webhookUrl, options).then((res) => {
console.log('webhook response ok.',res);
return request.ok();
})
.catch((err) => {
console.log('webhook error!',err);
return request.abort();
});
}
/*
Insert this code into your "Random Number" PubNub Event Handler.
Make sure the channel name is "random_number"
*/
export default (request) => {
// require this to so we can fire() our message to other channels
const pubnub = require('pubnub');
// let's generate a random number between 0 and 1.
// this will be our example message
const randomNumber = Math.random();
// here are our two pubnub fire() calls
const webhookCall = pubnub.fire({
"channel": "losant_webhook", // make sure this matches the channel you set up in your webhook event handler
"message": randomNumber
});
const apiCall = pubnub.fire({
"channel": "losant_rest", // make sure this matches the channel you set up in your webhook event handler
"message": randomNumber
});
// we'll send both requests at the same time
// one will be a webhook call, the other will be a direct call to the Losant API
// both will include the random number generated above as the message
// when both succeed (or when either fails), we'll log the result.
// note that the webhook and API calls could fail (if an error is returned in the response) and the Promise will still return OK
return Promise.all([webhookCall, apiCall])
.then((values) => {
console.log('Promises succeeded.', values);
return request.ok();
})
.catch((err) => {
console.log('Promises error!', err);
return request.abort();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment