UNPKG

@studyportals/sp-hs-misc

Version:

Miscellaneous code used in HouseStark's projects

82 lines 3.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ServiceLayerRequestsSender = void 0; class ServiceLayerRequestsSender { _ongoingRequestsByUrl; config; get ongoingRequestsByUrl() { return this._ongoingRequestsByUrl; } constructor(requestSenderConfig = {}) { this._ongoingRequestsByUrl = new Map(); this.config = requestSenderConfig; } send(request) { if (this.isIdenticalRequestOngoing(request)) { return this.getIdenticalOngoingRequestPromise(request); } if (this.config.userAgent) { request.set("User-Agent", this.config.userAgent); } return this.sendRequest(request); } isIdenticalRequestOngoing(request) { return this.ongoingRequestsByUrl.has(request.url); } getIdenticalOngoingRequestPromise(request) { const ongoingRequestPromise = this.ongoingRequestsByUrl.get(request.url); if (ongoingRequestPromise) { return ongoingRequestPromise; } throw new Error(`Could not find an ongoing request for: ${request.url}`); } sendRequest(request) { const promiseToSendTheRequestAndNormalizeTheOutput = this.sendRequestAndNormalizeOutput(request); this.registerOngoingRequest(request.url, promiseToSendTheRequestAndNormalizeTheOutput); return promiseToSendTheRequestAndNormalizeTheOutput; } sendRequestAndNormalizeOutput(request) { return new Promise((resolve, reject) => { request.end((err, res) => { this.removeOngoingRequest(request.url); if (err) { reject(err); } else { // // If the request is successfull, the Service Layer // can return either an empty array (when there is no data), // or an object that indexes the entities by their IDs. // // For consistancy's sake, return an empty array when there // is no data, or an array of the object's value when entities // are provided. if (Array.isArray(res.body)) { resolve(res.body); } else { if ("object" === typeof res.body) { const values = []; Object.keys(res.body).forEach(key => values.push(res.body[key])); resolve(values); } else { reject(new Error(`Unexpected body ${res.body}`)); } } } }); }); } registerOngoingRequest(url, requestPromise) { if (this.ongoingRequestsByUrl.has(url)) { throw new Error(`An ongoing request already exists for: ${url}`); } this.ongoingRequestsByUrl.set(url, requestPromise); } removeOngoingRequest(url) { this.ongoingRequestsByUrl.delete(url); } } exports.ServiceLayerRequestsSender = ServiceLayerRequestsSender; //# sourceMappingURL=service-layer-requests-sender.class.js.map