mobility-toolbox-js
Version:
Toolbox for JavaScript applications in the domains of mobility and logistics.
46 lines (45 loc) • 1.94 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import getUrlWithParams from '../common/utils/getUrlWithParams';
/**
* Common class to access to a geOps api using http.
* @private
*/
class HttpAPI {
constructor(options) {
this.url = options.url;
this.apiKey = options.apiKey;
}
/**
* Append the apiKey before sending the request.
*
* @private
*/
fetch(path, params, config) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.url) {
throw new Error(`No url defined for request to ${this.url}/${path}`);
}
if (!this.url &&
(!this.apiKey || this.apiKey === 'public') &&
!this.url.includes('key=')) {
throw new Error(`No apiKey defined for request to ${this.url}`);
}
const url = getUrlWithParams(`${this.url}${path || ''}`, Object.assign({ key: !this.apiKey || this.apiKey === 'public' ? undefined : this.apiKey }, (params || {})));
const response = yield fetch(url.toString(), config);
const data = (yield response.json());
if (data.error) {
throw new Error(data.error);
}
return data;
});
}
}
export default HttpAPI;