- Removed old folder

This commit is contained in:
Ferdi Koomen 2020-09-26 15:17:01 +02:00
parent 2f8d8b0a59
commit cf45ccd2e5
15 changed files with 0 additions and 698 deletions

View File

@ -1,17 +0,0 @@
import { ApiResult } from './ApiResult';
export class ApiError extends Error {
public readonly url: string;
public readonly status: number;
public readonly statusText: string;
public readonly body: any;
constructor(response: ApiResult, message: string) {
super(message);
this.url = response.url;
this.status = response.status;
this.statusText = response.statusText;
this.body = response.body;
}
}

View File

@ -1,11 +0,0 @@
export interface ApiRequestOptions {
readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH';
readonly path: string;
readonly cookies?: Record<string, any>;
readonly headers?: Record<string, any>;
readonly query?: Record<string, any>;
readonly formData?: Record<string, any>;
readonly body?: any;
readonly responseHeader?: string;
readonly errors?: Record<number, string>;
}

View File

@ -1,7 +0,0 @@
export interface ApiResult {
readonly url: string;
readonly ok: boolean;
readonly status: number;
readonly statusText: string;
readonly body: any;
}

View File

@ -1,15 +0,0 @@
interface Config {
BASE: string;
VERSION: string;
CLIENT: 'fetch' | 'xhr' | 'node';
WITH_CREDENTIALS: boolean;
TOKEN: string;
}
export const OpenAPI: Config = {
BASE: 'http://localhost:3000/base',
VERSION: '1.0',
CLIENT: 'fetch',
WITH_CREDENTIALS: false,
TOKEN: '',
};

View File

@ -1,176 +0,0 @@
import { ApiError } from './ApiError';
import { ApiRequestOptions } from './ApiRequestOptions';
import { ApiResult } from './ApiResult';
import { OpenAPI } from './OpenAPI';
function isDefined<T>(value: T | null | undefined): value is Exclude<T, null | undefined> {
return value !== undefined && value !== null;
}
function getQueryString(params: Record<string, any>): string {
const qs: string[] = [];
Object.keys(params).forEach(key => {
const value = params[key];
if (isDefined(value)) {
if (Array.isArray(value)) {
value.forEach(value => {
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
});
} else {
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
}
}
});
if (qs.length > 0) {
return `?${qs.join('&')}`;
}
return '';
}
function getUrl(options: ApiRequestOptions): string {
const path = options.path.replace(/[:]/g, '_');
const url = `${OpenAPI.BASE}${path}`;
if (options.query) {
return url + getQueryString(options.query);
}
return url;
}
function getFormData(params: Record<string, any>): FormData {
const formData = new FormData();
Object.keys(params).forEach(key => {
const value = params[key];
if (isDefined(value)) {
formData.append(key, value);
}
});
return formData;
}
function getHeaders(options: ApiRequestOptions): Headers {
const headers = new Headers({
Accept: 'application/json',
...options.headers,
});
if (OpenAPI.TOKEN !== null && OpenAPI.TOKEN !== '') {
headers.append('Authorization', `Bearer ${OpenAPI.TOKEN}`);
}
if (options.body) {
if (options.body instanceof Blob) {
if (options.body.type) {
headers.append('Content-Type', options.body.type);
}
} else if (typeof options.body === 'string') {
headers.append('Content-Type', 'text/plain');
} else {
headers.append('Content-Type', 'application/json');
}
}
return headers;
}
function getRequestBody(options: ApiRequestOptions): BodyInit | undefined {
if (options.formData) {
return getFormData(options.formData);
}
if (options.body) {
if (options.body instanceof Blob) {
return options.body;
} else if (typeof options.body === 'string') {
return options.body;
} else {
return JSON.stringify(options.body);
}
}
return undefined;
}
async function sendRequest(options: ApiRequestOptions, url: string): Promise<Response> {
const request: RequestInit = {
method: options.method,
headers: getHeaders(options),
body: getRequestBody(options),
};
return await fetch(url, request);
}
function getResponseHeader(response: Response, responseHeader?: string): string | null {
if (responseHeader) {
const content = response.headers.get(responseHeader);
if (typeof content === 'string') {
return content;
}
}
return null;
}
async function getResponseBody(response: Response): Promise<any> {
try {
const contentType = response.headers.get('Content-Type');
if (contentType) {
switch (contentType.toLowerCase()) {
case 'application/json':
case 'application/json; charset=utf-8':
return await response.json();
default:
return await response.text();
}
}
} catch (e) {
console.error(e);
}
return null;
}
function catchErrors(options: ApiRequestOptions, result: ApiResult): void {
const errors: Record<number, string> = {
400: 'Bad Request',
401: 'Unauthorized',
403: 'Forbidden',
404: 'Not Found',
500: 'Internal Server Error',
502: 'Bad Gateway',
503: 'Service Unavailable',
...options.errors,
};
const error = errors[result.status];
if (error) {
throw new ApiError(result, error);
}
if (!result.ok) {
throw new ApiError(result, 'Generic Error');
}
}
/**
* Request using fetch
* @param options Request options
* @result ApiResult
* @throws ApiError
*/
export async function request(options: ApiRequestOptions): Promise<ApiResult> {
const url = getUrl(options);
const response = await sendRequest(options, url);
const responseBody = await getResponseBody(response);
const responseHeader = getResponseHeader(response, options.responseHeader);
const result: ApiResult = {
url,
ok: response.ok,
status: response.status,
statusText: response.statusText,
body: responseHeader || responseBody,
};
catchErrors(options, result);
return result;
}

View File

@ -1,17 +0,0 @@
import { ApiResult } from './ApiResult';
export class ApiError extends Error {
public readonly url: string;
public readonly status: number;
public readonly statusText: string;
public readonly body: any;
constructor(response: ApiResult, message: string) {
super(message);
this.url = response.url;
this.status = response.status;
this.statusText = response.statusText;
this.body = response.body;
}
}

View File

@ -1,11 +0,0 @@
export interface ApiRequestOptions {
readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH';
readonly path: string;
readonly cookies?: Record<string, any>;
readonly headers?: Record<string, any>;
readonly query?: Record<string, any>;
readonly formData?: Record<string, any>;
readonly body?: any;
readonly responseHeader?: string;
readonly errors?: Record<number, string>;
}

View File

@ -1,7 +0,0 @@
export interface ApiResult {
readonly url: string;
readonly ok: boolean;
readonly status: number;
readonly statusText: string;
readonly body: any;
}

View File

@ -1,15 +0,0 @@
interface Config {
BASE: string;
VERSION: string;
CLIENT: 'fetch' | 'xhr' | 'node';
WITH_CREDENTIALS: boolean;
TOKEN: string;
}
export const OpenAPI: Config = {
BASE: 'http://localhost:3000/base',
VERSION: '1.0',
CLIENT: 'node',
WITH_CREDENTIALS: false,
TOKEN: '',
};

View File

@ -1,179 +0,0 @@
import * as FormData from 'form-data';
import fetch, { BodyInit, Headers, RequestInit, Response } from 'node-fetch';
import { ApiError } from './ApiError';
import { ApiRequestOptions } from './ApiRequestOptions';
import { ApiResult } from './ApiResult';
import { OpenAPI } from './OpenAPI';
function isDefined<T>(value: T | null | undefined): value is Exclude<T, null | undefined> {
return value !== undefined && value !== null;
}
function getQueryString(params: Record<string, any>): string {
const qs: string[] = [];
Object.keys(params).forEach(key => {
const value = params[key];
if (isDefined(value)) {
if (Array.isArray(value)) {
value.forEach(value => {
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
});
} else {
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
}
}
});
if (qs.length > 0) {
return `?${qs.join('&')}`;
}
return '';
}
function getUrl(options: ApiRequestOptions): string {
const path = options.path.replace(/[:]/g, '_');
const url = `${OpenAPI.BASE}${path}`;
if (options.query) {
return url + getQueryString(options.query);
}
return url;
}
function getFormData(params: Record<string, any>): FormData {
const formData = new FormData();
Object.keys(params).forEach(key => {
const value = params[key];
if (isDefined(value)) {
formData.append(key, value);
}
});
return formData;
}
function getHeaders(options: ApiRequestOptions): Headers {
const headers = new Headers({
Accept: 'application/json',
...options.headers,
});
if (OpenAPI.TOKEN !== null && OpenAPI.TOKEN !== '') {
headers.append('Authorization', `Bearer ${OpenAPI.TOKEN}`);
}
if (options.body) {
if (options.body instanceof Blob) {
if (options.body.type) {
headers.append('Content-Type', options.body.type);
}
} else if (typeof options.body === 'string') {
headers.append('Content-Type', 'text/plain');
} else {
headers.append('Content-Type', 'application/json');
}
}
return headers;
}
function getRequestBody(options: ApiRequestOptions): BodyInit | undefined {
if (options.formData) {
return getFormData(options.formData);
}
if (options.body) {
if (options.body instanceof ArrayBuffer) {
return options.body;
} else if (typeof options.body === 'string') {
return options.body;
} else {
return JSON.stringify(options.body);
}
}
return undefined;
}
async function sendRequest(options: ApiRequestOptions, url: string): Promise<Response> {
const request: RequestInit = {
method: options.method,
headers: getHeaders(options),
body: getRequestBody(options),
};
return await fetch(url, request);
}
function getResponseHeader(response: Response, responseHeader?: string): string | null {
if (responseHeader) {
const content = response.headers.get(responseHeader);
if (typeof content === 'string') {
return content;
}
}
return null;
}
async function getResponseBody(response: Response): Promise<any> {
try {
const contentType = response.headers.get('Content-Type');
if (contentType) {
switch (contentType.toLowerCase()) {
case 'application/json':
case 'application/json; charset=utf-8':
return await response.json();
default:
return await response.text();
}
}
} catch (e) {
console.error(e);
}
return null;
}
function catchErrors(options: ApiRequestOptions, result: ApiResult): void {
const errors: Record<number, string> = {
400: 'Bad Request',
401: 'Unauthorized',
403: 'Forbidden',
404: 'Not Found',
500: 'Internal Server Error',
502: 'Bad Gateway',
503: 'Service Unavailable',
...options.errors,
};
const error = errors[result.status];
if (error) {
throw new ApiError(result, error);
}
if (!result.ok) {
throw new ApiError(result, 'Generic Error');
}
}
/**
* Request using node-fetch
* @param options Request options
* @result ApiResult
* @throws ApiError
*/
export async function request(options: ApiRequestOptions): Promise<ApiResult> {
const url = getUrl(options);
const response = await sendRequest(options, url);
const responseBody = await getResponseBody(response);
const responseHeader = getResponseHeader(response, options.responseHeader);
const result: ApiResult = {
url,
ok: response.ok,
status: response.status,
statusText: response.statusText,
body: responseHeader || responseBody,
};
catchErrors(options, result);
return result;
}

View File

@ -1,17 +0,0 @@
import { ApiResult } from './ApiResult';
export class ApiError extends Error {
public readonly url: string;
public readonly status: number;
public readonly statusText: string;
public readonly body: any;
constructor(response: ApiResult, message: string) {
super(message);
this.url = response.url;
this.status = response.status;
this.statusText = response.statusText;
this.body = response.body;
}
}

View File

@ -1,11 +0,0 @@
export interface ApiRequestOptions {
readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH';
readonly path: string;
readonly cookies?: Record<string, any>;
readonly headers?: Record<string, any>;
readonly query?: Record<string, any>;
readonly formData?: Record<string, any>;
readonly body?: any;
readonly responseHeader?: string;
readonly errors?: Record<number, string>;
}

View File

@ -1,7 +0,0 @@
export interface ApiResult {
readonly url: string;
readonly ok: boolean;
readonly status: number;
readonly statusText: string;
readonly body: any;
}

View File

@ -1,15 +0,0 @@
interface Config {
BASE: string;
VERSION: string;
CLIENT: 'fetch' | 'xhr' | 'node';
WITH_CREDENTIALS: boolean;
TOKEN: string;
}
export const OpenAPI: Config = {
BASE: 'http://localhost:3000/base',
VERSION: '1.0',
CLIENT: 'xhr',
WITH_CREDENTIALS: false,
TOKEN: '',
};

View File

@ -1,193 +0,0 @@
import { ApiError } from './ApiError';
import { ApiRequestOptions } from './ApiRequestOptions';
import { ApiResult } from './ApiResult';
import { OpenAPI } from './OpenAPI';
function isDefined<T>(value: T | null | undefined): value is Exclude<T, null | undefined> {
return value !== undefined && value !== null;
}
function isSuccess(status: number): boolean {
return status >= 200 && status < 300;
}
function getQueryString(params: Record<string, any>): string {
const qs: string[] = [];
Object.keys(params).forEach(key => {
const value = params[key];
if (isDefined(value)) {
if (Array.isArray(value)) {
value.forEach(value => {
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
});
} else {
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
}
}
});
if (qs.length > 0) {
return `?${qs.join('&')}`;
}
return '';
}
function getUrl(options: ApiRequestOptions): string {
const path = options.path.replace(/[:]/g, '_');
const url = `${OpenAPI.BASE}${path}`;
if (options.query) {
return url + getQueryString(options.query);
}
return url;
}
function getFormData(params: Record<string, any>): FormData {
const formData = new FormData();
Object.keys(params).forEach(key => {
const value = params[key];
if (isDefined(value)) {
formData.append(key, value);
}
});
return formData;
}
function getHeaders(options: ApiRequestOptions): Headers {
const headers = new Headers({
Accept: 'application/json',
...options.headers,
});
if (OpenAPI.TOKEN !== null && OpenAPI.TOKEN !== '') {
headers.append('Authorization', `Bearer ${OpenAPI.TOKEN}`);
}
if (options.body) {
if (options.body instanceof Blob) {
if (options.body.type) {
headers.append('Content-Type', options.body.type);
}
} else if (typeof options.body === 'string') {
headers.append('Content-Type', 'text/plain');
} else {
headers.append('Content-Type', 'application/json');
}
}
return headers;
}
function getRequestBody(options: ApiRequestOptions): any {
if (options.formData) {
return getFormData(options.formData);
}
if (options.body) {
if (options.body instanceof Blob) {
return options.body;
} else if (typeof options.body === 'string') {
return options.body;
} else {
return JSON.stringify(options.body);
}
}
return undefined;
}
function sendRequest(options: ApiRequestOptions, url: string): Promise<XMLHttpRequest> {
return new Promise<XMLHttpRequest>((resolve, reject) => {
try {
const xhr = new XMLHttpRequest();
xhr.open(options.method, url, true);
xhr.withCredentials = OpenAPI.WITH_CREDENTIALS;
const headers = getHeaders(options);
headers.forEach((value, key) => {
xhr.setRequestHeader(key, value);
});
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
resolve(xhr);
}
};
xhr.send(getRequestBody(options));
} catch (error) {
reject(error);
}
});
}
function getResponseHeader(xhr: XMLHttpRequest, responseHeader?: string): string | null {
if (responseHeader) {
const content = xhr.getResponseHeader(responseHeader);
if (typeof content === 'string') {
return content;
}
}
return null;
}
function getResponseBody(xhr: XMLHttpRequest): any {
try {
const contentType = xhr.getResponseHeader('Content-Type');
if (contentType) {
switch (contentType.toLowerCase()) {
case 'application/json':
case 'application/json; charset=utf-8':
return JSON.parse(xhr.responseText);
default:
return xhr.responseText;
}
}
} catch (e) {
console.error(e);
}
return null;
}
function catchErrors(options: ApiRequestOptions, result: ApiResult): void {
const errors: Record<number, string> = {
400: 'Bad Request',
401: 'Unauthorized',
403: 'Forbidden',
404: 'Not Found',
500: 'Internal Server Error',
502: 'Bad Gateway',
503: 'Service Unavailable',
...options.errors,
};
const error = errors[result.status];
if (error) {
throw new ApiError(result, error);
}
if (!result.ok) {
throw new ApiError(result, 'Generic Error');
}
}
/**
* Request using XHR
* @param options Request options
* @result ApiResult
* @throws ApiError
*/
export async function request(options: ApiRequestOptions): Promise<ApiResult> {
const url = getUrl(options);
const response = await sendRequest(options, url);
const responseBody = getResponseBody(response);
const responseHeader = getResponseHeader(response, options.responseHeader);
const result: ApiResult = {
url,
ok: isSuccess(response.status),
status: response.status,
statusText: response.statusText,
body: responseHeader || responseBody,
};
catchErrors(options, result);
return result;
}