@opra/client
Version:
Opra Client package
101 lines (100 loc) • 3.19 kB
JavaScript
import { ApiDocumentFactory, } from '@opra/common';
import { kBackend } from '../constants.js';
import { HttpRequestObservable } from './http-request-observable.js';
const SPLIT_BACKSLASH_PATTERN = /^(\/*)(.+)/;
/**
*
* @class OpraClientBase
* @abstract
*/
export class HttpClientBase {
constructor(backend) {
Object.defineProperty(this, kBackend, {
enumerable: false,
value: backend,
});
}
get serviceUrl() {
return this[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 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 HttpRequestObservable(this[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,
});
}
}