import fetch from "node-fetch"; import * as responses from "./responses"; interface Options { baseUrl: string; apiKey?: string; } export default class { 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) { const error = new responses.AgcError(response); await error.tryParse(); throw error; } return response.json(); } }