Skip to content

Instantly share code, notes, and snippets.

@jasonporritt
Last active November 18, 2015 17:37
Show Gist options
  • Save jasonporritt/da02f9662db147dbb923 to your computer and use it in GitHub Desktop.
Save jasonporritt/da02f9662db147dbb923 to your computer and use it in GitHub Desktop.
Load an Ember Data hasMany relationship after possible network request failures
OfflineModeRouteHelpers = Em.Mixin.create
robustlyLoadHasMany: (model, relationshipName) ->
new Em.RSVP.Promise (resolve, reject) =>
model.get(relationshipName).then resolve, (error) =>
internalModels = model.get("#{relationshipName}.content.canonicalState")
internalModels.forEach (internalModel) ->
internalModel._loadingPromise = null
internalModel.transitionTo('empty')
model.get(relationshipName).reload().then resolve, reject
`export default OfflineModeRouteHelpers`
`import Ember from 'ember'`
`import OfflineModeRouteHelpers from 'offline-mode-route-helpers'`
CommentsRoute = Ember.Route.extend OfflineModeRouteHelpers,
model: (params) ->
@robustlyLoadHasMany(@modelFor('blog-post'), 'comments')
`export default CommentsRoute`
@jasonporritt
Copy link
Author

This helps Ember Data deal with network failures that happened in the past. Without these helpers, this happens:

  • Suzy is on a blog post page and clicks to navigate to a route with the post's comments
  • Her network is flaky and the request fails
  • She sees an "Oops" page
  • Now with a more robust network connection she hits "back" and is taken back to the post page
  • She clicks to navigate to the comments again, and again sees the "Oops" page because Ember Data didn't try to load anything -- it just remembered the last failure.
  • Suzy has to reload the page to resolve the problem

We wanted our app to do a better job handling transitions between error states and functioning states. With the robustlyLoadHasMany, Suzy now has this experience:

  • Suzy is on a blog post page and clicks to navigate to a route with the post's comments
  • Her network is flaky and the request fails (twice, actually -- there is an immediate retry)
  • She sees an "Oops" page
  • Now with a more robust network connection she hits "back" and is taken back to the post page
  • She clicks to navigate to the comments again -- it works!
    • A first attempt to load the relationship rejects with the historical failure
    • The error handling resets model promises and states so that Ember Data is willing to load the models again
    • A second attempt to load the relationship is made, and it results in a network request because of the state changes on the related models

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment