UNPKG

ionic-coreo

Version:

Ionic2 module for integration with Coreo

89 lines 3.35 kB
"use strict"; var core_1 = require('@angular/core'); var Observable_1 = require('rxjs/Observable'); var http_1 = require('@angular/http'); var token_context_1 = require('./token-context'); var config_1 = require('./config'); var CoreoClient = (function () { function CoreoClient(http, config, tokenContext) { this.http = http; this.config = config; this.tokenContext = tokenContext; } CoreoClient.prototype.getAuthorizationHeader = function (token) { return 'JWT ' + token.token; }; CoreoClient.prototype.post = function (path, body, options) { if (options === void 0) { options = {}; } if (body instanceof FormData) { options.body = body; options.headers = options.headers || {}; options.headers['enctype'] = 'multipart/form-data'; } else if (body) { options.body = JSON.stringify(body); } options.method = 'post'; return this.request(path, options); }; CoreoClient.prototype.request = function (path, options) { if (options === void 0) { options = {}; } var hdrs = options.headers || {}; if (!(options.body && options.body instanceof FormData)) { hdrs['Content-Type'] = 'application/json'; } if (typeof options.authentication !== 'undefined') { if (options.authentication) { hdrs.Authorization = this.getAuthorizationHeader(options.authentication); } } else if (this.tokenContext.token) { hdrs.Authorization = this.getAuthorizationHeader(this.tokenContext.token); } var headers = new http_1.Headers(hdrs); var url = this.config.baseUrl + path; var requestOptions = Object.assign({}, { url: url, method: 'get', body: null }, options); requestOptions.headers = headers; var request = new http_1.Request(requestOptions); return this.http.request(request) .map(function (res) { return res.json(); }) .catch(this.handleError); }; CoreoClient.prototype.handleError = function (error) { // In a real world app, we might use a remote logging infrastructure var errMsg; if (error instanceof http_1.Response) { switch (error.status) { case 401: errMsg = "Unauthorized"; break; default: var body = error.json() || ''; var err = body.error || JSON.stringify(body); errMsg = error.status + " - " + (error.statusText || '') + " " + err; } } else { errMsg = error.message ? error.message : error.toString(); } return Observable_1.Observable.throw(errMsg); }; CoreoClient.decorators = [ { type: core_1.Injectable }, ]; /** @nocollapse */ CoreoClient.ctorParameters = [ { type: http_1.Http, }, { type: config_1.CoreoConfig, }, { type: token_context_1.CoreoTokenContext, }, ]; return CoreoClient; }()); exports.CoreoClient = CoreoClient; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = CoreoClient; //# sourceMappingURL=client.js.map