Global exception handling for REST calls in Ember-CLI - rest

In my ember-cli app I use a token based approach to communicate with a secured REST interface on the server side. As tokens expire after some time, I would like to realize the following behaviour:
As soon as the client tries to access the REST service with an expired token, I would like the user to be redirected to the login screen.
Right now I use the 'catch' function on the store's find method while fetching data in the route's model callback. This works quite well. As a matter of fact, there are more REST invocations than the ones that refer to the model store.
What would be the best practice to deal with this situation? In what place should I implement the (exception) handling? As this seems to be a crosscutting concern, I'd like to implement it in a central place.
I prefer to follow an optimistic approach, thus not checking the validity of the token on each and every transition. It will be sufficient if the redirect will take place the moment the application tries to communicate with the REST interface (ie as soon as it gets the error message from the server).
Thanks

You may want to consider the global jquery hooks so you can respond to an Auth fail uniformly. See:
http://api.jquery.com/category/ajax/global-ajax-event-handlers/
It's up to you if you want to set window.location or lookup your application controller and use transitionToRoute() for switching to the login route. Make sure that if you use Ember functions to put your code in an Ember.run.once() from your jquery hook function so it occurs on the Ember run loop.
You could also consider using Ember SimpleAuth (which kind of locks you into its paradigm) or even better and a safer long term priposal IMO, doing it from scratch by first following these tutorials:
- http://coderberry.me/blog/2013/07/08/authentication-with-emberjs-part-1/
- http://coderberry.me/blog/2013/07/08/authentication-with-emberjs-part-2/
And then this which is newer and incorporates the above tutorials:
- http://webcloud.info/blog/2014/04/07/emberjs-authentication-the-right-way-javascript-version/

Related

URLSession cache only

Sometimes I want to get data from the cache only when using URLSession. For example when quickly scrolling in a UITableView, I would like to show images that are already in the cache, but do not fire any HTTP requests. Images are just an example could be anything.
So I'm currently looking into URLSession's CachePolicy but it doesn't support an option to only get valid (not expired, etc) data from cache.
I can look into the URLCache myself, but this also of course returns data that might be expired. Is there some API that can validate a CachedURLResponse? Because then I can do it myself. Or do I have to implement the validating myself.
That's a fairly unusual request. Normally, you're either writing code to operate in an offline mode (in which case you want to pull from the cache whether the cached results are still valid or not) or you are online (in which case you want to fetch new data if it isn't valid).
I would encourage you to really think long and hard about whether you really want to force cache validation if you aren't firing network requests.
That said, if you really want that behavior, there are two ways you can do it:
Use NSURLRequestReturnCacheDataDontLoad and validate the age of the cached response yourself.
Perform the request in a custom session, use NSURLRequestUseProtocolCachePolicy, and in that session, install a custom NSURLProtocol subclass that overrides initWithTask:cachedResponse:client: and startLoading, and calls URLProtocol:didFailWithError: on the provided client at the top of its startLoading method.
The second approach is probably the best option, because you don't have to worry about knowing all the esoteric rules for cache validation. By making the actual load fail, the cache will work normally, but as soon as it actually would start making a network request, your custom protocol prevents that from happening. And because you'll register the protocol only in that specific session (via the protocolClasses array on the session configuration), it won't break networking in other sessions.

Backbone sync request sequence

I've got a Backbone web application that talks to a RESTful PHP server. For PUT and POST it matters in which order the requests arrive at the server and for GET it matters in which order the responses arrive at the client.
The web application does not need to be used concurrently by multiple users, but what might happen is that the user changes its name twice really fast. Then the order in which the server processes PUT /name/Ann and PUT /name/Bea determines whether the name is set to Ann or Bea.
Backbone.Safesync and Backbone.Sync.AjaxQueue are two libraries that try to solve this problem. Doesn't Safesync only solve the problem with GET? Sync.AjaxQueue is outdated, but might serve as inspiration to implement a custom queued sync function. Making sync synchronous would solve the problem. If a request is only sent after the previous response is received, then only one request is processed at a time.
Any advice on how to proceed?
BTW: I don't think using PATCH requests would solve anything, because in my example the same attribute is changed twice.
There's a few ways to solve this, here's two:
add a timestamp to all requests, store it in the DB as "modified" and let the server check whether the timestamp of the new request is later than the one in the DB in order to be valid
use Promises to delay the second request from being made before the first one is responded on, there's a promise/deferred mechanism built into jquery, but you can also use a 3rd party one, for instance Q or when
If you can afford the delay, an easy approach is to set the async option to false when you call whatever method you're calling that results in the Backbone.sync. For example, in the appropriate model(s) simply override the default sync method to include the additional option.

How do I implement chess with backbone.js with a RESTful api?

When one player makes a move that is sent to the server. And that move is pushed by the server to the second player. As far as I know, the server pushing the move to the second player goes against being a RESTful api.
From what little I know about backbone.js it is meant really for RESTful setups. Is there a way to use backbone.js with websockets to allow the server to push data down to the clients at any time?
Is there even an idiomatic way of implementing chess with backbone.js and websockets? And if not then what would be the correct way to implement chess?
You can definitely do it. Instead of fetching your collection/model, you will just set or update/reset the json data from the websocket into the proper model or collection.
Somewhat pseudo-code example:
var board = new Backbone.Collection(); // this would probably be your own extended Collection instead.
function boardChange(jsonFromServer){
// Take the json array from server,
// and update the collection with it.
// This would trigger 'change' events in each model in the collection (if changed).
board.update(jsonFromServer);
}
Implementing a chess app doesn't really require a Backbone architecture. As long as your server supports Asynchronous API, WebSockets, or even long-polling (anything real-time), it's possible. There's tons of APIs out there on the web already that does this (ie FireBase) as well as frameworks (ie, Meteor) comes into mind.
Also check out Socket IO if you're using Node JS for your server-side. There's tons of open source projects on GitHub that takes advantage of some of these web technologies already, Backbone in particular. Backbone with Socket IO. Backbone.ioBind also looks like a promising project with code samples that you can look at.
To make it work with Backbone, the data API just needs to notify any client-side listeners that an update has been made on the server which in turn triggers a change event on your Backbone Model.
You can even set a timer that performs a request to the server every n amount of time just to test out your code prototypes.
You could overload the Backbone.sync method to use websockets. The de-facto To-Do example (http://addyosmani.github.com/todomvc/) does this to use localstorage instead of a RESTful datastore, and you could do the same for web sockets. In fact if you look around Github/Google you may be able to find someone who's already done it.

REST API and iPhone App Architecture and Code Structure

Background:
I am in the early stages of an an iPhone App and REST WebService product. Basically, I have a database on the a server and have written some REST APIs to access this database. I have a companion iphone app that will consume these REST APIs.
Questions:
What is the best approach to place the code for accessing the REST Apis? Should I create a separate subclass of NSObject and place the interface and implementation details there? I would like to reduce the amount of code duplication throughout the application in the various ViewControllers that would interact with the REST API.
For Example:
My app would start up and make a REST API call to determine the current state of local information on the device by comparing the value returned from the API vs local. Then I would initiate an update request from the API to refresh the local datastore.
Now if I have all of this logic in the start-up ViewController I have multiple calls using NSURLConnection which only has on delegate. I don't know how to make these separate calls in the same ViewController.
What are some approaches to solving this problem?
I generally create custom objects which use ASIHTTPRequest (using composition, not subclassing) which can be initialised with any required parameters, and use that to manage requests to the RESTful service. The custom object will provide a delegate protocol for handling success, failure and other custom notifications so that I can use this feedback to update the application UI while the request is performed asynchronously.
If you need to parse large amount of data returned from a request, make sure you launch a separate thread to do this, rather than doing it in your HTTP request success callback, otherwise this will keep the network activity spinner active longer than it actually should be.
If you need to manage multiple requests of the same type, you could add a "tag" property to your custom request, so that when your success/failure delegate response is called, you can easily identify which request it belongs to without having to keep an instance variable to the original request.

How do I make a reusable web interface class in objective C?

I'm working on a new iPhone/iPod app that includes the need to do web services requests. I've found methods for doing these requests synchronously, or asynchronously by setting the controller as the delegate. What I'd really like to be able to do, though, is to create a single class that can handle all web requests for the whole application, and just create an instance of that class when I need to use it. That way, cookies and common pieces of code can be handled in one place, rather than all over the app.
So far the only thing I thought of that could accomplish what I'm trying to do is to create a new thread that handles the request synchronously within itself, then sends a message back to the calling controller once the request is complete. Is there a better way to accomplish what I'm trying to do?
Cookies are already a shared resource.
I would suggest reading the URL Loading System Overview to get an idea of how Apple set everything up. From what you describe, you want something very similar to how they have set up the system, maybe with a Singleton class for the connection. You can also look at ASIHTTPRequests which is a good wrapper around all of the connections stuff.
I would not suggest writing my own code here. Lots and lots of people have solved this problem for you.