Tag Archives: services

6 Tips for building JavaScript apps

I’ve actually built a few JavaScript applications in the new style (AngularJS, Backbone.js, or other front-end JavaScript framework on the front-end and only APIs on the back-end) over the last couple of years. Here are some tips on what I think has worked well on those projects:

  1. Understand this, above all else, the front-end code is not real security! If you’re an American you can understand this via an analogy. The JavaScript code running in the browser is the TSA, it is security theater which exists just to make some user’s experience better. For example, it might hide buttons which the user is not allowed to click. But that doesn’t mean that the user cannot hack the JavaScript to turn on the forbidden button anyway. All of the real security in your application exists at the API layer. It must check every single value passed to it and confirm that the user has the permissions to perform the action he/she is trying to perform before actually doing anything. Likewise, it must not return any information which the logged in user should not have access to. Relying on the JavaScript code to hide part of the data will not work. Put all of your security focus on having a bulletproof API and you will never have real security problems.
  2. People use HTTP error codes to communicate back data for their APIs. In my opinion that’s a really bad idea and often not very adaptable to the actual errors you’re having. Instead use the JSend protocol for all the JSON you return. It’s the same objects you would probably send back today except that it is wrapped with an object that tells you status (‘success’, ‘fail’, or ‘error’) and messages/codes when appropriate because there were errors. Going this route will simplify your JavaScript service calling code and help you differentiate API errors from actual transport layer problems like servers being down or problems on the network.
  3. Don’t try to sequence operations from the front-end. I once answered a question on Stack Overflow where the asker wanted to know about how to sequence a seven step process for paying for something. I answered it once telling how to do it and then again to say never to do that. You should not have your front-end be the conductor and the back-end be the orchestra. If you do, you will be sorry because eventually someone will lose their web connection, close their laptop, or just shut down their browser in the middle of your carefully choreographed sequence. Instead, always try to make API calls from front to back that provide complete units of work, complete transactions with all the information needed for multi-step operations so you won’t end up with only part of an operation completing.
  4. Please, please, please, please don’t do things that break basic conventions in your apps. There’s no reason the user shouldn’t be able to hit the back button or the forward button. It requires very little thought to support (especially if you use modern JavaScript frameworks). Ditto bookmarks and multiple tabs. There shouldn’t be any reason I can’t copy a URL and send it to somebody else or make a bookmark of my location so I can get back to the same spot. Nevertheless, I’ve worked on so many apps over the years where these basic operations acted weird or wouldn’t work at all. Don’t be one of those apps.
  5. Spend some time thinking about what happens when the user sits on a page so long his/her session expires on the server. If you’re following suggestion two above then you can send back a standard error in your JSend and catch it in your JavaScript code. Then just prompt the user to login without ever leaving the page. Likewise, think about what happens when the user clicks on a bookmark in the browser or an email and goes to the site but is not yet logged in.
  6. Please, don’t be afraid to reject some ancient browsers. There’s good code out there to help you do it and make it look nice, but ultimately you’re doing yourself, your users, and everybody else a service if you refuse service for IE 6/7/8 and maybe more than that depending upon your needs.
About these ads

Yes it’s “REST” but is it any good?

I’m not picking on the author of this discussion of different levels of REST APIs. As a matter-of-fact, I thought it was a quite good article. But the advice I see over and over again for how to build remote APIs seems focused on the URLs and how they are formed as a function of whether the API is “good” or “bad”. So let me just say this… If your API has you performing atomic units of action via multiple API calls to the back end, your API is bad whether it conforms to all the REST requirements or not.

So, if you’re taking money out of one account via one call and then transferring it to another via another call, you’ve:

  • allowed business logic to leak into code outside the back end
  • created a situation that is almost guaranteed to result in a corrupted database, keystore, or whatever at some point
  • made anyone using your API work much harder (for example, if after adding a new user, they also need to go add that user to a group, add an avatar picture, etc. all as separate operations)

One alternative I would recommend looking at (I’m not advocating this as some kind of REST replacement, just something you need to take ten minutes to learn about) is CQRS. The link is to a warehouse of info on it but the basic idea is that an API will have queries where you just get data for display and commands (think Gang of Four Command pattern) for performing actions in the system. Thus moving money from one account to another might be a command or adding a user might be another. In each case, you’ll provide enough data with the command to make sure the back end can completely perform it in one atomic operation and the front end stays out of the business logic/sequencing business.

I’ve yet to read the grand treatise on how to create a great CQRS API which runs on REST. I’d love to read such a thing if you find one. Please leave a comment below if you do.

AngularJS Services and Promises

Promises, Deferred, Futures

Call it what you will, promises are another mechanism for dealing with the asynchronous nature of some things you’ll do within JavaScript. For example, calling remote services, timers, animations completing, etc. In each case you could just have a callback, but what if you wanted to attach several callbacks to the completion or failure of a single asynchronous job? That’s difficult with callbacks, but promises make it easy.

Promises make it easy to tie together several asynchronous actions and treat them as one. This makes it easy to react only when all have completed or one of them had a problem. This is a much better solution than the nesting of callbacks you often see done in JavaScript code. Nested callbacks are often written in a way that forces requests to be made serially when they could be executed in parallel and perform better as a result.

Promises can simplify code in another way because a promise which has already resolved and one which has yet to resolve are treated are both used in exactly the same way.

Promises in AngularJS

AngularJS offers promises via a service called $q. It is modeled after a promise library called (not surprisingly) Q. You’ll see promises returned from several of AngularJS’s services, including $http (for service calls), $timeout, and $route (though I admit I’m not sure how it’s being used in the latter case).

AngularJS even has support for promises being assigned directly to $scope variables. So you can take the promise you get back from a remote service call and assign it directly to a variable knowing that when the service call finally returns, the variable will be updated and any binding attached to the variable will redisplay. That’s significantly easier than other frameworks I’ve used in the past.

Service Calls

I thought I’d give three examples of calling a service with $http and show how the promise it returns may be used directly, and examples of how caching and aggregation can be made easier thanks to promises.

For these examples I’m just calling the OpenKeyval service to store and retrieve some JSON data. It’s simple, it’s free, and I know I can count on any code I give you being able to access it without any special API key.

Source code for all of the following and more is here: https://github.com/JohnMunsch/AngularJSExamples, in particular look at the app/scripts/controllers/promises.js and app/view/promises.html to see the code specific to these examples.

Click here to see all of the following as running examples on Github

    • Example 1: Store and retrieve some values. Promises returned from $http are assigned directly to $scope variables and AngularJS dereferences them automatically.
    • Example 2: Make multiple calls to different services aggregating the results of all the calls and merging the results into a single returned value.
    • Example 3: A common pattern for services is to be able to satisfy requests from a local cache when appropriate. Promises can make that an easy upgrade for an existing service.

A Shortcoming

$q is not as full featured as Q is. That’s not surprising because AngularJS is only trying to provide as much functionality as it needs without requiring you to load up another library. AngularJS does the same kind of thing when it comes to jQuery. It has a minimal subset of functionality built in (called jQLite) that it uses if jQuery wasn’t loaded prior to loading AngularJS.

However, this is where things suddenly differ. If you do load jQuery prior to loading AngularJS then it won’t use it’s own built in version, but will instead use the more full-featured jQuery implementation. However, as far as I know, loading up the Q library or jQuery before you load up AngularJS doesn’t cause AngularJS to use Q promises or jQuery Deferred objects instead of its own subset implementation. That seems to me like an oversight or shortcoming to their implementation.

Nevertheless, I hope I’ve shown with the examples above that you can still do some really interesting things even with the limited set of functionality $q provides.

Follow Up

After a few weeks I realized that something I didn’t really cover is how assigning a promise to a variable in $scope can hinder access of that same variable in the controller. For example, if you do something like this:

$scope.someValue = $http.get(someURL);

You’ve assigned a promise to the variable and from the standpoint of code in your view, nothing really changed. You can still do {{someValue.someSubValue}} and act blissfully unaware that someValue is a promise rather than a JavaScript object. But, try the same thing from the controller code and you’ll have all kinds of problems. $scope.someValue.someSubValue isn’t anything you can access in the controller because $scope.someValue is actually a promise and will always stay a promise, even once it’s resolved. The only thing that changes once it’s resolved is that any .then() function you call on it will immediately call the closure you pass into it with the value the promise now caches. Thus you will forever more have to use it within the controller like so:

$scope.someValue.then(function (value) { $log.info(value.someSubValue); });

If you have some values you’re getting via AJAX calls or via some other mechanism that returns a promise and you need to access them as much or more from a controller as from view code then only assign the resolved value into the scope and not the promise. For example:

$http.get(someURL).then(function (value) { $scope.someValue = value; });

In that case you’re waiting until the promise resolves and only assigning the final returned value into the scope. Now both the view code and the controller can directly access $scope.someValue.someSubValue freely.

Reference