Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 protected]",
    "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?

like image 416
Shamoon Avatar asked Apr 08 '15 16:04

Shamoon


2 Answers

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

session.$save().$promise.then(function (result) {
    console.log (result);
});
like image 147
Dave Alperovich Avatar answered Nov 05 '22 03:11

Dave Alperovich


May I suggest an XHR interceptor?

xhrInterceptor.js:

(function (app) {
    "use strict";

    function XhrInterceptor($q) {
        return {

            request: function requestInterceptor(config) {
                var data = config.data;

                if (data &&
                    config.method === "POST") {

                    config.data = {
                        data: data
                    };
                }

                return config || $q.when(config);
            },

            response: function responseInterceptor(response) {
                if (typeof response === "object") {
                    if (response.config.method === "POST") {
                        response.data = response.data.data || {};
                    }
                }

                return response || $q.when(response);
            }
        };
    }

    app
        .factory("app.XhrInterceptor", ["$q", XhrInterceptor]);

})(window.app);

app.js:

In with your config phase, or other initialisation logic, add the response interceptor.

app
    .config(["$httpProvider", function ($httpProvider) {
            $httpProvider.interceptors.push("app.XhrInterceptor");
    });

Further information

XHR Interceptor in an AngularJS web app

Intercept XHR/Ajax requests with AngularJS http

like image 31
Ash Clarke Avatar answered Nov 05 '22 04:11

Ash Clarke