← full-stack-fastapi-template  /  frontend/src/client/core/OpenAPI.ts

1
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
2
import type { ApiRequestOptions } from './ApiRequestOptions';
3
4
type Headers = Record<string, string>;
5
type Middleware<T> = (value: T) => T | Promise<T>;
6
type Resolver<T> = (options: ApiRequestOptions<T>) => Promise<T>;
7
8
export class Interceptors<T> {
9
  _fns: Middleware<T>[];
10
11
  constructor() {
12
    this._fns = [];
13
  }
14
15
  eject(fn: Middleware<T>): void {
16
    const index = this._fns.indexOf(fn);
17
    if (index !== -1) {
18
      this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)];
19
    }
20
  }
21
22
  use(fn: Middleware<T>): void {
23
    this._fns = [...this._fns, fn];
24
  }
25
}
26
27
export type OpenAPIConfig = {
28
	BASE: string;
29
	CREDENTIALS: 'include' | 'omit' | 'same-origin';
30
	ENCODE_PATH?: ((path: string) => string) | undefined;
31
	HEADERS?: Headers | Resolver<Headers> | undefined;
32
	PASSWORD?: string | Resolver<string> | undefined;
33
	TOKEN?: string | Resolver<string> | undefined;
34
	USERNAME?: string | Resolver<string> | undefined;
35
	VERSION: string;
36
	WITH_CREDENTIALS: boolean;
37
	interceptors: {
38
		request: Interceptors<AxiosRequestConfig>;
39
		response: Interceptors<AxiosResponse>;
40
	};
41
};
42
43
export const OpenAPI: OpenAPIConfig = {
44
	BASE: '',
45
	CREDENTIALS: 'include',
46
	ENCODE_PATH: undefined,
47
	HEADERS: undefined,
48
	PASSWORD: undefined,
49
	TOKEN: undefined,
50
	USERNAME: undefined,
51
	VERSION: '0.1.0',
52
	WITH_CREDENTIALS: false,
53
	interceptors: {
54
		request: new Interceptors(),
55
		response: new Interceptors(),
56
	},
57
};