@hasadna/open-bus-api-client
Version:
A client library for interacting with the Open-Bus API.
335 lines (334 loc) • 14.1 kB
JavaScript
/* tslint:disable */
/* eslint-disable */
/**
* Open Bus Stride API
* ### Follow planned and real-time bus statistics 🚌 Welcome to The Public Knowledge Workshop\'s Stride project. We provide usable and accurate data about the Israeli public transportation system. For background on the project and some more detailed documentation and usage guides, see [STRIDE.md](https://github.com/hasadna/open-bus-pipelines/blob/main/STRIDE.md). Looking for a specific use-case? * Take a look at the **user cases** APIs below. * Try one of our existing [jupyter notebooks](https://github.com/hasadna/open-bus-stride-client/blob/main/README.md#using-the-interactive-jupyter-notebooks). * Don\'t see your use-case covered here? Please [open us a ticket](https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fhasadna%2Fopen-bus%2Fissues%2Fnew)! Queries are by default limited to 100 results per query, this limit can be increased up to 500,000 results. Please try to set appropriate query parameters to limit the results to reduce load on our DB. If you do need to get large number of results (up to 500,000) it\'s recommended to use one of these methods: 1. Use HTTP streaming and JSON streaming decoder, this method is most efficient and provide accurate results. Our [Stride Python Client iterate method](https://github.com/hasadna/open-bus-stride-client#usage) uses this method. 2. Use combination of limit / offset parameters to get results by page. This method may be less accurate because it depends on data remaining unchanged between requests. For more advanced usage- * Use **gtfs** for data about the planned lines timetables. * Use **siri** for data about lines real-time * See [Open Bus Stride Data Model](https://github.com/hasadna/open-bus-stride-db/blob/main/DATA_MODEL.md) for description of field and table names. * See [Open Bus Stride ETL Processes](https://github.com/hasadna/open-bus-pipelines/blob/main/STRIDE_ETL_PROCESSES.md) for description of the ETL processes which fetch and aggregate the data. * See [MOT Developer Information](https://www.gov.il/BlobFolder/generalpage/gtfs_general_transit_feed_specifications/he/GTFS%20-%20Developer%20Information.pdf) for description of the source fields as published by the Israel Ministry of Transportation.
*
* The version of the OpenAPI document: 6909b3db7b8bfa5ac3f3c4aeb3de80d2a2c75810
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
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());
});
};
export const BASE_PATH = "http://localhost".replace(/\/+$/, "");
export class Configuration {
constructor(configuration = {}) {
this.configuration = configuration;
}
set config(configuration) {
this.configuration = configuration;
}
get basePath() {
return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
}
get fetchApi() {
return this.configuration.fetchApi;
}
get middleware() {
return this.configuration.middleware || [];
}
get queryParamsStringify() {
return this.configuration.queryParamsStringify || querystring;
}
get username() {
return this.configuration.username;
}
get password() {
return this.configuration.password;
}
get apiKey() {
const apiKey = this.configuration.apiKey;
if (apiKey) {
return typeof apiKey === 'function' ? apiKey : () => apiKey;
}
return undefined;
}
get accessToken() {
const accessToken = this.configuration.accessToken;
if (accessToken) {
return typeof accessToken === 'function' ? accessToken : () => __awaiter(this, void 0, void 0, function* () { return accessToken; });
}
return undefined;
}
get headers() {
return this.configuration.headers;
}
get credentials() {
return this.configuration.credentials;
}
}
export const DefaultConfig = new Configuration();
/**
* This is the base class for all generated API classes.
*/
export class BaseAPI {
constructor(configuration = DefaultConfig) {
this.configuration = configuration;
this.fetchApi = (url, init) => __awaiter(this, void 0, void 0, function* () {
let fetchParams = { url, init };
for (const middleware of this.middleware) {
if (middleware.pre) {
fetchParams = (yield middleware.pre(Object.assign({ fetch: this.fetchApi }, fetchParams))) || fetchParams;
}
}
let response = undefined;
try {
response = yield (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init);
}
catch (e) {
for (const middleware of this.middleware) {
if (middleware.onError) {
response = (yield middleware.onError({
fetch: this.fetchApi,
url: fetchParams.url,
init: fetchParams.init,
error: e,
response: response ? response.clone() : undefined,
})) || response;
}
}
if (response === undefined) {
if (e instanceof Error) {
throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response');
}
else {
throw e;
}
}
}
for (const middleware of this.middleware) {
if (middleware.post) {
response = (yield middleware.post({
fetch: this.fetchApi,
url: fetchParams.url,
init: fetchParams.init,
response: response.clone(),
})) || response;
}
}
return response;
});
this.middleware = configuration.middleware;
}
withMiddleware(...middlewares) {
const next = this.clone();
next.middleware = next.middleware.concat(...middlewares);
return next;
}
withPreMiddleware(...preMiddlewares) {
const middlewares = preMiddlewares.map((pre) => ({ pre }));
return this.withMiddleware(...middlewares);
}
withPostMiddleware(...postMiddlewares) {
const middlewares = postMiddlewares.map((post) => ({ post }));
return this.withMiddleware(...middlewares);
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
isJsonMime(mime) {
if (!mime) {
return false;
}
return BaseAPI.jsonRegex.test(mime);
}
request(context, initOverrides) {
return __awaiter(this, void 0, void 0, function* () {
const { url, init } = yield this.createFetchParams(context, initOverrides);
const response = yield this.fetchApi(url, init);
if (response && (response.status >= 200 && response.status < 300)) {
return response;
}
throw new ResponseError(response, 'Response returned an error code');
});
}
createFetchParams(context, initOverrides) {
return __awaiter(this, void 0, void 0, function* () {
let url = this.configuration.basePath + context.path;
if (context.query !== undefined && Object.keys(context.query).length !== 0) {
// only add the querystring to the URL if there are query parameters.
// this is done to avoid urls ending with a "?" character which buggy webservers
// do not handle correctly sometimes.
url += '?' + this.configuration.queryParamsStringify(context.query);
}
const headers = Object.assign({}, this.configuration.headers, context.headers);
Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {});
const initOverrideFn = typeof initOverrides === "function"
? initOverrides
: () => __awaiter(this, void 0, void 0, function* () { return initOverrides; });
const initParams = {
method: context.method,
headers,
body: context.body,
credentials: this.configuration.credentials,
};
const overriddenInit = Object.assign(Object.assign({}, initParams), (yield initOverrideFn({
init: initParams,
context,
})));
let body;
if (isFormData(overriddenInit.body)
|| (overriddenInit.body instanceof URLSearchParams)
|| isBlob(overriddenInit.body)) {
body = overriddenInit.body;
}
else if (this.isJsonMime(headers['Content-Type'])) {
body = JSON.stringify(overriddenInit.body);
}
else {
body = overriddenInit.body;
}
const init = Object.assign(Object.assign({}, overriddenInit), { body });
return { url, init };
});
}
/**
* Create a shallow clone of `this` by constructing a new instance
* and then shallow cloning data members.
*/
clone() {
const constructor = this.constructor;
const next = new constructor(this.configuration);
next.middleware = this.middleware.slice();
return next;
}
}
BaseAPI.jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i');
;
function isBlob(value) {
return typeof Blob !== 'undefined' && value instanceof Blob;
}
function isFormData(value) {
return typeof FormData !== "undefined" && value instanceof FormData;
}
export class ResponseError extends Error {
constructor(response, msg) {
super(msg);
this.response = response;
this.name = "ResponseError";
}
}
export class FetchError extends Error {
constructor(cause, msg) {
super(msg);
this.cause = cause;
this.name = "FetchError";
}
}
export class RequiredError extends Error {
constructor(field, msg) {
super(msg);
this.field = field;
this.name = "RequiredError";
}
}
export const COLLECTION_FORMATS = {
csv: ",",
ssv: " ",
tsv: "\t",
pipes: "|",
};
export function querystring(params, prefix = '') {
return Object.keys(params)
.map(key => querystringSingleKey(key, params[key], prefix))
.filter(part => part.length > 0)
.join('&');
}
function querystringSingleKey(key, value, keyPrefix = '') {
const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
if (value instanceof Array) {
const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue)))
.join(`&${encodeURIComponent(fullKey)}=`);
return `${encodeURIComponent(fullKey)}=${multiValue}`;
}
if (value instanceof Set) {
const valueAsArray = Array.from(value);
return querystringSingleKey(key, valueAsArray, keyPrefix);
}
if (value instanceof Date) {
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
}
if (value instanceof Object) {
return querystring(value, fullKey);
}
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
}
export function exists(json, key) {
const value = json[key];
return value !== null && value !== undefined;
}
export function mapValues(data, fn) {
const result = {};
for (const key of Object.keys(data)) {
result[key] = fn(data[key]);
}
return result;
}
export function canConsumeForm(consumes) {
for (const consume of consumes) {
if ('multipart/form-data' === consume.contentType) {
return true;
}
}
return false;
}
export class JSONApiResponse {
constructor(raw, transformer = (jsonValue) => jsonValue) {
this.raw = raw;
this.transformer = transformer;
}
value() {
return __awaiter(this, void 0, void 0, function* () {
return this.transformer(yield this.raw.json());
});
}
}
export class VoidApiResponse {
constructor(raw) {
this.raw = raw;
}
value() {
return __awaiter(this, void 0, void 0, function* () {
return undefined;
});
}
}
export class BlobApiResponse {
constructor(raw) {
this.raw = raw;
}
value() {
return __awaiter(this, void 0, void 0, function* () {
return yield this.raw.blob();
});
}
;
}
export class TextApiResponse {
constructor(raw) {
this.raw = raw;
}
value() {
return __awaiter(this, void 0, void 0, function* () {
return yield this.raw.text();
});
}
;
}