SlideShare a Scribd company logo
1 of 54
Download to read offline
Angular.js and Resources 
Effectively Managing Resources (Models) in Your Angular.js Based Single 
Page Application 
by Himanshu Kapoor, Front-end Engineer, Wingify 
Web: , fleon.org Twitter: @himkp, Email: info@fleon.org 
This presentation: 
http://lab.fleon.org/angularjs-and-resources/ 
https://github.com/fleon/angularjs-and-resources 
Download / Fork on GitHub:
The interwebs today... 
Single Page Apps™ 
(Today's Hot Topic) 
+ 
Front-end Frameworks 
(Our Pick: Angular.js) 
+ 
Moar Stuff 
(Package Management, AMD, Project Organisation, etc.)
Why Single Page Apps™? 
Why should you make Single Page Apps? 
They're cool 
Everybody else is doing it 
The ™ symbol on it looks cool
Why Single Page Apps™? 
The real reasons... 
Faster experience: no page refresh, on-demand data fetching 
Better runtimes: V8, spidermonkey 
Heightened expectations: new products, mobile
Well ok, lets make a Single Page App!
Thus begins our SPA Journey... 
with Angular.js + Angular UI Router + Require.js
And then, there were...
Models, Views and Controllers 
MVC 101: Angular.js Edition 
Views: rendered in the browser 
Controllers: makes your view dynamic, has the logic 
Models: plain old POJOs
POJOs as Models? 
Yes, Plain Old Javascript Objects! 
Hmm, sounds cool!
OK, here's what we got... 
The controller 
function MyCtrl($scope) { 
$scope.myModel = 'hello world'; 
} 
The view 
<h1 ng-controller="MyCtrl"> 
{{myModel}} 
</h1> 
The model 
// myModel is a POJO model
The result:
That was easy, but...
A real model, usually... 
is a rather big and complex object 
lies on the server
Ok, lets request the server! 
$http shall answer all our queries
The code... 
The controller 
function MyCtrl($scope, $http) { 
$http.get('/user').success(function (user) { 
$scope.user = user; 
}); 
} 
The view 
<h1 ng-controller="MyCtrl"> 
Hello there, {{user.name}} 
</h1> 
The model 
// HTTP GET 
{ 
"id": 1234, 
"name": "John Doe", 
"email": "johndoe@example.com" 
}
The result: 
Pretty sweet, right?
But hold on... 
Back in the real world, things aren't so simple.
The problems: 
What about multiple views? 
What about other kinds of actions (POST, PATCH, PUT, DELETE)? 
What about muliple types of models (users, posts, comments)? 
How do you handle multiple instances of the same model?
And while answering the questions, 
How do you make sure your code is: 
DRY 
Consistent 
Scalable 
Testable
And here are the answers... 
Q: What about multiple views? 
A: Abstract out the model in a service. 
Q: What about other kinds of actions? 
A: Add support for those methods in the service. 
Q: What about muliple types of models? 
A: Add support for instantiating different model types in the service.
This looks like a job for...
$resource
$resource to the rescue! 
A configurable REST adapter 
An abstraction of HTTP methods 
Ability to add custom actions 
Promise-based API 
Resources are lazily loaded
Time for some code... 
The model 
app.factory('UserResource', function () { 
return $resource('/user/:userId', { 
userId: '@id' 
}); 
}); 
The controller 
function MyCtrl($scope, UserResource) { 
$scope.user = UserResource.get({ 
id: 1 
}); 
} 
The view 
<h1 ng-controller="MyCtrl"> 
Hello there, {{user.name}} 
</h1>
The result: 
Looks no different from the previous output, 
but our code is a lot more extendible with the above logic.
The journey continues... 
Application grows bigger 
Several views, controllers and resources 
Editable content
Incoming problems that say...
Which include 
View inconsistencies 
Duplicated model functionality 
The code isn't DRY anymore
Editable content
What is it? 
Edit a model using a form 
The model gets updated in that view 
But not other views across the app 
Result: inconsistency
Inconsistencies? 
Multiple views render the same model 
Each with different values 
Example: Blog, edit author name, save
Why are inconstencies so bad? 
Contradicting/misleading information 
Worse than having no information at all
Here's an example: 
In addition to the code we already have: 
The model 
app.factory('UserResource', function () { 
return $resource('/user/:userId', { 
userId: '@id' 
}); 
}); 
The controller 
function MyCtrl($scope, UserResource) { 
$scope.user = UserResource.get({ 
id: 1 
}); 
} 
The view 
<h1 ng-controller="MyCtrl"> 
Hello there, {{user.name}} 
</h1>
Let us add another view that does something else, and something more... 
The view 
<hr> 
<h2>Edit your name</h2> 
<form ng-controller="MyEditCtrl" ng-if="user.name"> 
New name: <input type="text" ng-model="newName"> 
<button ng-click="updateName()">Save</button> 
</form> 
The controller 
function MyEditCtrl($scope, UserResource) { 
$scope.user = UserResource.get({ 
id: 1 
}); 
$scope.updateName = function () { 
$scope.user.name = $scope.newName; 
$scope.user.$save(); 
}; 
}
The result: 
Separation of concerns is good, but not if it leads to such an inconsistency.
The solution 
Maintain references of that model throughout the app 
When it changes, propagate that change to all instances
Real world inconsistencies: 
Editing a resource that is related to multiple parent resources 
Example: author ~ post, author ~ comment 
Maintaining references here isn’t so trivial
The solution: Relationships 
Relationships to handle sub-resources 
Maintaining a single reference for each unique resource / sub-resource
Relationships
Parent and children 
A property on a resource belongs to another resource 
Example: 
post.author is an AuthorResource, 
author.posts is a collection of PostResources 
Four kinds of relationships: one-to-one, one-to-many, many-to-one, many-to- 
many
Subsequent problem 
Maintaining references
References?
What are references? 
Maintaining references: Ensuring that each unique resource has only one 
instance throughout the app. 
For instance, there should be only one instance of: 
UserResource with id=1 
UserResource with id=2 
PostResource with id=1 
Q. How are such references maintained? 
A. By transforming each backend response.
Looks like a job for...
Transformer 
A service 
Input: A backend response object 
Output: A transformed mesh of resources
Example input: 
// GET /posts 
[{ 
"id": 1, 
"createdBy": { "id": 1, "name": "John Doe" } 
"title": "My First Post", 
"excerpt": "Lorem Ipsum" 
}, { 
"id": 2, 
"createdBy": { "id": 1, "name": "John Doe" } 
"title": "My Second Post", 
"excerpt": "Lorem Ipsum" 
}, { 
"id": 3, 
"createdBy": { "id": 1, "name": "Jony Ive" } 
"title": "My Third Post", 
"excerpt": "Lorem Ipsum" 
}]
The output: 
// Output obtained by transforming the response above 
var output = /* ... */; 
expect(output).toEqual(any(Array)); 
expect(output.length).toBe(3); 
expect(output[0]).toEqual(any(PostResource)) 
expect(output[1]).toEqual(any(PostResource)) 
expect(output[2]).toEqual(any(PostResource)) 
expect(output[0].createdBy).toBe(output[1].createdBy); 
expect(output[0].createdBy).toBe(output[2].createdBy);
How would such a transformation be 
possible? 
By identifying unique resources 
By getting one or more properties that can uniquely identify a resource 
For example: post.id, author.id 
By maintaining an index 
A key value pair where: 
Key: the unique identification above 
Value: the actual resource
Scalablity by abstraction 
Solving the same problem for different resources across the app 
Indexing each resource instance by a given property 
Transforming relationships between parents and children recursively 
How? 
Abstract out the core logic from configurable input 
In this particular case: the configuration is a schema
The End Result 
An abstracted base that every resource stands on that is: 
Scalable 
Testable 
Configurable 
Prevention of mixing resource management logic with the business logic 
The core logic stays at a single place
Putting it all together 
Relationships 
Resource Transformation 
Indexing / Maintaining References 
A configurable schema 
The result: ResourceManager
Resource Manager 
An abstraction of resource-related problems faced while developing VWO 
A lot of them described in this presentation 
We will be open-sourcing it soon
General Learnings 
Abstract out duplicate logic 
Abstract out configurations from the logic 
Think recursively 
Research along each step 
Take inspiration from other libraries 
(In this particular case, it was Ember-Data)
Thank You 
Questions / Comments / Suggestions? 
Reach Out 
Web: fleon.org 
GitHub: @fleon 
Twitter: @himkp 
Email: info@fleon.org 
View this presentation: 
Download / Fork on GitHub: 
http://lab.fleon.org/angularjs-and-resources/ 
http://github.com/fleon/angularjs-and-resources/

More Related Content

What's hot

Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplateGuo Albert
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentationLakshmi R
 
JQUERY TUTORIALS
JQUERY TUTORIALSJQUERY TUTORIALS
JQUERY TUTORIALSMoize Roxas
 
Deploy with Confidence using Pact Go!
Deploy with Confidence using Pact Go!Deploy with Confidence using Pact Go!
Deploy with Confidence using Pact Go!DiUS
 
Metaprogramming JavaScript
Metaprogramming  JavaScriptMetaprogramming  JavaScript
Metaprogramming JavaScriptdanwrong
 
Large-Scale JavaScript Development
Large-Scale JavaScript DevelopmentLarge-Scale JavaScript Development
Large-Scale JavaScript DevelopmentAddy Osmani
 
Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)Julie Meloni
 
Building sustainable RESTFul services
Building sustainable RESTFul servicesBuilding sustainable RESTFul services
Building sustainable RESTFul servicesOrtus Solutions, Corp
 
Selenium tests, the Object Oriented way
Selenium tests, the Object Oriented waySelenium tests, the Object Oriented way
Selenium tests, the Object Oriented wayimalittletester
 

What's hot (10)

Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplate
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
JQUERY TUTORIALS
JQUERY TUTORIALSJQUERY TUTORIALS
JQUERY TUTORIALS
 
Deploy with Confidence using Pact Go!
Deploy with Confidence using Pact Go!Deploy with Confidence using Pact Go!
Deploy with Confidence using Pact Go!
 
Jsp1
Jsp1Jsp1
Jsp1
 
Metaprogramming JavaScript
Metaprogramming  JavaScriptMetaprogramming  JavaScript
Metaprogramming JavaScript
 
Large-Scale JavaScript Development
Large-Scale JavaScript DevelopmentLarge-Scale JavaScript Development
Large-Scale JavaScript Development
 
Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)
 
Building sustainable RESTFul services
Building sustainable RESTFul servicesBuilding sustainable RESTFul services
Building sustainable RESTFul services
 
Selenium tests, the Object Oriented way
Selenium tests, the Object Oriented waySelenium tests, the Object Oriented way
Selenium tests, the Object Oriented way
 

Similar to Resources and relationships at front-end

Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN StackRob Davarnia
 
Progressive EPiServer Development
Progressive EPiServer DevelopmentProgressive EPiServer Development
Progressive EPiServer Developmentjoelabrahamsson
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web DevelopmentRobert J. Stein
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core ConceptsDivyang Bhambhani
 
Automating Performance Monitoring at Microsoft
Automating Performance Monitoring at MicrosoftAutomating Performance Monitoring at Microsoft
Automating Performance Monitoring at MicrosoftThousandEyes
 
From Backbone to Ember and Back(bone) Again
From Backbone to Ember and Back(bone) AgainFrom Backbone to Ember and Back(bone) Again
From Backbone to Ember and Back(bone) Againjonknapp
 
Managing Large Flask Applications On Google App Engine (GAE)
Managing Large Flask Applications On Google App Engine (GAE)Managing Large Flask Applications On Google App Engine (GAE)
Managing Large Flask Applications On Google App Engine (GAE)Emmanuel Olowosulu
 
Designing and Implementing a Multiuser Apps Platform
Designing and Implementing a Multiuser Apps PlatformDesigning and Implementing a Multiuser Apps Platform
Designing and Implementing a Multiuser Apps PlatformApigee | Google Cloud
 
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdfjayarao21
 
Java Technology
Java TechnologyJava Technology
Java Technologyifnu bima
 
Thinking in Components
Thinking in ComponentsThinking in Components
Thinking in ComponentsFITC
 
2013 06-24 Wf4Ever: Annotating research objects (PDF)
2013 06-24 Wf4Ever: Annotating research objects (PDF)2013 06-24 Wf4Ever: Annotating research objects (PDF)
2013 06-24 Wf4Ever: Annotating research objects (PDF)Stian Soiland-Reyes
 
2013 06-24 Wf4Ever: Annotating research objects (PPTX)
2013 06-24 Wf4Ever: Annotating research objects (PPTX)2013 06-24 Wf4Ever: Annotating research objects (PPTX)
2013 06-24 Wf4Ever: Annotating research objects (PPTX)Stian Soiland-Reyes
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)Chiew Carol
 
Rupicon 2014 Single table inheritance
Rupicon 2014 Single table inheritanceRupicon 2014 Single table inheritance
Rupicon 2014 Single table inheritancerupicon
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applicationsDivyanshGupta922023
 

Similar to Resources and relationships at front-end (20)

Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
 
Reusable Apps
Reusable AppsReusable Apps
Reusable Apps
 
Progressive EPiServer Development
Progressive EPiServer DevelopmentProgressive EPiServer Development
Progressive EPiServer Development
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web Development
 
Resume
ResumeResume
Resume
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
 
Automating Performance Monitoring at Microsoft
Automating Performance Monitoring at MicrosoftAutomating Performance Monitoring at Microsoft
Automating Performance Monitoring at Microsoft
 
From Backbone to Ember and Back(bone) Again
From Backbone to Ember and Back(bone) AgainFrom Backbone to Ember and Back(bone) Again
From Backbone to Ember and Back(bone) Again
 
Managing Large Flask Applications On Google App Engine (GAE)
Managing Large Flask Applications On Google App Engine (GAE)Managing Large Flask Applications On Google App Engine (GAE)
Managing Large Flask Applications On Google App Engine (GAE)
 
Designing and Implementing a Multiuser Apps Platform
Designing and Implementing a Multiuser Apps PlatformDesigning and Implementing a Multiuser Apps Platform
Designing and Implementing a Multiuser Apps Platform
 
Vanjs backbone-powerpoint
Vanjs backbone-powerpointVanjs backbone-powerpoint
Vanjs backbone-powerpoint
 
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdf
 
Java Technology
Java TechnologyJava Technology
Java Technology
 
Thinking in Components
Thinking in ComponentsThinking in Components
Thinking in Components
 
2013 06-24 Wf4Ever: Annotating research objects (PDF)
2013 06-24 Wf4Ever: Annotating research objects (PDF)2013 06-24 Wf4Ever: Annotating research objects (PDF)
2013 06-24 Wf4Ever: Annotating research objects (PDF)
 
2013 06-24 Wf4Ever: Annotating research objects (PPTX)
2013 06-24 Wf4Ever: Annotating research objects (PPTX)2013 06-24 Wf4Ever: Annotating research objects (PPTX)
2013 06-24 Wf4Ever: Annotating research objects (PPTX)
 
Untangling6
Untangling6Untangling6
Untangling6
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
Rupicon 2014 Single table inheritance
Rupicon 2014 Single table inheritanceRupicon 2014 Single table inheritance
Rupicon 2014 Single table inheritance
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applications
 

Recently uploaded

Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxPurva Nikam
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 

Recently uploaded (20)

Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 

Resources and relationships at front-end

  • 1. Angular.js and Resources Effectively Managing Resources (Models) in Your Angular.js Based Single Page Application by Himanshu Kapoor, Front-end Engineer, Wingify Web: , fleon.org Twitter: @himkp, Email: info@fleon.org This presentation: http://lab.fleon.org/angularjs-and-resources/ https://github.com/fleon/angularjs-and-resources Download / Fork on GitHub:
  • 2. The interwebs today... Single Page Apps™ (Today's Hot Topic) + Front-end Frameworks (Our Pick: Angular.js) + Moar Stuff (Package Management, AMD, Project Organisation, etc.)
  • 3. Why Single Page Apps™? Why should you make Single Page Apps? They're cool Everybody else is doing it The ™ symbol on it looks cool
  • 4. Why Single Page Apps™? The real reasons... Faster experience: no page refresh, on-demand data fetching Better runtimes: V8, spidermonkey Heightened expectations: new products, mobile
  • 5. Well ok, lets make a Single Page App!
  • 6. Thus begins our SPA Journey... with Angular.js + Angular UI Router + Require.js
  • 7. And then, there were...
  • 8. Models, Views and Controllers MVC 101: Angular.js Edition Views: rendered in the browser Controllers: makes your view dynamic, has the logic Models: plain old POJOs
  • 9. POJOs as Models? Yes, Plain Old Javascript Objects! Hmm, sounds cool!
  • 10. OK, here's what we got... The controller function MyCtrl($scope) { $scope.myModel = 'hello world'; } The view <h1 ng-controller="MyCtrl"> {{myModel}} </h1> The model // myModel is a POJO model
  • 12. That was easy, but...
  • 13. A real model, usually... is a rather big and complex object lies on the server
  • 14. Ok, lets request the server! $http shall answer all our queries
  • 15. The code... The controller function MyCtrl($scope, $http) { $http.get('/user').success(function (user) { $scope.user = user; }); } The view <h1 ng-controller="MyCtrl"> Hello there, {{user.name}} </h1> The model // HTTP GET { "id": 1234, "name": "John Doe", "email": "johndoe@example.com" }
  • 16. The result: Pretty sweet, right?
  • 17. But hold on... Back in the real world, things aren't so simple.
  • 18. The problems: What about multiple views? What about other kinds of actions (POST, PATCH, PUT, DELETE)? What about muliple types of models (users, posts, comments)? How do you handle multiple instances of the same model?
  • 19. And while answering the questions, How do you make sure your code is: DRY Consistent Scalable Testable
  • 20. And here are the answers... Q: What about multiple views? A: Abstract out the model in a service. Q: What about other kinds of actions? A: Add support for those methods in the service. Q: What about muliple types of models? A: Add support for instantiating different model types in the service.
  • 21. This looks like a job for...
  • 23. $resource to the rescue! A configurable REST adapter An abstraction of HTTP methods Ability to add custom actions Promise-based API Resources are lazily loaded
  • 24. Time for some code... The model app.factory('UserResource', function () { return $resource('/user/:userId', { userId: '@id' }); }); The controller function MyCtrl($scope, UserResource) { $scope.user = UserResource.get({ id: 1 }); } The view <h1 ng-controller="MyCtrl"> Hello there, {{user.name}} </h1>
  • 25. The result: Looks no different from the previous output, but our code is a lot more extendible with the above logic.
  • 26. The journey continues... Application grows bigger Several views, controllers and resources Editable content
  • 28. Which include View inconsistencies Duplicated model functionality The code isn't DRY anymore
  • 30. What is it? Edit a model using a form The model gets updated in that view But not other views across the app Result: inconsistency
  • 31. Inconsistencies? Multiple views render the same model Each with different values Example: Blog, edit author name, save
  • 32. Why are inconstencies so bad? Contradicting/misleading information Worse than having no information at all
  • 33. Here's an example: In addition to the code we already have: The model app.factory('UserResource', function () { return $resource('/user/:userId', { userId: '@id' }); }); The controller function MyCtrl($scope, UserResource) { $scope.user = UserResource.get({ id: 1 }); } The view <h1 ng-controller="MyCtrl"> Hello there, {{user.name}} </h1>
  • 34. Let us add another view that does something else, and something more... The view <hr> <h2>Edit your name</h2> <form ng-controller="MyEditCtrl" ng-if="user.name"> New name: <input type="text" ng-model="newName"> <button ng-click="updateName()">Save</button> </form> The controller function MyEditCtrl($scope, UserResource) { $scope.user = UserResource.get({ id: 1 }); $scope.updateName = function () { $scope.user.name = $scope.newName; $scope.user.$save(); }; }
  • 35. The result: Separation of concerns is good, but not if it leads to such an inconsistency.
  • 36. The solution Maintain references of that model throughout the app When it changes, propagate that change to all instances
  • 37. Real world inconsistencies: Editing a resource that is related to multiple parent resources Example: author ~ post, author ~ comment Maintaining references here isn’t so trivial
  • 38. The solution: Relationships Relationships to handle sub-resources Maintaining a single reference for each unique resource / sub-resource
  • 40. Parent and children A property on a resource belongs to another resource Example: post.author is an AuthorResource, author.posts is a collection of PostResources Four kinds of relationships: one-to-one, one-to-many, many-to-one, many-to- many
  • 43. What are references? Maintaining references: Ensuring that each unique resource has only one instance throughout the app. For instance, there should be only one instance of: UserResource with id=1 UserResource with id=2 PostResource with id=1 Q. How are such references maintained? A. By transforming each backend response.
  • 44. Looks like a job for...
  • 45. Transformer A service Input: A backend response object Output: A transformed mesh of resources
  • 46. Example input: // GET /posts [{ "id": 1, "createdBy": { "id": 1, "name": "John Doe" } "title": "My First Post", "excerpt": "Lorem Ipsum" }, { "id": 2, "createdBy": { "id": 1, "name": "John Doe" } "title": "My Second Post", "excerpt": "Lorem Ipsum" }, { "id": 3, "createdBy": { "id": 1, "name": "Jony Ive" } "title": "My Third Post", "excerpt": "Lorem Ipsum" }]
  • 47. The output: // Output obtained by transforming the response above var output = /* ... */; expect(output).toEqual(any(Array)); expect(output.length).toBe(3); expect(output[0]).toEqual(any(PostResource)) expect(output[1]).toEqual(any(PostResource)) expect(output[2]).toEqual(any(PostResource)) expect(output[0].createdBy).toBe(output[1].createdBy); expect(output[0].createdBy).toBe(output[2].createdBy);
  • 48. How would such a transformation be possible? By identifying unique resources By getting one or more properties that can uniquely identify a resource For example: post.id, author.id By maintaining an index A key value pair where: Key: the unique identification above Value: the actual resource
  • 49. Scalablity by abstraction Solving the same problem for different resources across the app Indexing each resource instance by a given property Transforming relationships between parents and children recursively How? Abstract out the core logic from configurable input In this particular case: the configuration is a schema
  • 50. The End Result An abstracted base that every resource stands on that is: Scalable Testable Configurable Prevention of mixing resource management logic with the business logic The core logic stays at a single place
  • 51. Putting it all together Relationships Resource Transformation Indexing / Maintaining References A configurable schema The result: ResourceManager
  • 52. Resource Manager An abstraction of resource-related problems faced while developing VWO A lot of them described in this presentation We will be open-sourcing it soon
  • 53. General Learnings Abstract out duplicate logic Abstract out configurations from the logic Think recursively Research along each step Take inspiration from other libraries (In this particular case, it was Ember-Data)
  • 54. Thank You Questions / Comments / Suggestions? Reach Out Web: fleon.org GitHub: @fleon Twitter: @himkp Email: info@fleon.org View this presentation: Download / Fork on GitHub: http://lab.fleon.org/angularjs-and-resources/ http://github.com/fleon/angularjs-and-resources/