SlideShare une entreprise Scribd logo
1  sur  35
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

Contenu connexe

Tendances

AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
Amazon Web Services Korea
 
AWS IoT 핸즈온 워크샵 - 실습 6. 긴급 데이터를 Kinesis Streams으로 보내기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 6. 긴급 데이터를 Kinesis Streams으로 보내기 (김무현 솔루션즈 아키텍트)AWS IoT 핸즈온 워크샵 - 실습 6. 긴급 데이터를 Kinesis Streams으로 보내기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 6. 긴급 데이터를 Kinesis Streams으로 보내기 (김무현 솔루션즈 아키텍트)
Amazon Web Services Korea
 
Controlling The Cloud With Python
Controlling The Cloud With PythonControlling The Cloud With Python
Controlling The Cloud With Python
Luca Mearelli
 

Tendances (19)

Micro app-framework
Micro app-frameworkMicro app-framework
Micro app-framework
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 
Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)
 
Why realm?
Why realm?Why realm?
Why realm?
 
Durable functions
Durable functionsDurable functions
Durable functions
 
Bare-knuckle web development
Bare-knuckle web developmentBare-knuckle web development
Bare-knuckle web development
 
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
 
Firebase ng2 zurich
Firebase ng2 zurichFirebase ng2 zurich
Firebase ng2 zurich
 
AWS IoT 핸즈온 워크샵 - 실습 6. 긴급 데이터를 Kinesis Streams으로 보내기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 6. 긴급 데이터를 Kinesis Streams으로 보내기 (김무현 솔루션즈 아키텍트)AWS IoT 핸즈온 워크샵 - 실습 6. 긴급 데이터를 Kinesis Streams으로 보내기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 6. 긴급 데이터를 Kinesis Streams으로 보내기 (김무현 솔루션즈 아키텍트)
 
Launching Beeline with Firebase
Launching Beeline with FirebaseLaunching Beeline with Firebase
Launching Beeline with Firebase
 
Server Side Swift with Swag
Server Side Swift with SwagServer Side Swift with Swag
Server Side Swift with Swag
 
How to send gzipped requests with boto3
How to send gzipped requests with boto3How to send gzipped requests with boto3
How to send gzipped requests with boto3
 
Inversion Of Control
Inversion Of ControlInversion Of Control
Inversion Of Control
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and Python
 
A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your App
 
Controlling The Cloud With Python
Controlling The Cloud With PythonControlling The Cloud With Python
Controlling The Cloud With Python
 
Azure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best PracticesAzure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best Practices
 

Similaire à Parse Advanced

CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
slicejs
 

Similaire à Parse Advanced (20)

The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Into The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api'sInto The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api's
 
C# 6.0
C# 6.0C# 6.0
C# 6.0
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
GlueCon 2016 - Threading in JavaScript
GlueCon 2016 - Threading in JavaScriptGlueCon 2016 - Threading in JavaScript
GlueCon 2016 - Threading in JavaScript
 
Serverless archtiectures
Serverless archtiecturesServerless archtiectures
Serverless archtiectures
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
Serverless Ballerina
Serverless BallerinaServerless Ballerina
Serverless Ballerina
 
SharePoint Conference 2018 - APIs, APIs everywhere!
SharePoint Conference 2018 - APIs, APIs everywhere!SharePoint Conference 2018 - APIs, APIs everywhere!
SharePoint Conference 2018 - APIs, APIs everywhere!
 
Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
 
Quick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase ServerQuick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase Server
 
SharePoint Saturday Belgium 2018 - APIs, APIs everywhere!
SharePoint Saturday Belgium 2018 - APIs, APIs everywhere!SharePoint Saturday Belgium 2018 - APIs, APIs everywhere!
SharePoint Saturday Belgium 2018 - APIs, APIs everywhere!
 

Dernier

Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Cara Menggugurkan Kandungan 087776558899
 

Dernier (6)

Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & Examples
 
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
 
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s Tools
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and Layouts
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdf
 

Parse Advanced

  • 2. HELL YEAH! Typical Mobile App Database REST APIs Server + Users + Security Networking Caching The Fun Stuff! no no no no no
  • 3. Quick Recap S What is Parse? Advantages. Features. S Parse Object S User Management S Queries S Security – ACLs/Roles S Files
  • 4. 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
  • 5. Parse android SDK gives us a huge amount of options to interact with our data. But what if we want more?
  • 6.
  • 7. 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
  • 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
  • 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 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
  • 35. Q & A

Notes de l'éditeur

  1. Show Khelo old Code
  2. checkIfCustomersOnCourts
  3. Look at dir structure once
  4. Show safari. refreshSportDetailsForSelectedSport