S
Parse Advanced
Tushar Acharya
MUTUAL MOBILE
HELL
YEAH!
Typical Mobile App
Database REST APIs Server
+ Users
+ Security
Networking Caching The Fun Stuff!
no
no
no
no
no
Quick Recap
S What is Parse? Advantages. Features.
S Parse Object
S User Management
S Queries
S Security – ACLs/Roles
S Files
What’s up next
S Cloud Code
S Basic Operations
S Queries
S CommonJS Modules
S JavaScript Promises
S Background Jobs
S Bolts on Android
Parse android SDK gives us a huge amount of options to
interact with our data.
But what if we want more?
Why cloud code?
S Complex operations
S Triggers for each object cycle
S Common code for various platforms
S 3rd party modules
S Data consistency
Directory Structure
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");
});
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
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();
}
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
Pyramid of DOOM
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
});
Promises
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.
Promises
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!
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?
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.
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);
});
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
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.
});
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.");
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!
});
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
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!);
})
});
Background Jobs
Background Jobs
Background Jobs
Background Jobs
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
Cloud Modules
experts.js
var googleExperts = [’Mustafa', ’Gervin', ’Daniel', ’David’];
exports.isGoogleExpert = function(name) {
return googleExperts.indexOf(name) !== -1;
}
main.js
var experts = require('cloud/experts.js');
experts.isGoogleExpert(’Pavan'); // returns false
experts.isGoogleExpert(’Mustafa'); // returns true
experts.googleExperts; // undefined
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
Q & A

Parse Advanced

  • 1.
  • 2.
    HELL YEAH! Typical Mobile App DatabaseREST APIs Server + Users + Security Networking Caching The Fun Stuff! no no no no no
  • 3.
    Quick Recap S Whatis Parse? Advantages. Features. S Parse Object S User Management S Queries S Security – ACLs/Roles S Files
  • 4.
    What’s up next SCloud Code S Basic Operations S Queries S CommonJS Modules S JavaScript Promises S Background Jobs S Bolts on Android
  • 5.
    Parse android SDKgives us a huge amount of options to interact with our data. But what if we want more?
  • 7.
    Why cloud code? SComplex operations S Triggers for each object cycle S Common code for various platforms S 3rd party modules S Data consistency
  • 8.
  • 9.
    Cloud Functions S ActualAPI 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 Callcloud 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 Enablesus 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 valuethat 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
  • 13.
  • 14.
    Promises S A simplecloud 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 });
  • 15.
  • 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.
  • 17.
  • 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 – ErrorHandling 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 – ErrorHandling 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 – ErrorHandling 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 Allof 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 setTimeoutpromisified .. 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 BGjobs 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!); }) });
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
    Cloud Modules S CloudCode 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
  • 33.
    Cloud Modules experts.js var googleExperts= [’Mustafa', ’Gervin', ’Daniel', ’David’]; exports.isGoogleExpert = function(name) { return googleExperts.indexOf(name) !== -1; } main.js var experts = require('cloud/experts.js'); experts.isGoogleExpert(’Pavan'); // returns false experts.isGoogleExpert(’Mustafa'); // returns true experts.googleExperts; // undefined
  • 34.
    Bolts for Android SKeep 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
  • 35.

Editor's Notes

  • #14 Show Khelo old Code
  • #25 checkIfCustomersOnCourts
  • #33 Look at dir structure once
  • #35 Show safari. refreshSportDetailsForSelectedSport