UNPKG

@opra/client

Version:
105 lines (104 loc) 3.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpClientBase = void 0; const common_1 = require("@opra/common"); const constants_js_1 = require("../constants.js"); const http_request_observable_js_1 = require("./http-request-observable.js"); const SPLIT_BACKSLASH_PATTERN = /^(\/*)(.+)/; /** * * @class OpraClientBase * @abstract */ class HttpClientBase { constructor(backend) { Object.defineProperty(this, constants_js_1.kBackend, { enumerable: false, value: backend, }); } get serviceUrl() { return this[constants_js_1.kBackend].serviceUrl; } async fetchDocument(options) { const documentMap = {}; const getDocument = async (documentId) => { const req = this.request('$schema', { headers: new Headers({ accept: 'application/json' }), }); if (documentId) req.param('id', documentId); const body = await req.getBody().catch(e => { e.message = 'Error fetching api schema from url (' + this.serviceUrl + ').\n' + e.message; throw e; }); if (body.references) { const oldReferences = body.references; body.references = {}; for (const [ns, obj] of Object.entries(oldReferences)) { if (documentMap[obj.id] === null) throw new Error('Circular reference detected'); documentMap[obj.id] = null; const x = await getDocument(obj.id); body.references[ns] = documentMap[obj.id] = x; } } return body; }; const body = await getDocument(options?.documentId); return await common_1.ApiDocumentFactory.createDocument(body).catch(e => { e.message = 'Error loading api document.\n' + e.message; throw e; }); } request(path, options) { /** Remove leading backslashes */ path = SPLIT_BACKSLASH_PATTERN.exec(path)?.[2] || ''; const observable = new http_request_observable_js_1.HttpRequestObservable(this[constants_js_1.kBackend], { ...options, method: options?.method || 'GET', url: new URL(path, this.serviceUrl), }); if (options?.params) observable.param(options.params); return observable; } delete(path, options) { return this.request(path, { ...options, method: 'DELETE', }); } get(path, options) { return this.request(path, { ...options, method: 'GET', }); } patch(path, requestBody, options) { return this.request(path, { ...options, method: 'PATCH', body: requestBody, }); } post(path, requestBody, options) { return this.request(path, { ...options, method: 'POST', body: requestBody, }); } put(path, requestBody, options) { return this.request(path, { ...options, method: 'PUT', body: requestBody, }); } } exports.HttpClientBase = HttpClientBase;