| 101 | * This is the base class for all generated API classes. |
| 102 | */ |
| 103 | export class BaseAPI { |
| 104 | private static readonly jsonRegex = new RegExp( |
| 105 | "^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$", |
| 106 | "i", |
| 107 | ); |
| 108 | private middleware: Middleware[]; |
| 109 | |
| 110 | constructor(protected configuration = DefaultConfig) { |
| 111 | this.middleware = configuration.middleware; |
| 112 | } |
| 113 | |
| 114 | withMiddleware<T extends BaseAPI>(this: T, ...middlewares: Middleware[]) { |
| 115 | const next = this.clone<T>(); |
| 116 | next.middleware = next.middleware.concat(...middlewares); |
| 117 | return next; |
| 118 | } |
| 119 | |
| 120 | withPreMiddleware<T extends BaseAPI>( |
| 121 | this: T, |
| 122 | ...preMiddlewares: Array<Middleware["pre"]> |
| 123 | ) { |
| 124 | const middlewares = preMiddlewares.map((pre) => ({ pre })); |
| 125 | return this.withMiddleware<T>(...middlewares); |
| 126 | } |
| 127 | |
| 128 | withPostMiddleware<T extends BaseAPI>( |
| 129 | this: T, |
| 130 | ...postMiddlewares: Array<Middleware["post"]> |
| 131 | ) { |
| 132 | const middlewares = postMiddlewares.map((post) => ({ post })); |
| 133 | return this.withMiddleware<T>(...middlewares); |
| 134 | } |
| 135 | |
| 136 | /** |
| 137 | * Check if the given MIME is a JSON MIME. |
| 138 | * JSON MIME examples: |
| 139 | * application/json |
| 140 | * application/json; charset=UTF8 |
| 141 | * APPLICATION/JSON |
| 142 | * application/vnd.company+json |
| 143 | * @param mime - MIME (Multipurpose Internet Mail Extensions) |
| 144 | * @return True if the given MIME is JSON, false otherwise. |
| 145 | */ |
| 146 | protected isJsonMime(mime: string | null | undefined): boolean { |
| 147 | if (!mime) { |
| 148 | return false; |
| 149 | } |
| 150 | return BaseAPI.jsonRegex.test(mime); |
| 151 | } |
| 152 | |
| 153 | protected async request( |
| 154 | context: RequestOpts, |
| 155 | initOverrides?: RequestInit | InitOverrideFunction, |
| 156 | ): Promise<Response> { |
| 157 | const { url, init } = await this.createFetchParams(context, initOverrides); |
| 158 | const response = await this.fetchApi(url, init); |
| 159 | if (response && response.status >= 200 && response.status < 300) { |
| 160 | return response; |