9. Cloud Functions
S Actual API end points on server
S Written in Javascript
S Allows asynchronous response
S Typical cloud function -
Parse.Cloud.define("hello", function(request, response) {
if(request.isError)
response.error("No Hello for you");
else response.success("Hello World");
});
10. Cloud Functions
S Call cloud code APIs using ParseCloud class -
Map<String, Object> params = new HashMap<>();
params.put("isError", true);
ParseCloud.callFunctionInBackground("hello", params, callback);
S Params can be of any data type supported by Parse.
S Response – either data or error, is handled in callback.
S Synchronous version - callFunction
11. Object Triggers
S Enables us to write hooks during object saving and
destroying.
S beforeSave and afterSave are triggered for object.save();
S beforeDelete and afterDelete are triggered for
object.destroy();
Parse.Cloud.afterSave(”ToDoItem", function (request) {
if (request.object.existed() == false) {
request.object.setACL(getDefaultAcl(request.user));
request.object.save();
}
12. Promises
S A value that may not be available yet, but will be resolved
at some point in future.
S Allows us to write asynchronous code in a more
synchronous fashion.
S The only interface requirement of a Promise is having a
function called then, which can be given callbacks to be
called when the promise is fulfilled or has failed.
S Better error handling
14. Promises
S A simple cloud code to save an object
object.save({
success: function(object) {
},
error: function(object, error) {
}
});
S In the new Promise paradigm, that same code would become
object.save().then(
function(object) { //Success
},
function(error) { //Failure
});
16. Promises
S Actually Yes. But the real power of promises is when
multiple of them are chained together.
S Calling promise.then(func) returns a new promise, which is not
fulfilled until func has completed.
S If a callback supplied to then returns a new promise, then
the promise returned by then will not be fulfilled until the
promise returned by the callback is fulfilled.
18. Promises
S Log in find an object update it
Parse.User.logIn("user", "pass", {
success: function(user) {
query.find({
success: function(results) {
results[0].save({ key: value }, {
success: function(result) {
console.log(“YAYY!”);
}
});
}
});
}
});
S All this even without any error handling code!
19. Promises
S Log in find an object update it
Parse.User.logIn("user", "pass").then(function(user) {
return query.find();
}).then(function(results) {
return results[0].save({ key: value });
}).then(function(result) {
// the object was saved.
});
S What about error handling?
20. Promises – Error Handling
S Error handling in every promise
Parse.User.logIn("user", "pass").then(function(user) {
return query.find();
}, function (error) {
console.error("Login Failed: "+error);
}).then(function(results) {
return results[0].save({ key: value });
}, function (error) {
console.error("Query Failed: "+error);
}).then(function(result) {
// the object was saved.
}, function (error) {
console.error("Save Failed: "+error);
});
S Things are getting messy again.
21. Promises – Error Handling
S Collective error handling
Parse.User.logIn("user", "pass").then(function(user) {
return query.find();
}).then(function(results) {
return results[0].save({ key: value });
}).then(function(result) {
// the object was saved.
}, function (error) {
console.error("Operation Failed: "+error);
});
22. Promises – Error Handling
S If a Promise in a chain fails, all of the success callbacks
after it will be skipped until an error callback is
encountered.
S The error callback can transform the error, or it can
handle it by returning a new Promise.
S Parse.Promise.error
S Parse.Promise.as
23. Complex Error Handling
query.find().then(function(students) {
students[0].set("valedictorian", true);
// Force this callback to fail.
return Parse.Promise.error("There was an error.");
}).then(function(valedictorian) {
// Now this will be skipped.
return query.find();
}).then(function(students) {
// This will also be skipped.
return students[1].save({"salutatorian", true});
}, function(error) {
// This error handler WILL be called. error will be "There was an error.".
// Let's handle the error by returning a new promise.
return Parse.Promise.as("Hello!");
}).then(function(hello) {
// Everything is done!
}, function(error) {
// This isn't called because the error was already handled.
});
24. Custom Promises
S All of parse methods returns a promise.
S What if you need to create your own method?
S Parse.Promise class
var promise = new Parse.Promise();
promise.resolve("The good result.");
promise.reject("An error message.");
25. Custom Promises
S setTimeout promisified .. promified -
var delay = function(millis) {
var promise = new Parse.Promise();
setTimeout(function() {
promise.resolve();
}, millis);
return promise;
};
S Usage
delay(100).then(function() {
// This ran after 100ms!
});
26. Background Jobs
S BG jobs are schedulable parse cloud functions.
S Mainly used in operations which run independent of API
calls
S For ex: Payment expiration, Redundant data cleanup, etc
S Created using Parse.Cloud.job
S Schedule is created using Dashboard at parse.com
27. Background Jobs
Parse.Cloud.job("clearHeldSlots", function (request, status) {
Parse.Cloud.useMasterKey();
var d = new Date();
d.setTime(d.getTime() - constants.TRANSACTION_EXPIRY_TIME);
var blockedSlotsQuery = new Parse.Query("BlockedSlot");
blockedSlotsQuery.equalTo("isHoldingForBooking", true);
blockedSlotsQuery.lessThanOrEqualTo("createdAt", d);
blockedSlotsQuery.find().then(function (blockedSlots) {
if (blockedSlots != undefined && blockedSlots != null) {
return Parse.Object.destroyAll(blockedSlots);
}
}).then(function () {
status.success();
}, function (error) {
status.error(“Job Failed!);
})
});
32. Cloud Modules
S Cloud Code supports breaking up JavaScript code into
modules.
S Each module is a separate JS file and all the APIs and
data it wants to expose should be added to exports
variable.
S Use require(“path_to_module.js”) to use that module.
S 3rd party modules available for integration with services.
S Ex: underscore, stripe, mailgun
34. Bolts for Android
S Keep long-running operations off of the UI thread.
S If several inter-dependent operations execute in
background, its hard to coordinate.
S Almost all internal Parse Android SDK APIs use bolts
S continueWithTask and onSuccessTask
S continueWith and onSuccess