UNPKG

@ng-app-framework/api

Version:

![Travis CI](https://travis-ci.org/ng-app-framework/api.svg?branch=master)

688 lines (683 loc) 21.6 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@ng-app-framework/validation'), require('@angular/common/http'), require('@ng-app-framework/core'), require('rxjs/Rx'), require('qs')) : typeof define === 'function' && define.amd ? define(['exports', '@angular/core', '@ng-app-framework/validation', '@angular/common/http', '@ng-app-framework/core', 'rxjs/Rx', 'qs'], factory) : (factory((global.api = {}),global.ng.core,global['ng-app-validation'],global.ng.common.http,global['ng-app-core'],global.rxjs,global.qs)); }(this, (function (exports,core,validation,http,core$1,Rx,qs) { 'use strict'; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var HttpProxy = /** @class */ (function () { /** * @param {?} http */ function HttpProxy(http$$1) { this.http = http$$1; } /** * @param {?} request * @return {?} */ HttpProxy.prototype.request = function (request) { return this.http.request(request); }; return HttpProxy; }()); HttpProxy.decorators = [ { type: core.Injectable }, ]; /** * @nocollapse */ HttpProxy.ctorParameters = function () { return [ { type: http.HttpClient, }, ]; }; var HeaderLoader = /** @class */ (function () { function HeaderLoader() { } /** * @param {?} response * @return {?} */ HeaderLoader.load = function (response) { for (var _i = 0, _a = Object.keys(HeaderLoader.headerMap); _i < _a.length; _i++) { var headerConstant = _a[_i]; var /** @type {?} */ body = response['body'] || response['error']; body.data = body.data || {}; var /** @type {?} */ header = this.getHeader(response, headerConstant); if (header !== null) { if (body.data[HeaderLoader.headerMap[headerConstant]]) { body.data[HeaderLoader.headerMap[headerConstant]] = header || body.data[HeaderLoader.headerMap[headerConstant]]; continue; } body.data[HeaderLoader.headerMap[headerConstant]] = header; } } return response; }; /** * @param {?} response * @param {?} header * @return {?} */ HeaderLoader.getHeader = function (response, header) { return response.headers.get(header.toLowerCase()) || response.headers.get(header.toUpperCase()); }; return HeaderLoader; }()); HeaderLoader.headerMap = {}; /** * @abstract */ var Requestable = /** @class */ (function () { function Requestable() { } /** * @abstract * @param {?} request * @return {?} */ Requestable.prototype.request = function (request) { }; return Requestable; }()); var RequestBuilder = /** @class */ (function () { function RequestBuilder() { } /** * @param {?} method * @param {?} url * @param {?} data * @return {?} */ RequestBuilder.getRequestArgs = function (method, url, data) { if (method === 'get' || method === 'delete') { return this.getQueryStringRequest(method, url, data); } return this.getBodyRequest(method, url, data); }; /** * @param {?} method * @param {?} url * @param {?} data * @return {?} */ RequestBuilder.getBodyRequest = function (method, url, data) { return { method: method, url: this.populateValuesInUrl(url, data), body: data }; }; /** * @param {?} method * @param {?} url * @param {?} data * @return {?} */ RequestBuilder.getQueryStringRequest = function (method, url, data) { var /** @type {?} */ fullUrl = this.populateValuesInUrl(url, data); return { method: method, url: RequestBuilder.getUrlWithQueryParameters(fullUrl, data) }; }; /** * @param {?} url * @param {?} data * @return {?} */ RequestBuilder.getUrlWithQueryParameters = function (url, data) { var /** @type {?} */ queryStringData = qs.stringify(data); if (queryStringData.length > 0) { var /** @type {?} */ delimiter = '?'; if (url.indexOf('?') !== -1) { delimiter = '&'; } return url + delimiter + queryStringData; } return url; }; /** * @param {?} url * @param {?} data * @return {?} */ RequestBuilder.populateValuesInUrl = function (url, data) { var /** @type {?} */ formatted = url; for (var /** @type {?} */ key in data) { if (core$1.Value.isScalar(data[key]) && key.indexOf(':') === 0) { formatted = core$1.StringValue.replace(formatted, "" + key, data[key].toString()); delete data[key]; } } return formatted; }; return RequestBuilder; }()); var EndpointConfig = /** @class */ (function () { function EndpointConfig() { this.baseUri = ''; } return EndpointConfig; }()); EndpointConfig.decorators = [ { type: core.Injectable }, ]; /** * @nocollapse */ EndpointConfig.ctorParameters = function () { return []; }; var EndpointCaller = /** @class */ (function () { /** * @param {?} http * @param {?=} config */ function EndpointCaller(http$$1, config) { if (config === void 0) { config = { baseUri: '' }; } this.http = http$$1; this.config = config; this.lastRequest = null; this.lastResponse = null; this.onApiStart = new core.EventEmitter(); this.onApiFinish = new core.EventEmitter(); } /** * @param {?} absoluteUrl * @param {?} method * @param {?=} requestData * @return {?} */ EndpointCaller.prototype.call = function (absoluteUrl, method, requestData) { if (requestData === void 0) { requestData = {}; } return this.execute(this.createRequestObject(absoluteUrl, method, requestData)); }; /** * @param {?} path * @param {?} method * @param {?} requestData * @return {?} */ EndpointCaller.prototype.createRequestObject = function (path, method, requestData) { return new http.HttpRequest('GET', path).clone(this.lastRequest = RequestBuilder.getRequestArgs(method, path, requestData)); }; /** * @param {?} request * @return {?} */ EndpointCaller.prototype.execute = function (request) { var _this = this; this.onApiStart.emit(); return this.http.request(request) .finally(function () { _this.onApiFinish.emit(); }) .last() .catch(function (err, caught) { HeaderLoader.load(err); return Rx.Observable.throw(err); }) .flatMap(function (response) { return _this.map(response); }); }; /** * @param {?} response * @return {?} */ EndpointCaller.prototype.map = function (response) { this.lastResponse = response; return Rx.Observable.from([this.transformResponse(this.getObjectFromResponse(response))]); }; /** * @param {?} response * @return {?} */ EndpointCaller.prototype.getObjectFromResponse = function (response) { HeaderLoader.load(response); if (core$1.Value.hasKey(response || {}, 'body') && core$1.Value.isProvided(response.body)) { return response.body; } return {}; }; /** * @param {?} response * @return {?} */ EndpointCaller.prototype.transformResponse = function (response) { return response; }; return EndpointCaller; }()); EndpointCaller.decorators = [ { type: core.Injectable }, ]; /** * @nocollapse */ EndpointCaller.ctorParameters = function () { return [ { type: Requestable, }, { type: EndpointConfig, decorators: [{ type: core.Optional },] }, ]; }; /** * @abstract */ var Callable = /** @class */ (function () { function Callable() { } /** * @abstract * @param {?} absoluteUrl * @param {?} method * @param {?=} requestData * @return {?} */ Callable.prototype.call = function (absoluteUrl, method, requestData) { }; return Callable; }()); Callable.decorators = [ { type: core.Injectable }, ]; /** * @nocollapse */ Callable.ctorParameters = function () { return []; }; var NgApiModule = /** @class */ (function () { function NgApiModule() { } /** * @param {?} baseUri * @return {?} */ NgApiModule.forRoot = function (baseUri) { return { ngModule: NgApiModule, providers: [ { provide: EndpointConfig, useValue: { baseUri: baseUri } } ] }; }; return NgApiModule; }()); NgApiModule.decorators = [ { type: core.NgModule, args: [{ imports: [ core$1.NgCoreModule, validation.NgValidationModule, http.HttpClientModule ], exports: [ http.HttpClientModule ], providers: [ EndpointCaller, EndpointConfig, HttpProxy, { provide: Callable, useExisting: EndpointCaller }, { provide: Requestable, useExisting: HttpProxy } ] },] }, ]; /** * @nocollapse */ NgApiModule.ctorParameters = function () { return []; }; var EndpointValidator = /** @class */ (function () { /** * @param {?=} input * @param {?=} output */ function EndpointValidator(input, output) { this.input = input; this.output = output; } /** * @param {?} request * @return {?} */ EndpointValidator.prototype.validateRequest = function (request) { if (this.input) { return this.input.validate$(request); } return new Rx.Observable(function (observer) { return observer.complete(); }); }; /** * @param {?} response * @return {?} */ EndpointValidator.prototype.validateResponse = function (response) { if (this.output) { return this.output.validate$(response).concat(Rx.Observable.from([response])); } return Rx.Observable.from([response]); }; return EndpointValidator; }()); var EndpointRegistry = /** @class */ (function () { function EndpointRegistry() { } /** * @param {?} endpoint * @return {?} */ EndpointRegistry.register = function (endpoint) { this.list.push(endpoint); this.listChange.emit(this.list); }; /** * @return {?} */ EndpointRegistry.getOrganizedList = function () { var /** @type {?} */ modules = {}; for (var _i = 0, _a = EndpointRegistry.list; _i < _a.length; _i++) { var endpoint = _a[_i]; if (!modules[endpoint.module]) { modules[endpoint.module] = []; } modules[endpoint.module].push(endpoint); } return modules; }; return EndpointRegistry; }()); EndpointRegistry.list = []; EndpointRegistry.listChange = new core.EventEmitter(); var EndpointEvents = /** @class */ (function () { function EndpointEvents() { this.onApiSuccess = new core.EventEmitter(); this.onApiFailure = new core.EventEmitter(); this.onValidationSuccess = new core.EventEmitter(); this.onValidationFailure = new core.EventEmitter(); this.onSuccess = new core.EventEmitter(); this.onFailure = new core.EventEmitter(); } return EndpointEvents; }()); var Endpoint = /** @class */ (function () { /** * @param {?} endpointCaller */ function Endpoint(endpointCaller) { this.endpointCaller = endpointCaller; this.module = 'Api'; this.customBaseUri = ''; this.path = ''; this.validator = new EndpointValidator(); this.metadata = {}; this.events = new EndpointEvents(); this.placeholders = {}; EndpointRegistry.register(this); } /** * @param {?} method * @param {?=} requestData * @return {?} */ Endpoint.prototype.request = function (method, requestData) { var _this = this; if (requestData === void 0) { requestData = {}; } return this.validator .validateRequest(requestData) .catch(function (err, caught) { return _this.onValidationFailure('request', err, caught); }) .concat(this.onRequestValidationSuccess()) .concat(this.continueWithRequest(method, requestData) .catch(function (err, caught) { return _this.onApiRequestFailure(err, caught); })) .map(function (response) { return _this.onRequestSuccess(response); }) .map(function (response) { return _this.transformResponse(response); }) .flatMap(function (transformedResponse) { return _this.validator.validateResponse(transformedResponse) .catch(function (err, caught) { return _this.onValidationFailure('response', err, caught); }); }) .map(function (transformedResponse) { return _this.onResponseSuccess(transformedResponse); }); }; /** * @param {?} method * @param {?} requestData * @return {?} */ Endpoint.prototype.continueWithRequest = function (method, requestData) { return this.endpointCaller.call(this.getAbsoluteUrl(requestData), method, requestData); }; /** * @param {?} transformedResponse * @return {?} */ Endpoint.prototype.onResponseSuccess = function (transformedResponse) { this.events.onValidationSuccess.emit({ location: 'response' }); this.events.onSuccess.emit(transformedResponse); return transformedResponse; }; /** * @param {?} transformed * @return {?} */ Endpoint.prototype.onRequestSuccess = function (transformed) { this.events.onApiSuccess.emit(transformed); return transformed; }; /** * @param {?} err * @param {?} caught * @return {?} */ Endpoint.prototype.onApiRequestFailure = function (err, caught) { this.events.onApiFailure.emit(err); return Rx.Observable.throw(err); }; /** * @return {?} */ Endpoint.prototype.onRequestValidationSuccess = function () { var _this = this; return new Rx.Observable(function (observer) { _this.events.onValidationSuccess.emit({ location: 'request' }); observer.complete(); }); }; /** * @param {?} location * @param {?} err * @param {?} caught * @return {?} */ Endpoint.prototype.onValidationFailure = function (location, err, caught) { this.events.onValidationFailure.emit({ location: location, content: err }); this.events.onFailure.emit(err); return Rx.Observable.throw(err); }; /** * @param {?} response * @return {?} */ Endpoint.prototype.transformResponse = function (response) { return response; }; /** * @param {?} requestData * @return {?} */ Endpoint.prototype.getAbsoluteUrl = function (requestData) { return (this.customBaseUri.length > 0 ? this.customBaseUri : this.endpointCaller.config.baseUri) + this.getReplacedPath(requestData); }; /** * @param {?} requestData * @return {?} */ Endpoint.prototype.getReplacedPath = function (requestData) { var /** @type {?} */ path = this.path; for (var /** @type {?} */ toReplace in this.placeholders) { if (this.placeholders.hasOwnProperty(toReplace) && this.placeholders[toReplace].hasOwnProperty('key')) { if (requestData.hasOwnProperty(this.placeholders[toReplace].key)) { path = path.replace(':' + toReplace, requestData[this.placeholders[toReplace].key]); if (this.placeholders[toReplace].remove) { delete requestData[this.placeholders[toReplace].key]; } } } } return path; }; return Endpoint; }()); Endpoint.decorators = [ { type: core.Injectable }, ]; /** * @nocollapse */ Endpoint.ctorParameters = function () { return [ { type: EndpointCaller, }, ]; }; var EndpointCallerMock = /** @class */ (function () { function EndpointCallerMock() { this.config = { baseUri: '' }; this.mockResponse = {}; } /** * @param {?} absoluteUrl * @param {?} method * @param {?=} requestData * @return {?} */ EndpointCallerMock.prototype.call = function (absoluteUrl, method, requestData) { if (requestData === void 0) { requestData = {}; } return Rx.Observable.of(this.mockResponse); }; return EndpointCallerMock; }()); var HttpSpy = /** @class */ (function () { function HttpSpy() { this.onRequest = function (request) { }; } /** * @param {?} request * @return {?} */ HttpSpy.prototype.request = function (request) { var /** @type {?} */ testRequest = (request); this.onRequest(/** @type {?} */ (request)); return Rx.Observable.from([testRequest.mockResponse]) .map(function (value) { var /** @type {?} */ url = new URL(testRequest.url); testRequest.params = new URLSearchParams(url.search); if (!value.ok) { throw value; } return value; }); }; return HttpSpy; }()); var EndpointCallerShunt = /** @class */ (function (_super) { __extends(EndpointCallerShunt, _super); /** * @param {?=} config */ function EndpointCallerShunt(config) { var _this = _super.call(this, new HttpSpy(), config) || this; _this.mockResponse = {}; _this.config.baseUri = 'http://www.local.dev/'; return _this; } /** * @param {?} path * @param {?} method * @param {?} requestData * @return {?} */ EndpointCallerShunt.prototype.createRequestObject = function (path, method, requestData) { return Object.assign(_super.prototype.createRequestObject.call(this, path, method, requestData), { mockResponse: this.mockResponse }); }; /** * @param {?} response * @return {?} */ EndpointCallerShunt.prototype.tryGettingObjectFromResponse = function (response) { return this.getObjectFromResponse(response); }; return EndpointCallerShunt; }(EndpointCaller)); /** * @abstract */ var EndpointMocker = /** @class */ (function () { /** * @param {?} endpoint */ function EndpointMocker(endpoint) { this.endpoint = endpoint; } /** * @return {?} */ EndpointMocker.prototype.mock = function () { var _this = this; this.endpoint.metadata.mockResponse = function (request, subject) { return _this.respond(request, subject); }; }; /** * @param {?} request * @param {?} subject * @return {?} */ EndpointMocker.prototype.respond = function (request, subject) { var /** @type {?} */ body = JSON.parse(request.body); if (this.isValidRequest(body, request.params)) { subject.next(this.getSuccess(body, request.params)); subject.complete(); return; } subject.error(this.getFailure(body, request.params)); }; /** * @abstract * @param {?} body * @param {?} params * @return {?} */ EndpointMocker.prototype.isValidRequest = function (body, params) { }; /** * @abstract * @param {?} body * @param {?} params * @return {?} */ EndpointMocker.prototype.getSuccess = function (body, params) { }; /** * @abstract * @param {?} body * @param {?} params * @return {?} */ EndpointMocker.prototype.getFailure = function (body, params) { }; return EndpointMocker; }()); exports.NgApiModule = NgApiModule; exports.Callable = Callable; exports.Requestable = Requestable; exports.EndpointCaller = EndpointCaller; exports.EndpointValidator = EndpointValidator; exports.EndpointConfig = EndpointConfig; exports.Endpoint = Endpoint; exports.EndpointRegistry = EndpointRegistry; exports.EndpointEvents = EndpointEvents; exports.HttpProxy = HttpProxy; exports.RequestBuilder = RequestBuilder; exports.HeaderLoader = HeaderLoader; exports.EndpointCallerMock = EndpointCallerMock; exports.EndpointCallerShunt = EndpointCallerShunt; exports.EndpointMocker = EndpointMocker; exports.HttpSpy = HttpSpy; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=api.umd.js.map