|
| 1 | +/*! theon-angular-adapter - v0.1.0 - MIT License - https://github.com/theonjs/theon-angular-adapter */ |
| 2 | +angular.module('theon.adapter', []) |
| 3 | + |
| 4 | + .factory('$theonAdapter', ['$http', '$theonResponseAdapter', function ($http, adapter) { |
| 5 | + var httpAgent = $http |
| 6 | + |
| 7 | + function $httpAdapter (req, res, done) { |
| 8 | + var opts = { |
| 9 | + url: req.url, |
| 10 | + method: req.method, |
| 11 | + auth: req.opts.auth, |
| 12 | + params: req.query, |
| 13 | + headers: req.headers, |
| 14 | + data: req.body, |
| 15 | + cache: req.agentOpts.cache, |
| 16 | + timeout: +req.opts.timeout || +req.agentOpts.timeout, |
| 17 | + withCredentials: req.agentOpts.withCredentials, |
| 18 | + xsrfHeaderName: req.agentOpts.xsrfHeaderName, |
| 19 | + xsrfCookieName: req.agentOpts.xsrfCookieName, |
| 20 | + transformRequest: req.agentOpts.transformRequest, |
| 21 | + transformResponse: req.agentOpts.transformResponse, |
| 22 | + paramSerializer: req.agentOpts.paramSerializer, |
| 23 | + responseType: req.agentOpts.responseType |
| 24 | + } |
| 25 | + |
| 26 | + httpAgent(opts).then(function (_res) { |
| 27 | + done(null, adapter(res, _res)) |
| 28 | + }, function (err) { |
| 29 | + done(adapter(res, err)) |
| 30 | + }) |
| 31 | + } |
| 32 | + |
| 33 | + $httpAdapter.setAgent = function (agent) { |
| 34 | + httpAgent = agent |
| 35 | + } |
| 36 | + |
| 37 | + return $httpAdapter |
| 38 | + }]) |
| 39 | + |
| 40 | + .factory('$theonResponseAdapter', ['$q', function ($q) { |
| 41 | + return function responseAdapter (res, _res) { |
| 42 | + if (!_res) return res |
| 43 | + |
| 44 | + // Expose the agent-specific response |
| 45 | + res.setOriginalResponse(_res) |
| 46 | + |
| 47 | + // Define recurrent HTTP fields |
| 48 | + res.setStatus(_res.status) |
| 49 | + res.setStatusText(_res.statusText) |
| 50 | + res.setHeaders(_res.headers) |
| 51 | + |
| 52 | + // Define body, if present |
| 53 | + if (_res.data) res.setBody(_res.data) |
| 54 | + |
| 55 | + return res |
| 56 | + } |
| 57 | + }]) |
0 commit comments