@mcma/client
Version:
Node module with classes and functions used to access services in an MCMA environment
84 lines (83 loc) • 3.22 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceEndpointClient = void 0;
const core_1 = require("@mcma/core");
const http_1 = require("../http");
class ResourceEndpointClient {
resourceEndpoint;
authProvider;
httpClientConfig;
serviceAuthType;
_httpClient;
constructor(resourceEndpoint, authProvider, httpClientConfig, serviceAuthType) {
this.resourceEndpoint = resourceEndpoint;
this.authProvider = authProvider;
this.httpClientConfig = httpClientConfig;
this.serviceAuthType = serviceAuthType;
if (!resourceEndpoint) {
throw new core_1.McmaException("resourceEndpoint cannot be null or undefined.");
}
if (!!authProvider && typeof authProvider.get !== "function") {
throw new core_1.McmaException("ResourceEndpoint: Provided authProvider does not define the required get(authType, authContext) function.", null, resourceEndpoint);
}
}
get httpEndpoint() {
return this.resourceEndpoint.httpEndpoint;
}
get httpClient() {
if (!this._httpClient) {
const authenticator = this.authProvider &&
this.authProvider.get(this.resourceEndpoint.authType || this.serviceAuthType);
this._httpClient = new http_1.HttpClient(authenticator, this.httpClientConfig);
}
return this._httpClient;
}
prepareRequest(urlOrConfig, config, body) {
let url;
if (typeof urlOrConfig === "string") {
url = urlOrConfig;
}
else if (!config) {
config = urlOrConfig;
url = "";
}
if (!url && body?.id) {
url = body.id;
}
url = url || "";
config = config || {};
config.baseURL = this.resourceEndpoint.httpEndpoint;
config.transformResponse = (data) => {
if (data) {
try {
return JSON.parse(data, core_1.Utils.reviver);
}
catch {
}
}
return data;
};
return { url, config, body };
}
async get(urlOrConfig, config) {
const request = this.prepareRequest(urlOrConfig, config);
return await this.httpClient.get(request.url, request.config);
}
async post(body, urlOrConfig, config) {
const request = this.prepareRequest(urlOrConfig, config, body);
return await this.httpClient.post(request.body, request.url, request.config);
}
async put(body, urlOrConfig, config) {
const request = this.prepareRequest(urlOrConfig, config, body);
return await this.httpClient.put(request.body, request.url, request.config);
}
async patch(body, urlOrConfig, config) {
const request = this.prepareRequest(urlOrConfig, config, body);
return await this.httpClient.patch(request.body, request.url, request.config);
}
async delete(urlOrConfig, config) {
const request = this.prepareRequest(urlOrConfig, config);
return await this.httpClient.delete(request.url, request.config);
}
}
exports.ResourceEndpointClient = ResourceEndpointClient;