UNPKG

@emergentmethods/asknews-typescript-sdk

Version:
444 lines (443 loc) 17.3 kB
"use strict"; /* tslint:disable */ /* eslint-disable */ /** * AskNews API * AskNews API * * The version of the OpenAPI document: 0.21.1 * Contact: contact@emergentmethods.ai * * 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.StreamApiResponse = exports.TextApiResponse = exports.BlobApiResponse = exports.VoidApiResponse = exports.JSONApiResponse = exports.canConsumeForm = exports.mapValues = exports.querystring = exports.COLLECTION_FORMATS = exports.UnauthorizedError = exports.RequiredError = exports.FetchError = exports.ResponseError = exports.BaseAPI = exports.DefaultConfig = exports.Configuration = exports.AUTH_URL = exports.BASE_PATH = void 0; exports.BASE_PATH = "https://api.asknews.app".replace(/\/+$/, ""); exports.AUTH_URL = "https://auth.asknews.app/oauth2/token"; class Configuration { constructor(configuration = {}) { this.configuration = configuration; } set config(configuration) { this.configuration = configuration; } get basePath() { return this.configuration.basePath != null ? this.configuration.basePath : exports.BASE_PATH; } get fetchApi() { return this.configuration.fetchApi; } get clientId() { return this.configuration.clientId; } get clientSecret() { return this.configuration.clientSecret; } get scopes() { return this.configuration.scopes; } get authUrl() { var _a; return (_a = this.configuration.authUrl) !== null && _a !== void 0 ? _a : exports.AUTH_URL; } get middleware() { return this.configuration.middleware || []; } get queryParamsStringify() { return this.configuration.queryParamsStringify || querystring; } get accessToken() { return this.configuration.accessToken; } set accessToken(accessToken) { this.configuration.accessToken = accessToken; } get headers() { return this.configuration.headers; } get credentials() { return this.configuration.credentials; } get debug() { return this.configuration.debug || false; } set debug(debug) { this.configuration.debug = debug; } } exports.Configuration = Configuration; exports.DefaultConfig = new Configuration(); /** * This is the base class for all generated API classes. */ class BaseAPI { constructor(_configuration = exports.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; }); if (!(_configuration instanceof Configuration)) { _configuration = new Configuration(_configuration); } this.middleware = _configuration.middleware; this.configuration = _configuration; } 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) { var _a; return __awaiter(this, void 0, void 0, function* () { if (this.configuration.accessToken && this.configuration.accessToken.expires) { const now = (new Date()).getTime(); const buffer = 10 * 1000; if (this.configuration.accessToken.expires - buffer < now) { if (this.configuration.debug) { console.log('Access token has expired. Removing it from the configuration'); } this.configuration.accessToken = undefined; } } if (!this.configuration.accessToken && this.configuration.clientId && this.configuration.clientSecret && this.configuration.scopes) { if (this.configuration.debug) { console.log('Requesting access token using client credentials'); } const token = btoa(`${this.configuration.clientId}:${this.configuration.clientSecret}`); const response = yield fetch((_a = this.configuration.authUrl) !== null && _a !== void 0 ? _a : exports.AUTH_URL, { headers: new Headers({ 'Authorization': `Basic ${token}`, 'Content-Type': 'application/x-www-form-urlencoded', }), method: 'POST', body: new URLSearchParams({ 'grant_type': 'client_credentials', 'scope': this.configuration.scopes.join(' '), }), }); if (response.status !== 200) { const responseCode = response.status; const responseText = yield response.text(); throw new ResponseError(`Failed to get access token\nError code: ${responseCode}\nError message: ${responseText}`); } if (this.configuration.debug) { console.log('Access token received'); } const json = yield response.json(); this.configuration.accessToken = { tokenType: json.token_type, tokenValue: json.access_token, expires: (new Date()).getTime() + json.expires_in * 1000, scopes: json.scope.split(' '), }; if (this.configuration.debug) { console.log('Access token stored in the configuration'); } } const { url, init } = yield this.createFetchParams(context, initOverrides); if (this.configuration.debug) { console.log(`Requesting ${url}`); console.log('Headers:', init.headers); console.log('Request body:', init.body); } const response = yield this.fetchApi(url, init); if (this.configuration.debug) { console.log('Response status:', response.status); console.log('Response headers:', response.headers); } if (response && response.status >= 200 && response.status < 300) { if (this.configuration.debug) { console.log('Request successful, returning response'); } return response; } else if (response && (response.status === 401 || response.status === 403)) { if (this.configuration.debug) { console.log('Request failed with 401/403 status code'); } throw new UnauthorizedError(response, 'Please check your credentials or scopes'); } const responseCode = response.status; const responseText = yield response.text(); if (this.configuration.debug) { console.log('Request failed with status code', responseCode); console.log('Response body:', responseText); } throw new ResponseError(`Response returned an error code: ${responseCode}\nError message: ${responseText}`); }); } 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] : {}); if (!headers['Authorization'] && this.configuration.accessToken) { headers['Authorization'] = `${this.configuration.accessToken.tokenType} ${this.configuration.accessToken.tokenValue}`; } 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; } } exports.BaseAPI = BaseAPI; 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; } class ResponseError extends Error { constructor(msg) { super(msg); this.name = "ResponseError"; } } exports.ResponseError = ResponseError; class FetchError extends Error { constructor(cause, msg) { super(msg); this.cause = cause; this.name = "FetchError"; } } exports.FetchError = FetchError; class RequiredError extends Error { constructor(field, msg) { super(msg); this.field = field; this.name = "RequiredError"; } } exports.RequiredError = RequiredError; class UnauthorizedError extends Error { constructor(response, msg) { super(msg); this.response = response; this.name = "UnauthorizedError"; } } exports.UnauthorizedError = UnauthorizedError; exports.COLLECTION_FORMATS = { csv: ",", ssv: " ", tsv: "\t", pipes: "|", }; function querystring(params, prefix = '') { return Object.keys(params) .map(key => querystringSingleKey(key, params[key], prefix)) .filter(part => part.length > 0) .join('&'); } exports.querystring = querystring; 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))}`; } function mapValues(data, fn) { return Object.keys(data).reduce((acc, key) => (Object.assign(Object.assign({}, acc), { [key]: fn(data[key]) })), {}); } exports.mapValues = mapValues; function canConsumeForm(consumes) { for (const consume of consumes) { if ('multipart/form-data' === consume.contentType) { return true; } } return false; } exports.canConsumeForm = canConsumeForm; 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()); }); } } exports.JSONApiResponse = JSONApiResponse; class VoidApiResponse { constructor(raw) { this.raw = raw; } value() { return __awaiter(this, void 0, void 0, function* () { return undefined; }); } } exports.VoidApiResponse = VoidApiResponse; class BlobApiResponse { constructor(raw) { this.raw = raw; } value() { return __awaiter(this, void 0, void 0, function* () { return yield this.raw.blob(); }); } ; } exports.BlobApiResponse = BlobApiResponse; class TextApiResponse { constructor(raw) { this.raw = raw; } value() { return __awaiter(this, void 0, void 0, function* () { return yield this.raw.text(); }); } ; } exports.TextApiResponse = TextApiResponse; class StreamApiResponse { constructor(raw) { this.raw = raw; } value() { return __awaiter(this, void 0, void 0, function* () { return this.raw.body; }); } ; } exports.StreamApiResponse = StreamApiResponse;