(function(app) {                    
  app.BooksService = ng.core
    .Class({
      constructor: [ng.http.Http, function(http) {
        this.http = http;
      }],
      get: function() {
        return this.http.get('/books')
                   .map(this.extractData)
                   .catch(this.returnException);
      },
      extractData: function(response) {
        if(response.status !== 200)
          throw new Error("No response from server");
          
        return response.json();
      },
      returnException: function(error) {
        return Observable.throw(error.message || "Error: request failed");
      },
      post: function(newBook) {
        var options = 
           {headers: new ng.http.Headers(
             {'Content-Type': 'application/json'})};
        
        return this.http.post('/books', JSON.stringify(newBook), options)
                   .map(this.extractResponse)
                   .catch(this.returnException);     
      },
      extractResponse: function(response) {
        if(response.status !== 200)
          throw new Error("No response from server");
          
        return response.text();        
      }
    });
})(window.app || (window.app = {}));