import { BaseResponse } from "./responses"; import * as responses from "./responses"; interface Options { baseUrl: string; apiKey?: string; } export class Client { readonly baseHeaders: { [key: string]: string }; baseUrl!: string; requestId: number; constructor(options: Options) { this.requestId = 0; this.baseHeaders = { "Content-Type": "application/json; charset=utf-8", }; this.changeOptions(options); } isReady() { return this.baseUrl !== ""; } changeOptions(options: Options) { this.baseUrl = options.baseUrl; if (options.apiKey != null) { this.baseHeaders["X-API-KEY"] = options.apiKey; } } buildHeaders(headers?: { [key: string]: string }): { [key: string]: string } { if (headers != null) { return { ...this.baseHeaders, ...headers, }; } return { ...this.baseHeaders, }; } async call(method: string, path: string, body?: string): Promise> { return this.callAny(method, path, body); } async callAny(method: string, path: string, body?: string) { const url = `${this.baseUrl}${path}`; const requestId = ++this.requestId; if (requestId) { // 警告回避用。requestIdはそのうちデバッグで使うかも程度 } const response = await fetch(url, { method, headers: this.buildHeaders(), body, }); if (response.status < 200 || response.status >= 300) { let json: responses.BaseResponse | undefined = undefined; try { json = (await response.json()) as responses.BaseResponse; } catch (error) { console.log(error); // logger.log(response); throw new Error(`Can not call ${method} ${url}: ${response.status}, not json response.`); } throw new CallApiError(`Can not call ${method} ${url}: ${response.status}`, json); } return response.json(); } } export class CallApiError extends Error { response: responses.BaseResponse; constructor(message: string, response: responses.BaseResponse) { super(message); this.response = response; } }