Search code examples
javascriptangularjsnode.jsrestngresource

How should i use ngResource with a specific response body?


My response body looks like this:

{
   "code": 200,
   "message": Items succesfully retrieved,
   "items": [ 
              {
                 ... 
              }
            ]
}

I was using $http before so i didn't have this problem but i've decided to switch to ngResource because it seemed better. And i'm sure i'm doing it wrong, so if you could please tell me how to target 'items' (in this example) to be the returned object (same for put, post, ...)

Here is the sample of code i've made to try out ngResource

app.factory("Product", function($resource,APILINK) {
  return $resource(APILINK+"/api/v1/products/:id", {id: '@id'}, {
     query: {method: 'GET',
  isArray: false
  },
  update: { method: 'PUT' }
  });
});

I don't really know if it's a good way to build my REST Api sending the code and message. But it feels much cleaner this way :'(

Do I need to modify the json sent by my REST Api ? Or is there a way to make ngResource ignore "code" and "message" in the response body ?


Solution

  • Setting the status code and message in your data transfer (json) object might not be the way to go. Is it necessary to access the status code?

    The documentation on $resource reads as follows:

    • HTTP GET "class" actions: Resource.action([parameters], [success], [error])
    • non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
    • non-GET instance actions: instance.$action([parameters], [success], [error])

    So, every $resource call gives us a success and error callback. For example:

    var Product = $resource('/api/as/product');
    
    Product.query(function(items) {
       // success handler
    }, function(error) {
       // error handler
    });
    

    You might not be able to read the status code, but you have knowledge about whether or not your call was successful.

    Alternatively, you can look into interceptors if getting the status code is a must:

    // Resource
    var Product = $resource(url, {}, {
       get: {
           method: 'GET'
           interceptor: {
               response: function(response) {      
                   var result = response.resource;        
                   result.$status = response.status;
                   return result;
               }
           }
       }                            
     });
    
     // Caller
     Product.get(params, function(result) {
        console.log('status code: ' + result.$status);
     });
    

    When a call is made with this resource, we will intercept the result, add the status code to it from the response and then return it to the caller.