","name":"ServiceName","dependencies":"clearblade, log","run_user":""}", function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* })
*/
code.update = function(name, body, callback) {
var reqOptions = {
method: "PUT",
endpoint: "api/v/3/code/" + this.systemKey + "/service/" + name,
body: body,
user: this.user,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
/**
* Deletes a ClearBlade Code Service
* @method ClearBlade.Code.prototype.delete
* @param {String} name name of the ClearBlade service you wish to delete
* @param {Function} callback
* @example
* cb.Code().delete("ServiceName", function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* })
*/
code.delete = function(name, callback) {
var reqOptions = {
method: "DELETE",
endpoint: "api/v/3/code/" + this.systemKey + "/service/" + name,
user: this.user,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
/**
* Executes a ClearBlade Code Service
* @method ClearBlade.Code.prototype.execute
* @param {String} name name of the ClearBlade service
* @param {Object} params object containing parameters to be used in service
* @param {Function} callback
* @example
* cb.Code().execute("ServiceName", {stringParam: "stringVal", numParam: 1, objParam: {"key": "val"}, arrayParam: ["ClearBlade", "is", "awesome"]}, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* })
*/
code.execute = function(name, params, callback) {
var reqOptions = {
method: "POST",
endpoint: "api/v/1/code/" + this.systemKey + "/" + name,
body: params,
user: this.user,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
/**
* Retrieves a list of completed services for a system
* @method ClearBlade.Code.prototype.getCompletedServices
* @param {Function} callback
* @example
* cb.Code().getCompletedServices(function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* })
*/
code.getCompletedServices = function(callback) {
var reqOptions = {
method: "GET",
endpoint: "api/v/3/code/" + this.systemKey + "/completed",
user: this.user,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Retrieves a list of failed services for a system
* @method ClearBlade.Code.prototype.getFailedServices
* @param {Function} callback
* @example
* cb.Code().getFailedServices(function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* })
*/
code.getFailedServices = function(callback) {
var reqOptions = {
method: "GET",
endpoint: "api/v/3/code/" + this.systemKey + "/failed",
user: this.user,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Retrieves a list of services for a system
* @method ClearBlade.Code.prototype.getAllServices
* @param {Function} callback
* @example
* cb.Code().fetch(function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* })
*/
code.getAllServices = function(callback) {
var reqOptions = {
method: "GET",
endpoint: "/api/v/3/code/" + this.systemKey,
user: this.user,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
return code;
};
/**
* @class ClearBlade.User
* @returns {Object} ClearBlade.User the created User object
*/
ClearBlade.prototype.User = function() {
var user = {};
user.user = this.user;
user.URI = this.URI;
user.endpoint = "api/v/1/user";
user.systemKey = this.systemKey;
user.systemSecret = this.systemSecret;
user.callTimeout = this._callTimeout;
/**
* Retrieves info on the current user
* @method ClearBlade.User.prototype.getUser
* @param {Function} callback
* @example
* var user = cb.User();
* user.getUser(function(err, body) {
* if(err) {
* //handle error
* } else {
* //do stuff with user info
* }
* });
*/
user.getUser = function(callback) {
var reqOptions = {
method: "GET",
endpoint: this.endpoint + "/info",
user: this.user,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
/**
* Performs a put on the current users row
* @method ClearBlade.User.prototype.setUser
* @param {Object} data Object containing the data to update
* @param {Function} callback
* @example
* var newUserInfo = {
* "name": "newName",
* "age": 76
* }
* var user = cb.User();
* user.setUser(newUserInfo, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
*/
user.setUser = function(data, callback) {
var reqOptions = {
method: "PUT",
endpoint: this.endpoint + "/info",
systemKey: this.systemKey,
body: data,
user: this.user,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
/**
* Performs a post on the current users row
* @method ClearBlade.User.prototype.addUser
* @param {Object} data Object containing the data to insert
* @param {Function} callback
* @example
* var newUserInfo = {
* "email": "[email protected]",
* "password": "thePassword"
* "name": "newName",
* "age": 76
* }
* var user = cb.User();
* user.addUser(newUserInfo, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
*/
user.addUser = function(data, callback) {
var reqOptions = {
method: "POST",
endpoint: this.endpoint + "/info",
systemKey: this.systemKey,
body: data,
user: this.user,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
/**
* Performs a put on the a users row
* @method ClearBlade.User.prototype.updateUser
* @param {Object} data Object containing the data to update
* @param {Function} callback
* @example
* var newUserInfo = {
* "name": "newName",
* "age": 76
* }
* var user = cb.User();
* user.updateUser(newUserInfo, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
*/
user.updateUser = function(data, callback) {
var reqOptions = {
method: "PUT",
endpoint: "api/v/2/user/info",
systemKey: this.systemKey,
body: data,
user: this.user,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
/**
* Performs a delete on the current users row
* @method ClearBlade.User.prototype.deleteUser
* @param {Object} data Object containing the user to delete
* @param {Function} callback
* @example
* var deleteUserInfo = {
* "user_id": "theID"
* }
* var user = cb.User();
* user.deleteUser(deleteUserInfo, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
*/
user.deleteUser = function(data, callback) {
var reqOptions = {
method: "DELETE",
endpoint: this.endpoint + "/info",
systemKey: this.systemKey,
body: data,
user: this.user,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
/**
* Method to retrieve all the users in a system
* @method ClearBlade.User.prototype.allUsers
* @param {ClearBlade.Query} _query ClearBlade query used to filter users
* @param {Function} callback
* @example
* var user = cb.User();
* var query = cb.Query();
* query.equalTo("name", "John");
* query.setPage(0,0);
* user.allUsers(query, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
* //returns all the users with a name property equal to "John"
*/
user.allUsers = function(_query, callback) {
if (typeof callback === "function") {
var query;
if (callback === undefined) {
callback = _query;
query = "";
} else if (Object.keys(_query).length < 1) {
query = "";
} else {
query = "query=" + _parseQuery(_query.query);
}
ClearBlade.request(
{
method: "GET",
systemKey: this.systemKey,
systemSecret: this.systemSecret,
endpoint: this.endpoint,
qs: query,
user: this.user,
URI: this.URI
},
callback
);
} else {
logger("No callback was defined!");
}
};
user.setPassword = function(oldPass, newPass, callback) {
if (typeof callback === "function") {
ClearBlade.request(
{
method: "PUT",
endpoint: this.endpoint + "/pass",
body: { old_password: oldPass, new_password: newPass },
user: this.user,
URI: this.URI
},
callback
);
} else {
logger("No callback was defined!");
}
};
user.count = function(_query, callback) {
if (typeof callback === "function") {
var query;
if (_query === undefined || Object.keys(_query).length < 1) {
query = "";
} else {
query = "query=" + _parseOperationQuery(_query.query);
}
ClearBlade.request(
{
method: "GET",
systemKey: this.systemKey,
systemSecret: this.systemSecret,
endpoint: this.endpoint + "/count",
qs: query,
user: this.user,
URI: this.URI
},
callback
);
} else {
logger("No callback was defined!");
}
};
user.columns = function(callback) {
if (typeof callback === "function") {
ClearBlade.request(
{
method: "GET",
URI: this.URI,
endpoint: this.endpoint + "/columns",
systemKey: this.systemKey,
systemSecret: this.systemSecret,
user: this.user
},
callback
);
} else {
logger("No callback was defined!");
}
};
return user;
};
/**
* Initializes the ClearBlade messaging object and connects to a server.
* @class ClearBlade.Messaging
* @param {Object} options This value contains the config object for connecting. A number of reasonable defaults are set for the option if none are set.
*
*The connect options and their defaults are:
*
{number} [timeout] sets the timeout for the websocket connection in case of failure. The default is 60
* {Messaging Message} [willMessage] A message sent on a specified topic when the client disconnects without sending a disconnect packet. The default is none.
* {Number} [keepAliveInterval] The server disconnects if there is no activity for this pierod of time. The default is 60.
* {boolean} [cleanSession] The server will persist state of the session if true. Not avaliable in beta.
* {boolean} [useSSL] The option to use SSL websockets. Default is false for now.
* {object} [invocationContext] An object to wrap all the important variables needed for the onFalure and onSuccess functions. The default is empty.
* {function} [onSuccess] A callback to operate on the result of a sucessful connect. In beta the default is just the invoking of the `callback` parameter with the data from the connection.
* {function} [onFailure] A callback to operate on the result of an unsuccessful connect. In beta the default is just the invoking of the `callback` parameter with the data from the connection.
* {Object} [hosts] An array of hosts to attempt to connect too. Sticks to the first one that works. The default is [ClearBlade.messagingURI].
* {Object} [ports] An array of ports to try, it also sticks to thef first one that works. The default is [1337].
*
* @param {function} callback Callback to be run upon either succeessful or
* failed connection
* @example A standard connect
* var callback = function (data) {
* console.log(data);
* };
* //A connect with a nonstandard timeout
* var cb = ClearBlade.Messaging({"timeout":15}, callback);
*/
ClearBlade.prototype.Messaging = function(options, callback) {
if (!window.Paho) {
throw new Error("Please include the mqttws31.js script on the page");
}
var _this = this;
var messaging = {};
messaging.user = this.user;
messaging.URI = this.URI;
messaging.endpoint = "api/v/1/message";
messaging.systemKey = this.systemKey;
messaging.systemSecret = this.systemSecret;
messaging.callTimeout = this._callTimeout;
//roll through the config
var conf = {};
conf.userName = this.user.authToken;
conf.password = this.systemKey;
conf.cleanSession = options.cleanSession || true;
conf.useSSL = options.useSSL || false; //up for debate. ole' perf vs sec argument
conf.hosts = options.hosts || [this.messagingURI];
conf.ports = options.ports || [this.messagingPort];
if (options.qos !== undefined && options.qos !== null) {
messaging._qos = options.qos;
} else {
messaging._qos = this.defaultQoS;
}
var clientID = Math.floor(Math.random() * 10e12).toString();
messaging.client = new Paho.MQTT.Client(
conf.hosts[0],
conf.ports[0],
clientID
); //new Messaging.Client(conf.hosts[0],conf.ports[0],clientID);
messaging.client.onConnectionLost = function(response) {
console.log(
"ClearBlade Messaging connection lost- attempting to reestablish"
);
delete conf.mqttVersionExplicit;
delete conf.uris;
messaging.client.connect(conf);
};
messaging.client.onMessageArrived = function(message) {
// messageCallback from Subscribe()
messaging.messageCallback(message.payloadString);
};
// the mqtt websocket library uses "onConnect," but our terminology uses
// "onSuccess" and "onFailure"
var onSuccess = function(data) {
callback(undefined, data);
};
messaging.client.onConnect = onSuccess;
var onFailure = function(err) {
console.log("ClearBlade Messaging failed to connect");
callback(err, undefined);
};
conf.onSuccess = options.onSuccess || onSuccess;
conf.onFailure = options.onFailure || onFailure;
messaging.client.connect(conf);
/**
* Gets the message history from a ClearBlade Messaging topic.
* @method ClearBlade.Messaging.getMessageHistoryWithTimeFrame
* @param {string} topic The topic from which to retrieve history
* @param {number} last Epoch timestamp in seconds that will retrieve 'count' number of messages before that timestamp. Set to -1 if not used
* @param {number} count Number that signifies how many messages to return; 0 returns all messages
* @param {number} start Epoch timestamp in seconds that will retrieve 'count' number of messages within timeframe. Set to -1 if not used
* @param {number} stop Epoch timestamp in seconds that will retrieve 'count' number of messages within timeframe. Set to -1 if not used
* @param {function} callback The function to be called upon execution of query -- called with a boolean error and the response
*/
messaging.getMessageHistoryWithTimeFrame = function(
topic,
count,
last,
start,
stop,
callback
) {
var reqOptions = {
method: "GET",
endpoint: this.endpoint + "/" + this.systemKey,
qs:
"topic=" +
topic +
"&count=" +
count +
"&last=" +
last +
"&start=" +
start +
"&stop=" +
stop,
authToken: this.user.authToken,
timeout: this.callTimeout,
URI: this.URI
};
ClearBlade.request(reqOptions, function(err, response) {
if (err) {
execute(true, response, callback);
} else {
execute(false, response, callback);
}
});
};
/**
* Gets the message history from a ClearBlade Messaging topic.
* @method ClearBlade.Messaging.getMessageHistory
* @param {string} topic The topic from which to retrieve history
* @param {number} last Epoch timestamp in seconds that will retrieve 'count' number of messages before that timestamp. Set to -1 if not used
* @param {number} count Number that signifies how many messages to return; 0 returns all messages
* @param {function} callback The function to be called upon execution of query -- called with a boolean error and the response
*/
messaging.getMessageHistory = function(topic, last, count, callback) {
messaging.getMessageHistoryWithTimeFrame(
topic,
count,
last,
-1,
-1,
callback
);
};
/**
* Gets the message history from a ClearBlade Messaging topic.
* @method ClearBlade.Messaging.getAndDeleteMessageHistory
* @param {string} topic The topic from which to retrieve history
* @param {number} last Epoch timestamp in seconds that will retrieve and delete 'count' number of messages before that timestamp. Set to -1 if not used
* @param {number} count Number that signifies how many messages to return and delete; 0 returns and deletes all messages
* @param {number} start Epoch timestamp in seconds that will retrieve and delete 'count' number of messages within timeframe. Set to -1 if not used
* @param {number} stop Epoch timestamp in seconds that will retrieve and delete 'count' number of messages within timeframe. Set to -1 if not used
* @param {function} callback The function to be called upon execution of query -- called with a boolean error and the response
*/
messaging.getAndDeleteMessageHistory = function(
topic,
count,
last,
start,
stop,
callback
) {
var reqOptions = {
method: "DELETE",
endpoint: this.endpoint + "/" + this.systemKey,
qs:
"topic=" +
topic +
"&count=" +
count +
"&last=" +
last +
"&start=" +
start +
"&stop=" +
stop,
authToken: this.user.authToken,
timeout: this.callTimeout,
URI: this.URI
};
ClearBlade.request(reqOptions, function(err, response) {
if (err) {
execute(true, response, callback);
} else {
execute(false, response, callback);
}
});
};
messaging.currentTopics = function(callback) {
if (typeof callback === "function") {
ClearBlade.request(
{
method: "GET",
endpoint: this.endpoint + "/" + this.systemKey + "/currentTopics",
user: this.user,
URI: this.URI
},
callback
);
} else {
logger("No callback was defined!");
}
};
/**
* Publishes to a topic.
* @method ClearBlade.Messaging.prototype.publish
* @param {string} topic Is the topic path of the message to be published. This will be sent to all listeners on the topic. No default.
* @param {string | ArrayBuffer} payload The payload to be sent. Also no default.
* @example How to publish
* var callback = function (data) {
* console.log(data);
* };
* var cb = ClearBlade.Messaging({}, callback);
* cb.publish("ClearBlade/is awesome!","Totally rules");
* //Topics can include spaces and punctuation except "/"
*/
messaging.publish = function(topic, payload) {
var msg = new Paho.MQTT.Message(payload);
msg.destinationName = topic;
msg.qos = this._qos;
messaging.client.send(msg);
};
messaging.publishREST = function(topic, payload, callback) {
ClearBlade.request(
{
method: "POST",
endpoint: this.endpoint + "/" + this.systemKey + "/publish",
body: { topic: topic, payload: payload },
systemKey: this.systemKey,
systemSecret: this.systemSecret,
user: this.user,
URI: this.URI
},
callback
);
};
/**
* Subscribes to a topic
* @method ClearBlade.Messaging.prototype.subscribe
* @param {string} topic The topic to subscribe to. No default.
* @param {Object} [options] The configuration object. Options:
{Number} [qos] The quality of service specified within MQTT. The default is 0, or fire and forget.
{Object} [invocationContext] An object that contains variables and other data for the onSuccess and failure callbacks. The default is blank.
{function} [onSuccess] The callback invoked on a successful subscription. The default is nothing.
{function} [onFailure] The callback invoked on a failed subsciption. The default is nothing.
{Number} [timeout] The time to wait for a response from the server acknowleging the subscription.
* @param {function} messageCallback Callback to invoke upon message arrival
* @example How to publish
* var callback = function (data) {
* console.log(data);
* };
* var cb = ClearBlade.Messaging({}, callback);
* cb.subscribe("ClearBlade/is awesome!",{});
*/
messaging.subscribe = function(topic, options, messageCallback) {
var _this = this;
var onSuccess = function() {
var conf = {};
conf["qos"] = this._qos || 0;
conf["invocationContext"] = options["invocationContext"] || {};
conf["onSuccess"] = options["onSuccess"] || null;
conf["onFailure"] = options["onFailure"] || null;
conf["timeout"] = options["timeout"] || 60;
_this.client.subscribe(topic, conf);
};
var onFailure = function() {
alert("failed to connect");
};
this.client.subscribe(topic);
this.messageCallback = messageCallback;
};
/**
* Unsubscribes from a topic
* @method ClearBlade.Messaging.prototype.unsubscribe
* @param {string} topic The topic to subscribe to. No default.
* @param {Object} [options] The configuration object
@options {Object} [invocationContext] An object that contains variables and other data for the onSuccess and failure callbacks. The default is blank.
@options {function} [onSuccess] The callback invoked on a successful unsubscription. The default is nothing.
@options {function} [onFailure] The callback invoked on a failed unsubcription. The default is nothing.
@options {Number} [timeout] The time to wait for a response from the server acknowleging the subscription.
* @example How to publish
* var callback = function (data) {
* console.log(data);
* };
* var cb = ClearBlade.Messaging({}, callback);
* cb.unsubscribe("ClearBlade/is awesome!",{"onSuccess":function(){console.log("we unsubscribe");});
*/
messaging.unsubscribe = function(topic, options) {
var conf = {};
conf["invocationContext"] = options["invocationContext"] || {};
conf["onSuccess"] = options["onSuccess"] || function() {}; //null;
conf["onFailure"] = options["onFailure"] || function() {}; //null;
conf["timeout"] = options["timeout"] || 60;
this.client.unsubscribe(topic, conf);
};
/**
* Disconnects from the server.
* @method ClearBlade.Messaging.prototype.disconnect
* @example How to publish
* var callback = function (data) {
* console.log(data);
* };
* var cb = ClearBlade.Messaging({}, callback);
* cb.disconnect()//why leave so soon :(
*/
messaging.disconnect = function() {
this.client.disconnect();
};
return messaging;
};
/**
* @class ClearBlade.MessagingStats
* @returns {Object} ClearBlade.MessagingStats the created MessagingStats object
*/
ClearBlade.prototype.MessagingStats = function() {
var _this = this;
var messagingStats = {};
messagingStats.user = this.user;
messagingStats.URI = this.URI;
messagingStats.endpoint = "api/v/3/message";
messagingStats.systemKey = this.systemKey;
/**
* Method to retrieve the average payload size for a topic
* @method ClearBlade.MessagingStats.prototype.getAveragePayloadSize
* @param {string} topic Topic to retrieve the average payload size for
* @param {int} start Point in time in which to begin the query (epoch timestamp)
* @param {int} stop Point in time in which to end the query (epoch timestamp)
* @param {Function} callback
* @example
* cb.MessagingStats().getAveragePayloadSize("mytopic", 1490819666, 1490819676, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
* //returns {"payloadsize":28}
*/
messagingStats.getAveragePayloadSize = function(
topic,
start,
stop,
callback
) {
var reqOptions = {
method: "GET",
endpoint: this.endpoint + "/" + this.systemKey + "/averagePayload",
qs: "topic=" + topic + "&start=" + start + "&stop=" + stop,
user: this.user,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Method to retrieve the number of MQTT connections for a system
* @method ClearBlade.MessagingStats.prototype.getOpenConnections
* @param {Function} callback
* @example
* cb.MessagingStats().getOpenConnections(function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
* //returns {"connections":42}
*/
messagingStats.getOpenConnections = function(callback) {
var reqOptions = {
method: "GET",
endpoint: this.endpoint + "/" + this.systemKey + "/connections",
user: this.user,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Method to retrieve the number of subscribers for a topic
* @method ClearBlade.MessagingStats.prototype.getCurrentSubscribers
* @param {string} topic Topic to retrieve the current subscribers for
* @param {Function} callback
* @example
* cb.MessagingStats().getCurrentSubscribers("mytopic", function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
* //returns {"subscribers": 42}
*/
messagingStats.getCurrentSubscribers = function(topic, callback) {
var reqOptions = {
method: "GET",
endpoint:
this.endpoint + "/" + this.systemKey + "/subscribers/" + topic,
user: this.user,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
return messagingStats;
};
/**
* Sends a push notification
* @method ClearBlade.sendPush
* @param {Array} users The list of users to which the message will be sent
* @param {Object} payload An object with the keys 'alert', 'badge', 'sound'
* @param {string} appId A string with appId that identifies the app to send to
* @param {function} callback A function like `function (err, data) {}` to handle the response
*/
ClearBlade.prototype.sendPush = function(users, payload, appId, callback) {
if (!callback || typeof callback !== "function") {
throw new Error("Callback must be a function");
}
if (!Array.isArray(users)) {
throw new Error("User list must be an array of user IDs");
}
var formattedObject = {};
Object.getOwnPropertyNames(payload).forEach(function(key, element) {
if (key === "alert" || key === "badge" || key === "sound") {
if (!formattedObject.hasOwnProperty("aps")) {
formattedObject.aps = {};
}
formattedObject.aps[key] = payload[key];
}
});
var body = {
cbids: users,
"apple-message": JSON.stringify(formattedObject),
appid: appId
};
var reqOptions = {
method: "POST",
endpoint: "api/v/1/push/" + this.systemKey,
body: body,
user: this.user,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Gets an array of Edges on the system.
* @method ClearBlade.getEdges
* @param {function} callback A function like `function (err, data) {}` to handle the response
*/
ClearBlade.prototype.getEdges = function(_query, callback) {
let query;
if (callback === undefined) {
callback = _query;
query = {
FILTERS: []
};
query = "query=" + _parseQuery(query);
} else {
if (Object.keys(_query) < 1) {
query = "";
} else {
query = "query=" + _parseQuery(_query.query);
}
}
const reqOptions = {
method: "GET",
user: this.user,
endpoint: "api/v/2/edges/" + this.systemKey,
qs: query,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
ClearBlade.prototype.Edge = function() {
let edge = {};
edge.user = this.user;
edge.URI = this.URI;
edge.systemKey = this.systemKey;
edge.systemSecret = this.systemSecret;
/**
* Updates data for an edge
* @method ClearBlade.Edge.prototype.updateEdgeByName
* @param {String} name Specifies which edge to update
* @param {Object} object Supplies the data to update
* @param {function} callback Supplies processing for what to do with the data that is returned from the devices
* @return {Object} An object containing updated edge's data
* @example Updating edge data
* const callback = function (err, data) {
* if (err) {
* throw new Error (data);
* }
* };
*
* edge.updateEdgeByName(name, object, callback);
*/
edge.updateEdgeByName = function(name, object, callback) {
if (typeof object != "object") {
throw new Error("Invalid object format");
}
if (typeof name === "object") {
name = name.query.FILTERS[0][0].EQ[0].edge_key.split(":")[1];
}
const reqOptions = {
method: "PUT",
user: this.user,
endpoint: "api/v/3/edges/" + this.systemKey + "/" + name,
URI: this.URI
};
reqOptions["body"] = object;
ClearBlade.request(reqOptions, callback);
};
/**
* Deletes edge or edges
* @method ClearBlade.Edge.prototype.deleteEdgeByName
* @param {String} name Specifies name of which edge to delete or query object containing edge or edges to delete
* @param {function} callback Supplies processing for what to do with the data that is returned from the devices
* @example Deleting edge data
* const callback = function (err, data) {
* if (err) {
* throw new Error (data);
* }
* };
*
* edge.deleteEdgeByName(name, callback);
*/
edge.deleteEdgeByName = function(name, callback) {
if (typeof name === "object") {
const edges = name.query.FILTERS;
for (let i = 0; i < edges.length; i++) {
const edgeName = edges[i][0].EQ[0].edge_key.split(":")[1];
const reqOptions = {
method: "DELETE",
user: this.user,
endpoint: "api/v/3/edges/" + this.systemKey + "/" + edgeName,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
}
} else {
const reqOptions = {
method: "DELETE",
user: this.user,
endpoint: "api/v/3/edges/" + this.systemKey + "/" + name,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
}
};
/**
* Creates a new edge and returns the created item to the callback
* @method ClearBlade.Edge.prototype.create
* @param {Object} newItem An object that represents the new edge, requiring the fields below.
* @param {function} callback Supplies processing for what to do with the data that is returned from the edge list
* @example Creating a new edge
* var newEdge = {
token: '',
system_key: '',
system_secret: '',
* };
* var name = 'newName';
* var callback = function (err, data) {
* if (err) {
* throw new Error (data);
* } else {
* console.log(data);
* }
* };
* edge.create(newEdge, name, callback);
* //this inserts the the newEdge into the edge list
*
*/
edge.create = function(newEdge, name, callback) {
var reqOptions = {
method: "POST",
endpoint: "api/v/3/edges/" + this.systemKey + "/" + name,
body: newEdge,
user: this.user,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
edge.columns = function(callback) {
if (typeof callback === "function") {
ClearBlade.request(
{
method: "GET",
URI: this.URI,
endpoint: "api/v/3/edges/" + this.systemKey + "/columns",
systemKey: this.systemKey,
systemSecret: this.systemSecret,
user: this.user
},
callback
);
} else {
logger("No callback was defined!");
}
};
edge.count = function(_query, callback) {
let query;
if (callback === undefined) {
callback = _query;
query = {
FILTERS: []
};
query = "query=" + _parseQuery(query);
} else {
if (Object.keys(_query) < 1) {
query = "";
} else {
query = "query=" + _parseQuery(_query.query);
}
}
const reqOptions = {
method: "GET",
URI: this.URI,
qs: query,
endpoint: "api/v/3/edges/" + this.systemKey + "/count",
systemKey: this.systemKey,
systemSecret: this.systemSecret,
user: this.user
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
return edge;
};
ClearBlade.prototype.Metrics = function() {
var metrics = {};
metrics.systemKey = this.systemKey;
metrics.URI = this.URI;
metrics.user = this.user;
metrics.setQuery = function(_query) {
metrics.query = _query.query;
};
metrics.getStatistics = function(callback) {
if (!callback || typeof callback !== "function") {
throw new Error("Callback must be a function");
}
var endpoint = "api/v/3/platform/statistics/" + this.systemKey;
var query = "query=" + _parseQuery(this.query);
var reqOptions = {
method: "GET",
user: this.user,
endpoint: endpoint,
URI: this.URI,
qs: query
};
ClearBlade.request(reqOptions, callback);
};
metrics.getStatisticsHistory = function(callback) {
if (!callback || typeof callback !== "function") {
throw new Error("Callback must be a function");
}
var endpoint =
"api/v/3/platform/statistics/" + this.systemKey + "/history";
var query = "query=" + _parseQuery(this.query);
var reqOptions = {
method: "GET",
user: this.user,
endpoint: endpoint,
URI: this.URI,
qs: query
};
ClearBlade.request(reqOptions, callback);
};
metrics.getDBConnections = function(callback) {
if (!callback || typeof callback !== "function") {
throw new Error("Callback must be a function");
}
var endpoint = "api/v/3/platform/dbconnections/" + this.systemKey;
var query = "query=" + _parseQuery(this.query);
var reqOptions = {
method: "GET",
user: this.user,
endpoint: endpoint,
URI: this.URI
};
if (this.query) {
reqOptions.qs = query;
}
ClearBlade.request(reqOptions, callback);
};
metrics.getLogs = function(callback) {
if (!callback || typeof callback !== "function") {
throw new Error("Callback must be a function");
}
var endpoint = "api/v/3/platform/logs/" + this.systemKey;
var query = "query=" + _parseQuery(this.query);
var reqOptions = {
method: "GET",
user: this.user,
endpoint: endpoint,
URI: this.URI,
qs: query
};
ClearBlade.request(reqOptions, callback);
};
return metrics;
};
/**
* Creates a representation of devices
* @class ClearBlade.Device
* @classdesc It does not actually make a connection upon instantiation, but has all the methods necessary to do so.
* @example
* var device = cb.Device();
*/
ClearBlade.prototype.Device = function() {
let device = {};
device.user = this.user;
device.URI = this.URI;
device.systemKey = this.systemKey;
device.systemSecret = this.systemSecret;
/**
* Requests the named device
* @method ClearBlade.Device.prototype.getDeviceByName
* @param {String} name Used to indicate which device to get
* @param {function} callback Supplies processing for what to do with the data that is returned from the devices
* @return {Object} An object containing device's data
* @example Fetching data from device
* let returnedData = {};
* const callback = function (err, data) {
* if (err) {
* throw new Error (data);
* } else {
* returnedData = data;
* }
* };
*
* device.updateDeviceByName(name, callback);
* //this will give returnedData the value of what ever was returned from the server.
*/
device.getDeviceByName = function(name, callback) {
const reqOptions = {
method: "GET",
user: this.user,
endpoint: "api/v/2/devices/" + this.systemKey + "/" + name,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Updates data for a device
* @method ClearBlade.Device.prototype.updateDeviceByName
* @param {String} name Specifies which device to update
* @param {Object} object Supplies the data to update
* @param {Boolean} trigger Indicates whether or not should cause a trigger
* @param {function} callback Supplies processing for what to do with the data that is returned from the devices
* @return {Object} An object containing updated device's data
* @example Updating device data
* const callback = function (err, data) {
* if (err) {
* throw new Error (data);
* }
* };
*
* device.updateDevice(name, object, trigger, callback);
*/
device.updateDeviceByName = function(name, object, trigger, callback) {
if (typeof object != "object") {
throw new Error("Invalid object format");
}
object["causeTrigger"] = trigger;
const reqOptions = {
method: "PUT",
user: this.user,
endpoint: "api/v/2/devices/" + this.systemKey + "/" + name,
URI: this.URI
};
reqOptions["body"] = object;
ClearBlade.request(reqOptions, callback);
};
/**
* Deletes the named device
* @method ClearBlade.Device.prototype.deleteDeviceByName
* @param {String} name Used to indicate which device to remove
* @param {function} callback Handles response from the server
* @example Removing device
* const callback = function (err, data) {
* if (err) {
* throw new Error (data);
* } else {
* returnedData = data;
* }
* };
*
* device.deleteDeviceByName(name, callback);
* //this will remove the indicated device.
*/
device.deleteDeviceByName = function(name, callback) {
const reqOptions = {
method: "DELETE",
user: this.user,
endpoint: "api/v/2/devices/" + this.systemKey + "/" + name,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
/**
* Requests a list of all devices, unless query specifies item or a set of items.
* @method ClearBlade.Device.prototype.fetch
* @param {Query} _query Used to request a specific item or subset of items from the devices on the server. Optional.
* @param {function} callback Supplies processing for what to do with the data that is returned from the devices
* @return {Object} An array of objects
* @example Fetching data from devices
* let returnedData = [];
* const callback = function (err, data) {
* if (err) {
* throw new Error (data);
* } else {
* returnedData = data;
* }
* };
*
* device.fetch(query, callback);
* //this will give returnedData the value of what ever was returned from the server.
*/
device.fetch = function(_query, callback) {
let query;
/*
* The following logic may look funny, but it is intentional.
* I do this because it is typeical for the callback to be the last parameter.
* However, '_query' is an optional parameter, so I have to check if 'callback' is undefined
* in order to see weather or not _query is defined.
*/
if (callback === undefined) {
callback = _query;
query = {
FILTERS: []
};
query = "query=" + _parseQuery(query);
} else {
if (Object.keys(_query) < 1) {
query = "";
} else {
query = "query=" + _parseQuery(_query.query);
}
}
const reqOptions = {
method: "GET",
user: this.user,
endpoint: "api/v/2/devices/" + this.systemKey,
qs: query,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
/**
* Updates all devices, unless query specifies item or a set of items to update.
* @method ClearBlade.Device.prototype.update
* @param {Query} _query Used to request a specific item or subset of items from the devices on the server. Optional.
* @param {Object} object Supplies the data to update
* @param {Boolean} trigger Indicates whether or not should cause a trigger
* @param {function} callback Supplies processing for what to do with the data that is returned from the devices
* @return {Object} An object containing updated devices' data
* @example Updating devices' data
* const query = ClearBlade.query();
* query.equalTo('state', 'TX')
* const changes = {
* state: 'CA'
* }
* const callback = function (err, data) {
* if (err) {
* throw new Error (data);
* }
* };
* device.update(query, changes, true, callback);
*/
device.update = function(_query, object, trigger, callback) {
const filters = _query ? _query.query.FILTERS : [];
const reqOptions = {
method: "PUT",
user: this.user,
endpoint: "api/v/2/devices/" + this.systemKey,
URI: this.URI
};
reqOptions["causeTrigger"] = trigger;
reqOptions["body"] = { query: filters, $set: object };
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
/**
* Deletes device or a set of devices indicated by query.
* @method ClearBlade.Device.prototype.delete
* @param {Query} _query Used to request a specific item or subset of items from the devices on the server. Required.
* @param {function} callback Supplies processing for what to do with the data that is returned from the devices
* @example Removing devices from devices
* const query = ClearBlade.Query();
* query.equalTo('state', 'TX');
* var callback = function (err, data) {
* if (err) {
* throw new Error (data);
* } else {
* console.log(data);
* }
* };
*
* device.delete(query, callback);
* //removes every device whose 'state' attribute is equal to 'TX'
*/
device.delete = function(_query, callback) {
let query;
if (_query === undefined) {
throw new Error("no query defined!");
} else {
query = "query=" + _parseOperationQuery(_query.query);
}
const reqOptions = {
method: "DELETE",
user: this.user,
endpoint: "api/v/2/devices/" + this.systemKey,
qs: query,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
/**
* Creates a new device and returns the created item to the callback
* @method ClearBlade.Device.prototype.create
* @param {Object} newItem An object that represents the new device, requiring the fields below.
* @param {function} callback Supplies processing for what to do with the data that is returned from the device list
* @example Creating a new device
* var newDevice = {
* active_key: "deviceKey",
* allow_certificate_auth: true,
* allow_key_auth: true,
* certificate: '',
* description: '',
* enabled: true,
* keys: '',
* name: 'newDevice",
* state: 'TX',
* type: '',
* };
* var callback = function (err, data) {
* if (err) {
* throw new Error (data);
* } else {
* console.log(data);
* }
* };
* device.create(newDevice, callback);
* //this inserts the the newDevice into the device list
*
*/
device.create = function(newDevice, callback) {
var reqOptions = {
method: "POST",
endpoint: "api/v/2/devices/" + this.systemKey + "/" + newDevice.name,
body: newDevice,
user: this.user,
URI: this.URI
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
device.columns = function(callback) {
if (typeof callback === "function") {
ClearBlade.request(
{
method: "GET",
URI: this.URI,
endpoint: "api/v/3/devices/" + this.systemKey + "/columns",
systemKey: this.systemKey,
systemSecret: this.systemSecret,
user: this.user
},
callback
);
} else {
logger("No callback was defined!");
}
};
device.count = function(_query, callback) {
let query;
if (callback === undefined) {
callback = _query;
query = {
FILTERS: []
};
query = "query=" + _parseQuery(query);
} else {
if (Object.keys(_query) < 1) {
query = "";
} else {
query = "query=" + _parseQuery(_query.query);
}
}
const reqOptions = {
method: "GET",
URI: this.URI,
qs: query,
endpoint: "api/v/3/devices/" + this.systemKey + "/count",
systemKey: this.systemKey,
systemSecret: this.systemSecret,
user: this.user
};
if (typeof callback === "function") {
ClearBlade.request(reqOptions, callback);
} else {
logger("No callback was defined!");
}
};
return device;
};
/**
* @class ClearBlade.Analytics
* @returns {Object} ClearBlade.Analytics the created Analytics object
*/
ClearBlade.prototype.Analytics = function() {
var analytics = {};
analytics.user = this.user;
analytics.URI = this.URI;
analytics.systemKey = this.systemKey;
analytics.systemSecret = this.systemSecret;
/**
* Method to retrieve the average payload size for a topic
* @method ClearBlade.Analytics.prototype.getStorage
* @param {string} topic Topic to retrieve the average payload size for
* @param {int} start Point in time in which to begin the query (epoch timestamp)
* @param {int} stop Point in time in which to end the query (epoch timestamp)
* @param {Function} callback
* @example
* cb.MessagingStats().getStorage(filter, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
*/
analytics.getStorage = function(filter, callback) {
var query = "query=" + JSON.stringify(filter);
var reqOptions = {
method: "GET",
user: this.user,
endpoint: "api/v/2/analytics/storage",
qs: query,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Method to retrieve the average payload size for a topic
* @method ClearBlade.Analytics.prototype.getCount
* @param {string} topic Topic to retrieve the average payload size for
* @param {int} start Point in time in which to begin the query (epoch timestamp)
* @param {int} stop Point in time in which to end the query (epoch timestamp)
* @param {Function} callback
* @example
* cb.MessagingStats().getCount(filter, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
*/
analytics.getCount = function(filter, callback) {
var query = "query=" + JSON.stringify(filter);
var reqOptions = {
method: "GET",
user: this.user,
endpoint: "api/v/2/analytics/count",
qs: query,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Method to retrieve the average payload size for a topic
* @method ClearBlade.Analytics.prototype.getEventList
* @param {string} topic Topic to retrieve the average payload size for
* @param {int} start Point in time in which to begin the query (epoch timestamp)
* @param {int} stop Point in time in which to end the query (epoch timestamp)
* @param {Function} callback
* @example
* cb.MessagingStats().getEventList(filter, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
*/
analytics.getEventList = function(filter, callback) {
var query = "query=" + JSON.stringify(filter);
var reqOptions = {
method: "GET",
user: this.user,
endpoint: "api/v/2/analytics/eventlist",
qs: query,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Method to retrieve the average payload size for a topic
* @method ClearBlade.Analytics.prototype.getEventTotals
* @param {string} topic Topic to retrieve the average payload size for
* @param {int} start Point in time in which to begin the query (epoch timestamp)
* @param {int} stop Point in time in which to end the query (epoch timestamp)
* @param {Function} callback
* @example
* cb.MessagingStats().getEventTotals(filter, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
*/
analytics.getEventTotals = function(filter, callback) {
var query = "query=" + JSON.stringify(filter);
var reqOptions = {
method: "GET",
user: this.user,
endpoint: "api/v/2/analytics/eventtotals",
qs: query,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Method to retrieve the average payload size for a topic
* @method ClearBlade.Analytics.prototype.getUserEvents
* @param {string} topic Topic to retrieve the average payload size for
* @param {int} start Point in time in which to begin the query (epoch timestamp)
* @param {int} stop Point in time in which to end the query (epoch timestamp)
* @param {Function} callback
* @example
* cb.MessagingStats().getUserEvents(filter, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* });
*/
analytics.getUserEvents = function(filter, callback) {
var query = "query=" + JSON.stringify(filter);
var reqOptions = {
method: "GET",
user: this.user,
endpoint: "api/v/2/analytics/userevents",
qs: query,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
return analytics;
};
ClearBlade.prototype.Portal = function(name) {
var portal = {};
if (!name) {
throw new Error("Must supply a name for portal");
}
portal.name = name;
portal.user = this.user;
portal.URI = this.URI;
portal.systemKey = this.systemKey;
portal.systemSecret = this.systemSecret;
portal.fetch = function(callback) {
var reqOptions = {
method: "GET",
user: this.user,
endpoint: "api/v/2/portals/" + this.systemKey + "/" + this.name,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
portal.update = function(data, callback) {
if (typeof data != "object") {
throw new Error("Invalid object format");
}
var reqOptions = {
method: "PUT",
user: this.user,
endpoint: "api/v/2/portals/" + this.systemKey + "/" + this.name,
URI: this.URI
};
reqOptions["body"] = data;
ClearBlade.request(reqOptions, callback);
};
return portal;
};
ClearBlade.prototype.Triggers = function() {
var triggers = {};
triggers.user = this.user;
triggers.URI = this.URI;
triggers.systemKey = this.systemKey;
triggers.systemSecret = this.systemSecret;
triggers.fetchDefinitions = function(callback) {
var reqOptions = {
method: "GET",
user: this.user,
endpoint: "admin/triggers/definitions",
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Creates a ClearBlade Trigger
* @method ClearBlade.Triggers.prototype.create
* @param {String} name name of the ClearBlade trigger you wish to create
* @param {Object} def object that represents the trigger definition
* @param {Function} callback
* @example
* cb.Triggers().create("myTrigger", {"system_key":"","name":"myTrigger","def_module":"Messaging","def_name":"Subscribe","service_name":"","key_value_pairs":{"topic":"mytopic"}}, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* })
*/
triggers.create = function(name, def, callback) {
var reqOptions = {
method: "POST",
user: this.user,
body: def,
endpoint: "api/v/3/code/" + this.systemKey + "/trigger/" + name,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Updates a ClearBlade Trigger
* @method ClearBlade.Triggers.prototype.update
* @param {String} name name of the ClearBlade trigger you wish to update
* @param {Object} def object that represents the trigger definition
* @param {Function} callback
* @example
* cb.Triggers().update("myTrigger", {"system_key":"","name":"myTrigger","def_module":"Messaging","def_name":"Publish","service_name":"","key_value_pairs":{"topic":"mytopic"}}, function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* })
*/
triggers.update = function(name, def, callback) {
var reqOptions = {
method: "PUT",
user: this.user,
body: def,
endpoint: "api/v/3/code/" + this.systemKey + "/trigger/" + name,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
/**
* Deletes a ClearBlade Trigger
* @method ClearBlade.Triggers.prototype.delete
* @param {String} name name of the ClearBlade trigger you wish to delete
* @param {Object} def object that represents the trigger definition
* @param {Function} callback
* @example
* cb.Triggers().delete("myTrigger", function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* })
*/
triggers.delete = function(name, callback) {
var reqOptions = {
method: "DELETE",
user: this.user,
endpoint: "api/v/3/code/" + this.systemKey + "/trigger/" + name,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
return triggers;
};
ClearBlade.prototype.Roles = function() {
var roles = {};
roles.user = this.user;
roles.URI = this.URI;
roles.systemKey = this.systemKey;
roles.systemSecret = this.systemSecret;
roles.update = function(id, changes, callback) {
var reqOptions = {
method: "PUT",
user: this.user,
body: {
id: id,
changes: changes
},
endpoint: "api/v/3/user/roles/" + this.systemKey,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
return roles;
};
/**
* Retrieves a list of collections for a system
* @method ClearBlade.Collection.prototype.getAllCollections
* @param {Function} callback
* @example
* cb.getAllCollections(function(err, body) {
* if(err) {
* //handle error
* } else {
* console.log(body);
* }
* })
*/
ClearBlade.prototype.getAllCollections = function(callback) {
var reqOptions = {
method: "GET",
endpoint: "api/v/3/allcollections/" + this.systemKey,
user: this.user,
URI: this.URI
};
ClearBlade.request(reqOptions, callback);
};
})(window);