Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

fix(resource): check whether response matches action.isArray #3054

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/ngResource/resource.js
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,10 @@ angular.module('ngResource', ['ng']).
promise = value.$promise;

if (data) {
if ( angular.isArray(data) != !!action.isArray ) {
return $q.reject("Error in resource configuration. Expected response to contain an " +
(action.isArray?'array':'object') + " but got an " + (angular.isArray(data)?'array':'object'));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we throw a minErr instead of explicitly rejecting the promise?

}
if (action.isArray) {
value.length = 0;
forEach(data, function(item) {
Expand Down
21 changes: 21 additions & 0 deletions test/ngResource/resourceSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -800,6 +800,27 @@ describe("resource", function() {
});
});

it('should fail if action expects an object but response is an array', function() {
var successHandler = jasmine.createSpy('successHandler');
var failureHandler = jasmine.createSpy('failureHandler');
$httpBackend.expect('GET', '/Customer/123').respond({id: 'abc'});
$resource('/Customer/123').query().$promise.then(successHandler, failureHandler);
$httpBackend.flush();
expect(successHandler).not.toHaveBeenCalled();
expect(failureHandler).toHaveBeenCalledWith(
'Error in resource configuration. Expected response to contain an array but got an object');
});

it('should fail if action expects an array but response is an object', function() {
var successHandler = jasmine.createSpy('successHandler');
var failureHandler = jasmine.createSpy('failureHandler');
$httpBackend.expect('GET', '/Customer/123').respond([1,2,3]);
$resource('/Customer/123').get().$promise.then(successHandler, failureHandler);
$httpBackend.flush();
expect(successHandler).not.toHaveBeenCalled();
expect(failureHandler).toHaveBeenCalledWith(
'Error in resource configuration. Expected response to contain an object but got an array');
});

it('should transform request/response', function() {
var Person = $resource('/Person/:id', {}, {
Expand Down