UNPKG

@obelisk/client

Version:

Typescript client to interact with Obelisk on a higher level than the regular ReST API calls.

83 lines (82 loc) 3.52 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TPageEndpoint = void 0; const rxjs_1 = require("rxjs"); const operators_1 = require("rxjs/operators"); const util_1 = require("../util"); /** * Endpoint class represents an Obelisk API Endpoint. * You can just execute it, or request soms higher level function from it, like give me a range. */ class TPageEndpoint { constructor(client, uri, apiVersion = 'v1') { this.client = client; this._apiVersion = apiVersion; this._url = util_1.InternalUtils.norm(client, uri, apiVersion); } /** * Absolute url to use in requests */ get url() { return this._url; } /** * Creates an TPageEndpoint instance, the client is used to add tokens and uri is relative path starting after /api/<version>. * Examples are: <code>/things/my_thing/metrics/my_metric/events?from=1530089953000</code> or <code>/locations/my_loc/metrics/my_metric/stats/unit</code> */ static create(client, uri, apiVersion = 'v1') { return new TPageEndpoint(client, uri, apiVersion); } get(uri) { util_1.Logger.debug(uri, 'AJAX'); uri = util_1.InternalUtils.norm(this.client, uri, this._apiVersion); const request = { responseType: 'json', url: uri }; return util_1.InternalUtils.authRequest(this.client, request) .pipe(operators_1.map(util_1.InternalUtils.mapAjaxResponse2TPageResponse)); } /** * Executes the call to the given endpoint. * If the call requires authentication, it will add it. * If the call requires extra handling because it defines a range of multple buckets, * it will handle it. */ execute() { util_1.Logger.debug(this._url, 'Execute'); let last; return this.get(this._url).pipe(operators_1.tap(tpage => { last = (tpage.link && tpage.link.last) ? tpage.link.last : null; }), operators_1.expand(tpage => { if (!tpage.link) { // no link header: stop return rxjs_1.empty(); } else { if (last === null) { // No last cached, so no expanding util_1.Logger.debug('no expansion', 'CASE no last cached'); return rxjs_1.empty(); } // link header present else if (last !== null && last === tpage.link.self) { // last reached, stop expanding util_1.Logger.debug('stop expansion', 'CASE last === self'); return rxjs_1.empty(); } else if (last !== null && util_1.InternalUtils.part(last)[0] === tpage.link.next) { // last reached, stop expanding util_1.Logger.debug('expand to next' + util_1.InternalUtils.part(last)[1], 'CASE last-path === next'); return this.get(tpage.link.next + util_1.InternalUtils.part(last)[1]); } else { // no last, follow next util_1.Logger.debug('expand to next', 'CASE following next'); return this.get(tpage.link.next); // since this is a range, there should be a next link } } })); } } exports.TPageEndpoint = TPageEndpoint;