From 4031ede32ae8612ee6e65effdb688c64272b7c29 Mon Sep 17 00:00:00 2001 From: slavkor <30171206+slavkor@users.noreply.github.com> Date: Thu, 22 Aug 2024 08:10:28 +0000 Subject: [PATCH] chore: release data-link SDK --- README.md | 43 +-- src/.npmignore | 1 + src/.openapi-generator/FILES | 20 +- src/README.md | 43 +-- src/apis/DefaultApi.ts | 143 ---------- src/apis/index.ts | 1 - src/index.ts | 4 - src/models/ApiResponse.ts | 29 -- src/models/PushData.ts | 58 ---- src/models/PushDataAttribute.ts | 29 -- src/models/State.ts | 23 -- src/package.json | 7 +- src/runtime.ts | 193 ------------- src/servers.ts | 45 --- src/src/apis/DefaultApi.ts | 211 ++++++++++++++ src/src/apis/index.ts | 3 + src/src/index.ts | 5 + src/src/models/ModelApiResponse.ts | 68 +++++ src/src/models/PushData.ts | 115 ++++++++ src/src/models/PushDataAttribute.ts | 68 +++++ src/src/models/State.ts | 49 ++++ src/{ => src}/models/index.ts | 4 +- src/src/runtime.ts | 426 ++++++++++++++++++++++++++++ src/tsconfig.json | 4 +- 24 files changed, 964 insertions(+), 628 deletions(-) create mode 100644 src/.npmignore delete mode 100644 src/apis/DefaultApi.ts delete mode 100644 src/apis/index.ts delete mode 100644 src/index.ts delete mode 100644 src/models/ApiResponse.ts delete mode 100644 src/models/PushData.ts delete mode 100644 src/models/PushDataAttribute.ts delete mode 100644 src/models/State.ts delete mode 100644 src/runtime.ts delete mode 100644 src/servers.ts create mode 100644 src/src/apis/DefaultApi.ts create mode 100644 src/src/apis/index.ts create mode 100644 src/src/index.ts create mode 100644 src/src/models/ModelApiResponse.ts create mode 100644 src/src/models/PushData.ts create mode 100644 src/src/models/PushDataAttribute.ts create mode 100644 src/src/models/State.ts rename src/{ => src}/models/index.ts (53%) create mode 100644 src/src/runtime.ts diff --git a/README.md b/README.md index 7d4d697..cac0135 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ ## databox@2.1.1 -This generator creates TypeScript/JavaScript client that utilizes [RxJS](https://rxjs-dev.firebaseapp.com/). The generated Node module can be used in the following environments: +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: Environment * Node.js @@ -44,44 +44,3 @@ _unPublished (not recommended):_ ``` npm install PATH_TO_GENERATED_PACKAGE --save ``` - -### How to apply middleware - -First, add a singleton class that extends the generated `Configuration` class. - -``` -export class AuthInterceptor extends Configuration { - private static config: AuthInterceptor; - - private constructor() { - const middleware: Middleware[] = [ - { - pre(request: RequestArgs): RequestArgs { - const token = getAuthToken(); - - return { - ...request, - headers: { - ...request.headers, - Authorization: `Bearer ${token}`, - }, - }; - }, - }, - ]; - - super({ middleware }); - } - - public static get Instance() { - return AuthInterceptor.config || (AuthInterceptor.config = new this()); - } -} -``` - -Next, pass it to the generated api controller. - -``` -const api = new StoreApi(AuthInterceptor.Instance); - -``` diff --git a/src/.npmignore b/src/.npmignore new file mode 100644 index 0000000..42061c0 --- /dev/null +++ b/src/.npmignore @@ -0,0 +1 @@ +README.md \ No newline at end of file diff --git a/src/.openapi-generator/FILES b/src/.openapi-generator/FILES index 13cafd5..d613877 100644 --- a/src/.openapi-generator/FILES +++ b/src/.openapi-generator/FILES @@ -1,14 +1,14 @@ .gitignore +.npmignore README.md -apis/DefaultApi.ts -apis/index.ts -index.ts -models/ApiResponse.ts -models/PushData.ts -models/PushDataAttribute.ts -models/State.ts -models/index.ts package.json -runtime.ts -servers.ts +src/apis/DefaultApi.ts +src/apis/index.ts +src/index.ts +src/models/ModelApiResponse.ts +src/models/PushData.ts +src/models/PushDataAttribute.ts +src/models/State.ts +src/models/index.ts +src/runtime.ts tsconfig.json diff --git a/src/README.md b/src/README.md index 7d4d697..cac0135 100644 --- a/src/README.md +++ b/src/README.md @@ -1,6 +1,6 @@ ## databox@2.1.1 -This generator creates TypeScript/JavaScript client that utilizes [RxJS](https://rxjs-dev.firebaseapp.com/). The generated Node module can be used in the following environments: +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: Environment * Node.js @@ -44,44 +44,3 @@ _unPublished (not recommended):_ ``` npm install PATH_TO_GENERATED_PACKAGE --save ``` - -### How to apply middleware - -First, add a singleton class that extends the generated `Configuration` class. - -``` -export class AuthInterceptor extends Configuration { - private static config: AuthInterceptor; - - private constructor() { - const middleware: Middleware[] = [ - { - pre(request: RequestArgs): RequestArgs { - const token = getAuthToken(); - - return { - ...request, - headers: { - ...request.headers, - Authorization: `Bearer ${token}`, - }, - }; - }, - }, - ]; - - super({ middleware }); - } - - public static get Instance() { - return AuthInterceptor.config || (AuthInterceptor.config = new this()); - } -} -``` - -Next, pass it to the generated api controller. - -``` -const api = new StoreApi(AuthInterceptor.Instance); - -``` diff --git a/src/apis/DefaultApi.ts b/src/apis/DefaultApi.ts deleted file mode 100644 index edac066..0000000 --- a/src/apis/DefaultApi.ts +++ /dev/null @@ -1,143 +0,0 @@ -// tslint:disable -/** - * Static OpenAPI document of Push API resource - * Push API resources Open API documentation - * - * The version of the OpenAPI document: 0.4.1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -import type { Observable } from 'rxjs'; -import type { AjaxResponse } from 'rxjs/ajax'; -import { BaseAPI, throwIfNullOrUndefined, encodeURI } from '../runtime'; -import type { OperationOpts, HttpHeaders } from '../runtime'; -import type { - PushData, -} from '../models'; - -export interface DataMetricKeyDeleteRequest { - metricKey: string; -} - -export interface DataPostRequest { - pushData?: Array; -} - -export interface MetrickeysPostRequest { - body?: object; -} - -/** - * no description - */ -export class DefaultApi extends BaseAPI { - - /** - */ - dataDelete(): Observable - dataDelete(opts?: OperationOpts): Observable> - dataDelete(opts?: OperationOpts): Observable> { - const headers: HttpHeaders = { - ...(this.configuration.username != null && this.configuration.password != null ? { Authorization: `Basic ${btoa(this.configuration.username + ':' + this.configuration.password)}` } : undefined), - }; - - return this.request({ - url: '/data', - method: 'DELETE', - headers, - }, opts?.responseOpts); - }; - - /** - */ - dataMetricKeyDelete({ metricKey }: DataMetricKeyDeleteRequest): Observable - dataMetricKeyDelete({ metricKey }: DataMetricKeyDeleteRequest, opts?: OperationOpts): Observable> - dataMetricKeyDelete({ metricKey }: DataMetricKeyDeleteRequest, opts?: OperationOpts): Observable> { - throwIfNullOrUndefined(metricKey, 'metricKey', 'dataMetricKeyDelete'); - - const headers: HttpHeaders = { - ...(this.configuration.username != null && this.configuration.password != null ? { Authorization: `Basic ${btoa(this.configuration.username + ':' + this.configuration.password)}` } : undefined), - }; - - return this.request({ - url: '/data/{metricKey}'.replace('{metricKey}', encodeURI(metricKey)), - method: 'DELETE', - headers, - }, opts?.responseOpts); - }; - - /** - */ - dataPost({ pushData }: DataPostRequest): Observable - dataPost({ pushData }: DataPostRequest, opts?: OperationOpts): Observable> - dataPost({ pushData }: DataPostRequest, opts?: OperationOpts): Observable> { - - const headers: HttpHeaders = { - 'Content-Type': 'application/json', - ...(this.configuration.username != null && this.configuration.password != null ? { Authorization: `Basic ${btoa(this.configuration.username + ':' + this.configuration.password)}` } : undefined), - }; - - return this.request({ - url: '/data', - method: 'POST', - headers, - body: pushData, - }, opts?.responseOpts); - }; - - /** - */ - metrickeysGet(): Observable - metrickeysGet(opts?: OperationOpts): Observable> - metrickeysGet(opts?: OperationOpts): Observable> { - const headers: HttpHeaders = { - ...(this.configuration.username != null && this.configuration.password != null ? { Authorization: `Basic ${btoa(this.configuration.username + ':' + this.configuration.password)}` } : undefined), - }; - - return this.request({ - url: '/metrickeys', - method: 'GET', - headers, - }, opts?.responseOpts); - }; - - /** - */ - metrickeysPost({ body }: MetrickeysPostRequest): Observable - metrickeysPost({ body }: MetrickeysPostRequest, opts?: OperationOpts): Observable> - metrickeysPost({ body }: MetrickeysPostRequest, opts?: OperationOpts): Observable> { - - const headers: HttpHeaders = { - 'Content-Type': 'application/json', - ...(this.configuration.username != null && this.configuration.password != null ? { Authorization: `Basic ${btoa(this.configuration.username + ':' + this.configuration.password)}` } : undefined), - }; - - return this.request({ - url: '/metrickeys', - method: 'POST', - headers, - body: body as any, - }, opts?.responseOpts); - }; - - /** - */ - pingGet(): Observable - pingGet(opts?: OperationOpts): Observable> - pingGet(opts?: OperationOpts): Observable> { - const headers: HttpHeaders = { - ...(this.configuration.username != null && this.configuration.password != null ? { Authorization: `Basic ${btoa(this.configuration.username + ':' + this.configuration.password)}` } : undefined), - }; - - return this.request({ - url: '/ping', - method: 'GET', - headers, - }, opts?.responseOpts); - }; - -} diff --git a/src/apis/index.ts b/src/apis/index.ts deleted file mode 100644 index a1aa469..0000000 --- a/src/apis/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './DefaultApi'; diff --git a/src/index.ts b/src/index.ts deleted file mode 100644 index b9e2f3c..0000000 --- a/src/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from './runtime'; -export * from './servers'; -export * from './apis'; -export * from './models'; diff --git a/src/models/ApiResponse.ts b/src/models/ApiResponse.ts deleted file mode 100644 index 5468f8f..0000000 --- a/src/models/ApiResponse.ts +++ /dev/null @@ -1,29 +0,0 @@ -// tslint:disable -/** - * Static OpenAPI document of Push API resource - * Push API resources Open API documentation - * - * The version of the OpenAPI document: 0.4.1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/** - * @export - * @interface ApiResponse - */ -export interface ApiResponse { - /** - * @type {string} - * @memberof ApiResponse - */ - status?: string; - /** - * @type {string} - * @memberof ApiResponse - */ - message?: string; -} diff --git a/src/models/PushData.ts b/src/models/PushData.ts deleted file mode 100644 index 947cb5a..0000000 --- a/src/models/PushData.ts +++ /dev/null @@ -1,58 +0,0 @@ -// tslint:disable -/** - * Static OpenAPI document of Push API resource - * Push API resources Open API documentation - * - * The version of the OpenAPI document: 0.4.1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -import type { - PushDataAttribute, -} from './'; - -/** - * @export - * @interface PushData - */ -export interface PushData { - /** - * @type {Array} - * @memberof PushData - */ - attributes?: Array; - /** - * @type {string} - * @memberof PushData - */ - date?: string; - /** - * @type {string} - * @memberof PushData - */ - key?: string; - /** - * @type {string} - * @memberof PushData - */ - periodFrom?: string; - /** - * @type {string} - * @memberof PushData - */ - periodTo?: string; - /** - * @type {string} - * @memberof PushData - */ - unit?: string; - /** - * @type {number} - * @memberof PushData - */ - value?: number; -} diff --git a/src/models/PushDataAttribute.ts b/src/models/PushDataAttribute.ts deleted file mode 100644 index 32f7b89..0000000 --- a/src/models/PushDataAttribute.ts +++ /dev/null @@ -1,29 +0,0 @@ -// tslint:disable -/** - * Static OpenAPI document of Push API resource - * Push API resources Open API documentation - * - * The version of the OpenAPI document: 0.4.1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/** - * @export - * @interface PushDataAttribute - */ -export interface PushDataAttribute { - /** - * @type {string} - * @memberof PushDataAttribute - */ - key?: string; - /** - * @type {string} - * @memberof PushDataAttribute - */ - value?: string; -} diff --git a/src/models/State.ts b/src/models/State.ts deleted file mode 100644 index 24c831a..0000000 --- a/src/models/State.ts +++ /dev/null @@ -1,23 +0,0 @@ -// tslint:disable -/** - * Static OpenAPI document of Push API resource - * Push API resources Open API documentation - * - * The version of the OpenAPI document: 0.4.1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/** - * - * @export - * @enum {string} - */ -export enum State { - Down = 'DOWN', - Up = 'UP' -} - diff --git a/src/package.json b/src/package.json index e477053..1afd64c 100644 --- a/src/package.json +++ b/src/package.json @@ -9,13 +9,10 @@ }, "main": "./dist/index.js", "typings": "./dist/index.d.ts", - "scripts" : { - "build": "node_modules/.bin/tsc --outDir dist/", + "scripts": { + "build": "tsc", "prepare": "npm run build" }, - "dependencies": { - "rxjs": "^7.2.0" - }, "devDependencies": { "typescript": "^4.0 || ^5.0" } diff --git a/src/runtime.ts b/src/runtime.ts deleted file mode 100644 index ebe923c..0000000 --- a/src/runtime.ts +++ /dev/null @@ -1,193 +0,0 @@ -// tslint:disable -/** - * Static OpenAPI document of Push API resource - * Push API resources Open API documentation - * - * The version of the OpenAPI document: 0.4.1 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -import { of } from 'rxjs'; -import type { Observable } from 'rxjs'; -import { ajax } from 'rxjs/ajax'; -import type { AjaxConfig, AjaxResponse } from 'rxjs/ajax'; -import { map, concatMap } from 'rxjs/operators'; -import { servers } from './servers'; - -export const BASE_PATH = servers[0].getUrl(); - -export interface ConfigurationParameters { - basePath?: string; // override base path - middleware?: Middleware[]; // middleware to apply before/after rxjs requests - username?: string; // parameter for basic security - password?: string; // parameter for basic security - apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security -} - -export class Configuration { - constructor(private configuration: ConfigurationParameters = {}) {} - - get basePath(): string { - return this.configuration.basePath ?? BASE_PATH; - } - - get middleware(): Middleware[] { - return this.configuration.middleware ?? []; - } - - get username(): string | undefined { - return this.configuration.username; - } - - get password(): string | undefined { - return this.configuration.password; - } - - get apiKey(): ((name: string) => string) | undefined { - const { apiKey } = this.configuration; - return apiKey ? (typeof apiKey === 'string' ? () => apiKey : apiKey) : undefined; - } - - get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { - const { accessToken } = this.configuration; - return accessToken ? (typeof accessToken === 'string' ? () => accessToken : accessToken) : undefined; - } -} - -/** - * This is the base class for all generated API classes. - */ -export class BaseAPI { - private middleware: Middleware[] = []; - - constructor(protected configuration = new Configuration()) { - this.middleware = configuration.middleware; - } - - withMiddleware = (middlewares: Middleware[]): this => { - const next = this.clone(); - next.middleware = next.middleware.concat(middlewares); - return next; - }; - - withPreMiddleware = (preMiddlewares: Array) => - this.withMiddleware(preMiddlewares.map((pre) => ({ pre }))); - - withPostMiddleware = (postMiddlewares: Array) => - this.withMiddleware(postMiddlewares.map((post) => ({ post }))); - - protected request(requestOpts: RequestOpts): Observable - protected request(requestOpts: RequestOpts, responseOpts?: ResponseOpts): Observable> - protected request(requestOpts: RequestOpts, responseOpts?: ResponseOpts): Observable> { - return this.rxjsRequest(this.createRequestArgs(requestOpts)).pipe( - map((res) => { - const { status, response } = res; - if (status >= 200 && status < 300) { - return responseOpts?.response === 'raw' ? res : response; - } - throw res; - }) - ); - } - - private createRequestArgs = ({ url: baseUrl, query, method, headers, body, responseType }: RequestOpts): AjaxConfig => { - // 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. - const url = `${this.configuration.basePath}${baseUrl}${query && Object.keys(query).length ? `?${queryString(query)}`: ''}`; - - return { - url, - method, - headers, - body: body instanceof FormData ? body : JSON.stringify(body), - responseType: responseType ?? 'json', - }; - } - - private rxjsRequest = (params: AjaxConfig): Observable> => - of(params).pipe( - map((request) => { - this.middleware.filter((item) => item.pre).forEach((mw) => (request = mw.pre!(request))); - return request; - }), - concatMap((args) => - ajax(args).pipe( - map((response) => { - this.middleware.filter((item) => item.post).forEach((mw) => (response = mw.post!(response))); - return response; - }) - ) - ) - ); - - /** - * Create a shallow clone of `this` by constructing a new instance - * and then shallow cloning data members. - */ - private clone = (): this => - Object.assign(Object.create(Object.getPrototypeOf(this)), this); -} - -/** - * @deprecated - * export for not being a breaking change - */ -export class RequiredError extends Error { - override name: 'RequiredError' = 'RequiredError'; -} - -export const COLLECTION_FORMATS = { - csv: ',', - ssv: ' ', - tsv: '\t', - pipes: '|', -}; - -export type Json = any; -export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; -export type HttpHeaders = { [key: string]: string }; -export type HttpQuery = Partial<{ [key: string]: string | number | null | boolean | Array }>; // partial is needed for strict mode -export type HttpBody = Json | FormData; - -export interface RequestOpts extends AjaxConfig { - // TODO: replace custom 'query' prop with 'queryParams' - query?: HttpQuery; // additional prop - // the following props have improved types over AjaxRequest - method: HttpMethod; - headers?: HttpHeaders; - body?: HttpBody; -} - -export interface ResponseOpts { - response?: 'raw'; -} - -export interface OperationOpts { - responseOpts?: ResponseOpts; -} - -export const encodeURI = (value: any) => encodeURIComponent(`${value}`); - -const queryString = (params: HttpQuery): string => Object.entries(params) - .map(([key, value]) => value instanceof Array - ? value.map((val) => `${encodeURI(key)}=${encodeURI(val)}`).join('&') - : `${encodeURI(key)}=${encodeURI(value)}` - ) - .join('&'); - -export const throwIfNullOrUndefined = (value: any, paramName: string, nickname: string) => { - if (value == null) { - throw new Error(`Parameter "${paramName}" was null or undefined when calling "${nickname}".`); - } -}; - -export interface Middleware { - pre?(request: AjaxConfig): AjaxConfig; - post?(response: AjaxResponse): AjaxResponse; -} diff --git a/src/servers.ts b/src/servers.ts deleted file mode 100644 index ac4547d..0000000 --- a/src/servers.ts +++ /dev/null @@ -1,45 +0,0 @@ -/** - * - * Represents the configuration of a server including its - * url template and variable configuration based on the url. - * - */ -export class ServerConfiguration { - public constructor(private url: string, private variableConfiguration: T, private description: string) {} - - /** - * Sets the value of the variables of this server. - * - * @param variableConfiguration a partial variable configuration for the variables contained in the url - */ - public setVariables(variableConfiguration: Partial) { - Object.assign(this.variableConfiguration, variableConfiguration); - } - - public getConfiguration(): T { - return this.variableConfiguration; - } - - public getDescription(): string { - return this.description; - } - - /** - * Constructions the URL this server using the url with variables - * replaced with their respective values - */ - public getUrl(): string { - let replacedUrl = this.url; - for (const key in this.variableConfiguration) { - if (this.variableConfiguration.hasOwnProperty(key)) { - const re = new RegExp("{" + key + "}","g"); - replacedUrl = replacedUrl.replace(re, this.variableConfiguration[key]); - } - } - return replacedUrl; - } -} - -const server1 = new ServerConfiguration<{ }>("https://push.databox.com", { }, "Dev mode server description"); - -export const servers = [server1]; diff --git a/src/src/apis/DefaultApi.ts b/src/src/apis/DefaultApi.ts new file mode 100644 index 0000000..f7c7af3 --- /dev/null +++ b/src/src/apis/DefaultApi.ts @@ -0,0 +1,211 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Static OpenAPI document of Push API resource + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 0.4.3 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import * as runtime from '../runtime'; +import type { + PushData, +} from '../models/index'; +import { + PushDataFromJSON, + PushDataToJSON, +} from '../models/index'; + +export interface DataMetricKeyDeleteRequest { + metricKey: string; +} + +export interface DataPostRequest { + pushData?: Array; +} + +export interface MetrickeysPostRequest { + body?: object; +} + +/** + * + */ +export class DefaultApi extends runtime.BaseAPI { + + /** + */ + async dataDeleteRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && (this.configuration.username !== undefined || this.configuration.password !== undefined)) { + headerParameters["Authorization"] = "Basic " + btoa(this.configuration.username + ":" + this.configuration.password); + } + const response = await this.request({ + path: `/data`, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + */ + async dataDelete(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.dataDeleteRaw(initOverrides); + } + + /** + */ + async dataMetricKeyDeleteRaw(requestParameters: DataMetricKeyDeleteRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + if (requestParameters['metricKey'] == null) { + throw new runtime.RequiredError( + 'metricKey', + 'Required parameter "metricKey" was null or undefined when calling dataMetricKeyDelete().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && (this.configuration.username !== undefined || this.configuration.password !== undefined)) { + headerParameters["Authorization"] = "Basic " + btoa(this.configuration.username + ":" + this.configuration.password); + } + const response = await this.request({ + path: `/data/{metricKey}`.replace(`{${"metricKey"}}`, encodeURIComponent(String(requestParameters['metricKey']))), + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + */ + async dataMetricKeyDelete(requestParameters: DataMetricKeyDeleteRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.dataMetricKeyDeleteRaw(requestParameters, initOverrides); + } + + /** + */ + async dataPostRaw(requestParameters: DataPostRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && (this.configuration.username !== undefined || this.configuration.password !== undefined)) { + headerParameters["Authorization"] = "Basic " + btoa(this.configuration.username + ":" + this.configuration.password); + } + const response = await this.request({ + path: `/data`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters['pushData']!.map(PushDataToJSON), + }, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + */ + async dataPost(requestParameters: DataPostRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.dataPostRaw(requestParameters, initOverrides); + } + + /** + */ + async metrickeysGetRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && (this.configuration.username !== undefined || this.configuration.password !== undefined)) { + headerParameters["Authorization"] = "Basic " + btoa(this.configuration.username + ":" + this.configuration.password); + } + const response = await this.request({ + path: `/metrickeys`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + */ + async metrickeysGet(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.metrickeysGetRaw(initOverrides); + } + + /** + */ + async metrickeysPostRaw(requestParameters: MetrickeysPostRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && (this.configuration.username !== undefined || this.configuration.password !== undefined)) { + headerParameters["Authorization"] = "Basic " + btoa(this.configuration.username + ":" + this.configuration.password); + } + const response = await this.request({ + path: `/metrickeys`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters['body'] as any, + }, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + */ + async metrickeysPost(requestParameters: MetrickeysPostRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.metrickeysPostRaw(requestParameters, initOverrides); + } + + /** + */ + async pingGetRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && (this.configuration.username !== undefined || this.configuration.password !== undefined)) { + headerParameters["Authorization"] = "Basic " + btoa(this.configuration.username + ":" + this.configuration.password); + } + const response = await this.request({ + path: `/ping`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + */ + async pingGet(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.pingGetRaw(initOverrides); + } + +} diff --git a/src/src/apis/index.ts b/src/src/apis/index.ts new file mode 100644 index 0000000..69c44c0 --- /dev/null +++ b/src/src/apis/index.ts @@ -0,0 +1,3 @@ +/* tslint:disable */ +/* eslint-disable */ +export * from './DefaultApi'; diff --git a/src/src/index.ts b/src/src/index.ts new file mode 100644 index 0000000..bebe8bb --- /dev/null +++ b/src/src/index.ts @@ -0,0 +1,5 @@ +/* tslint:disable */ +/* eslint-disable */ +export * from './runtime'; +export * from './apis/index'; +export * from './models/index'; diff --git a/src/src/models/ModelApiResponse.ts b/src/src/models/ModelApiResponse.ts new file mode 100644 index 0000000..76f74d0 --- /dev/null +++ b/src/src/models/ModelApiResponse.ts @@ -0,0 +1,68 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Static OpenAPI document of Push API resource + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 0.4.3 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface ModelApiResponse + */ +export interface ModelApiResponse { + /** + * + * @type {string} + * @memberof ModelApiResponse + */ + status?: string; + /** + * + * @type {string} + * @memberof ModelApiResponse + */ + message?: string; +} + +/** + * Check if a given object implements the ModelApiResponse interface. + */ +export function instanceOfModelApiResponse(value: object): value is ModelApiResponse { + return true; +} + +export function ModelApiResponseFromJSON(json: any): ModelApiResponse { + return ModelApiResponseFromJSONTyped(json, false); +} + +export function ModelApiResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ModelApiResponse { + if (json == null) { + return json; + } + return { + + 'status': json['status'] == null ? undefined : json['status'], + 'message': json['message'] == null ? undefined : json['message'], + }; +} + +export function ModelApiResponseToJSON(value?: ModelApiResponse | null): any { + if (value == null) { + return value; + } + return { + + 'status': value['status'], + 'message': value['message'], + }; +} + diff --git a/src/src/models/PushData.ts b/src/src/models/PushData.ts new file mode 100644 index 0000000..654290b --- /dev/null +++ b/src/src/models/PushData.ts @@ -0,0 +1,115 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Static OpenAPI document of Push API resource + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 0.4.3 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { PushDataAttribute } from './PushDataAttribute'; +import { + PushDataAttributeFromJSON, + PushDataAttributeFromJSONTyped, + PushDataAttributeToJSON, +} from './PushDataAttribute'; + +/** + * + * @export + * @interface PushData + */ +export interface PushData { + /** + * + * @type {Array} + * @memberof PushData + */ + attributes?: Array; + /** + * + * @type {string} + * @memberof PushData + */ + date?: string; + /** + * + * @type {string} + * @memberof PushData + */ + key?: string; + /** + * + * @type {string} + * @memberof PushData + */ + periodFrom?: string; + /** + * + * @type {string} + * @memberof PushData + */ + periodTo?: string; + /** + * + * @type {string} + * @memberof PushData + */ + unit?: string; + /** + * + * @type {number} + * @memberof PushData + */ + value?: number; +} + +/** + * Check if a given object implements the PushData interface. + */ +export function instanceOfPushData(value: object): value is PushData { + return true; +} + +export function PushDataFromJSON(json: any): PushData { + return PushDataFromJSONTyped(json, false); +} + +export function PushDataFromJSONTyped(json: any, ignoreDiscriminator: boolean): PushData { + if (json == null) { + return json; + } + return { + + 'attributes': json['attributes'] == null ? undefined : ((json['attributes'] as Array).map(PushDataAttributeFromJSON)), + 'date': json['date'] == null ? undefined : json['date'], + 'key': json['key'] == null ? undefined : json['key'], + 'periodFrom': json['periodFrom'] == null ? undefined : json['periodFrom'], + 'periodTo': json['periodTo'] == null ? undefined : json['periodTo'], + 'unit': json['unit'] == null ? undefined : json['unit'], + 'value': json['value'] == null ? undefined : json['value'], + }; +} + +export function PushDataToJSON(value?: PushData | null): any { + if (value == null) { + return value; + } + return { + + 'attributes': value['attributes'] == null ? undefined : ((value['attributes'] as Array).map(PushDataAttributeToJSON)), + 'date': value['date'], + 'key': value['key'], + 'periodFrom': value['periodFrom'], + 'periodTo': value['periodTo'], + 'unit': value['unit'], + 'value': value['value'], + }; +} + diff --git a/src/src/models/PushDataAttribute.ts b/src/src/models/PushDataAttribute.ts new file mode 100644 index 0000000..723670d --- /dev/null +++ b/src/src/models/PushDataAttribute.ts @@ -0,0 +1,68 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Static OpenAPI document of Push API resource + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 0.4.3 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface PushDataAttribute + */ +export interface PushDataAttribute { + /** + * + * @type {string} + * @memberof PushDataAttribute + */ + key?: string; + /** + * + * @type {string} + * @memberof PushDataAttribute + */ + value?: string; +} + +/** + * Check if a given object implements the PushDataAttribute interface. + */ +export function instanceOfPushDataAttribute(value: object): value is PushDataAttribute { + return true; +} + +export function PushDataAttributeFromJSON(json: any): PushDataAttribute { + return PushDataAttributeFromJSONTyped(json, false); +} + +export function PushDataAttributeFromJSONTyped(json: any, ignoreDiscriminator: boolean): PushDataAttribute { + if (json == null) { + return json; + } + return { + + 'key': json['key'] == null ? undefined : json['key'], + 'value': json['value'] == null ? undefined : json['value'], + }; +} + +export function PushDataAttributeToJSON(value?: PushDataAttribute | null): any { + if (value == null) { + return value; + } + return { + + 'key': value['key'], + 'value': value['value'], + }; +} + diff --git a/src/src/models/State.ts b/src/src/models/State.ts new file mode 100644 index 0000000..6f88713 --- /dev/null +++ b/src/src/models/State.ts @@ -0,0 +1,49 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Static OpenAPI document of Push API resource + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 0.4.3 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * + * @export + */ +export const State = { + Down: 'DOWN', + Up: 'UP' +} as const; +export type State = typeof State[keyof typeof State]; + + +export function instanceOfState(value: any): boolean { + for (const key in State) { + if (Object.prototype.hasOwnProperty.call(State, key)) { + if (State[key] === value) { + return true; + } + } + } + return false; +} + +export function StateFromJSON(json: any): State { + return StateFromJSONTyped(json, false); +} + +export function StateFromJSONTyped(json: any, ignoreDiscriminator: boolean): State { + return json as State; +} + +export function StateToJSON(value?: State | null): any { + return value as any; +} + diff --git a/src/models/index.ts b/src/src/models/index.ts similarity index 53% rename from src/models/index.ts rename to src/src/models/index.ts index 7f2f918..0825fa7 100644 --- a/src/models/index.ts +++ b/src/src/models/index.ts @@ -1,4 +1,6 @@ -export * from './ApiResponse'; +/* tslint:disable */ +/* eslint-disable */ +export * from './ModelApiResponse'; export * from './PushData'; export * from './PushDataAttribute'; export * from './State'; diff --git a/src/src/runtime.ts b/src/src/runtime.ts new file mode 100644 index 0000000..6c1c675 --- /dev/null +++ b/src/src/runtime.ts @@ -0,0 +1,426 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Static OpenAPI document of Push API resource + * Push API resources Open API documentation + * + * The version of the OpenAPI document: 0.4.3 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const BASE_PATH = "https://push.databox.com".replace(/\/+$/, ""); + +export interface ConfigurationParameters { + basePath?: string; // override base path + fetchApi?: FetchAPI; // override for fetch implementation + middleware?: Middleware[]; // middleware to apply before/after fetch requests + queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings + username?: string; // parameter for basic security + password?: string; // parameter for basic security + apiKey?: string | Promise | ((name: string) => string | Promise); // parameter for apiKey security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security + headers?: HTTPHeaders; //header params we want to use on every request + credentials?: RequestCredentials; //value for the credentials param we want to use on each request +} + +export class Configuration { + constructor(private configuration: ConfigurationParameters = {}) {} + + set config(configuration: Configuration) { + this.configuration = configuration; + } + + get basePath(): string { + return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; + } + + get fetchApi(): FetchAPI | undefined { + return this.configuration.fetchApi; + } + + get middleware(): Middleware[] { + return this.configuration.middleware || []; + } + + get queryParamsStringify(): (params: HTTPQuery) => string { + return this.configuration.queryParamsStringify || querystring; + } + + get username(): string | undefined { + return this.configuration.username; + } + + get password(): string | undefined { + return this.configuration.password; + } + + get apiKey(): ((name: string) => string | Promise) | undefined { + const apiKey = this.configuration.apiKey; + if (apiKey) { + return typeof apiKey === 'function' ? apiKey : () => apiKey; + } + return undefined; + } + + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { + const accessToken = this.configuration.accessToken; + if (accessToken) { + return typeof accessToken === 'function' ? accessToken : async () => accessToken; + } + return undefined; + } + + get headers(): HTTPHeaders | undefined { + return this.configuration.headers; + } + + get credentials(): RequestCredentials | undefined { + return this.configuration.credentials; + } +} + +export const DefaultConfig = new Configuration(); + +/** + * This is the base class for all generated API classes. + */ +export class BaseAPI { + + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private middleware: Middleware[]; + + constructor(protected configuration = DefaultConfig) { + this.middleware = configuration.middleware; + } + + withMiddleware(this: T, ...middlewares: Middleware[]) { + const next = this.clone(); + next.middleware = next.middleware.concat(...middlewares); + return next; + } + + withPreMiddleware(this: T, ...preMiddlewares: Array) { + const middlewares = preMiddlewares.map((pre) => ({ pre })); + return this.withMiddleware(...middlewares); + } + + withPostMiddleware(this: T, ...postMiddlewares: Array) { + 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. + */ + protected isJsonMime(mime: string | null | undefined): boolean { + if (!mime) { + return false; + } + return BaseAPI.jsonRegex.test(mime); + } + + protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { + const { url, init } = await this.createFetchParams(context, initOverrides); + const response = await this.fetchApi(url, init); + if (response && (response.status >= 200 && response.status < 300)) { + return response; + } + throw new ResponseError(response, 'Response returned an error code'); + } + + private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) { + 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 + : async () => initOverrides; + + const initParams = { + method: context.method, + headers, + body: context.body, + credentials: this.configuration.credentials, + }; + + const overriddenInit: RequestInit = { + ...initParams, + ...(await initOverrideFn({ + init: initParams, + context, + })) + }; + + let body: any; + 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: RequestInit = { + ...overriddenInit, + body + }; + + return { url, init }; + } + + private fetchApi = async (url: string, init: RequestInit) => { + let fetchParams = { url, init }; + for (const middleware of this.middleware) { + if (middleware.pre) { + fetchParams = await middleware.pre({ + fetch: this.fetchApi, + ...fetchParams, + }) || fetchParams; + } + } + let response: Response | undefined = undefined; + try { + response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init); + } catch (e) { + for (const middleware of this.middleware) { + if (middleware.onError) { + response = await 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 = await middleware.post({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + response: response.clone(), + }) || response; + } + } + return response; + } + + /** + * Create a shallow clone of `this` by constructing a new instance + * and then shallow cloning data members. + */ + private clone(this: T): T { + const constructor = this.constructor as any; + const next = new constructor(this.configuration); + next.middleware = this.middleware.slice(); + return next; + } +}; + +function isBlob(value: any): value is Blob { + return typeof Blob !== 'undefined' && value instanceof Blob; +} + +function isFormData(value: any): value is FormData { + return typeof FormData !== "undefined" && value instanceof FormData; +} + +export class ResponseError extends Error { + override name: "ResponseError" = "ResponseError"; + constructor(public response: Response, msg?: string) { + super(msg); + } +} + +export class FetchError extends Error { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { + super(msg); + } +} + +export class RequiredError extends Error { + override name: "RequiredError" = "RequiredError"; + constructor(public field: string, msg?: string) { + super(msg); + } +} + +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +export type FetchAPI = WindowOrWorkerGlobalScope['fetch']; + +export type Json = any; +export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; +export type HTTPHeaders = { [key: string]: string }; +export type HTTPQuery = { [key: string]: string | number | null | boolean | Array | Set | HTTPQuery }; +export type HTTPBody = Json | FormData | URLSearchParams; +export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody }; +export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original'; + +export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise + +export interface FetchParams { + url: string; + init: RequestInit; +} + +export interface RequestOpts { + path: string; + method: HTTPMethod; + headers: HTTPHeaders; + query?: HTTPQuery; + body?: HTTPBody; +} + +export function querystring(params: HTTPQuery, prefix: string = ''): string { + return Object.keys(params) + .map(key => querystringSingleKey(key, params[key], prefix)) + .filter(part => part.length > 0) + .join('&'); +} + +function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array | Set | HTTPQuery, keyPrefix: string = ''): string { + 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 as HTTPQuery, fullKey); + } + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; +} + +export function mapValues(data: any, fn: (item: any) => any) { + return Object.keys(data).reduce( + (acc, key) => ({ ...acc, [key]: fn(data[key]) }), + {} + ); +} + +export function canConsumeForm(consumes: Consume[]): boolean { + for (const consume of consumes) { + if ('multipart/form-data' === consume.contentType) { + return true; + } + } + return false; +} + +export interface Consume { + contentType: string; +} + +export interface RequestContext { + fetch: FetchAPI; + url: string; + init: RequestInit; +} + +export interface ResponseContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + response: Response; +} + +export interface ErrorContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + error: unknown; + response?: Response; +} + +export interface Middleware { + pre?(context: RequestContext): Promise; + post?(context: ResponseContext): Promise; + onError?(context: ErrorContext): Promise; +} + +export interface ApiResponse { + raw: Response; + value(): Promise; +} + +export interface ResponseTransformer { + (json: any): T; +} + +export class JSONApiResponse { + constructor(public raw: Response, private transformer: ResponseTransformer = (jsonValue: any) => jsonValue) {} + + async value(): Promise { + return this.transformer(await this.raw.json()); + } +} + +export class VoidApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return undefined; + } +} + +export class BlobApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.blob(); + }; +} + +export class TextApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.text(); + }; +} diff --git a/src/tsconfig.json b/src/tsconfig.json index 59a6083..4567ec1 100644 --- a/src/tsconfig.json +++ b/src/tsconfig.json @@ -5,11 +5,9 @@ "module": "commonjs", "moduleResolution": "node", "outDir": "dist", - "rootDir": ".", "lib": [ "es6", - "dom", - "es2017" + "dom" ], "typeRoots": [ "node_modules/@types"