Shamoon Shamoon - 2 months ago 16
AngularJS Question

How do I use transformRequest and transformResponse to modify data for a $resource?

I am using a JSONAPI compliant API, and one of the format requirements is that all data (incoming and outgoing) must be wrapped in a

data
object. So my request looks like:

{
"data": {
"email": "email@example.com",
"password": "pass",
"type": "sessions"
}
}


And my response looks like:

{
"data": {
"user_id": 13,
"expires": 7200,
"token": "gpKkNpSIzxrkYbQiYxc6us0yDeqRPNRb9Lo1YRMocyXnXbcwXlyedjPZi88yft3y"
}
}


In my controller, when making a new session request, I have:

$scope.signin = ->
session = new Session
email: $scope.user.email
password: $scope.user.password

session.$save()

console.log session
console.log session.token
if not session.token
alert 'Invalid Login'
else
$rootScope.session_token = session.token
$state.go 'app.dashboard'


And my
Session
is a factory that looks like:

angular.module('webapp').factory 'Session', [
'$resource'
($resource) ->
$resource 'http://localhost:9500/v1/sessions',
id: '@id'
,
save:
method: 'POST'
transformRequest: (data) ->
result =
data: JSON.parse JSON.stringify data
result.data.types = 'sessions'
result = JSON.stringify result
result
transformResponse: (data) ->
result = JSON.parse data
a = JSON.parse JSON.stringify result.data
console.log a
a


The request is fine. The formatting and parsing seems to work. However, the response, when I
log
it shows as a
Resource
, not
Object
. And
session.token
shows as undefined even though the server is returning valid data.

How do I modify my
transformResponse
to account for this?

Answer

I think what you want is to capture your Resource response with a promise:

session.$save().$promise.then(function (result) {
    console.log (result);
});
Comments