diff --git a/module/discord-request-manager.ts b/module/discord-request-manager.ts index 6859de630..f9d7452f1 100644 --- a/module/discord-request-manager.ts +++ b/module/discord-request-manager.ts @@ -4,53 +4,42 @@ import { RequestMethod } from "../types/fetch.ts" // type RequestBody = string | Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams | null | undefined export default class DiscordDiscordRequestManager { - client: Client - token: string - - constructor(client: Client, token: string) { - this.client = client - this.token = token + constructor(public client: Client, public token: string) { + this.client = client; + this.token = token; } async get(url: string, body?: unknown) { - const headers = this.getDiscordHeaders() - return fetch(url, { headers, body: body ? JSON.stringify(body) : undefined }).then(res => res.json()) + return this.thenToJSON(this.runMethod(RequestMethod.Get, url, body)); } async post(url: string, body?: unknown) { - const headers = this.getDiscordHeaders() - return fetch(url, { - method: RequestMethod.Post, - headers, - body: body ? JSON.stringify(body) : undefined - }).then(res => res.json()) + return this.thenToJSON(this.runMethod(RequestMethod.Post, url, body)); } async delete(url: string, body?: unknown) { - const headers = this.getDiscordHeaders() - return fetch(url, { - method: RequestMethod.Delete, - headers, - body: body ? JSON.stringify(body) : undefined - }) + return this.runMethod(RequestMethod.Delete, url, body); } async patch(url: string, body: unknown) { - const headers = this.getDiscordHeaders() - return fetch(url, { - method: RequestMethod.Patch, - headers, - body: body ? JSON.stringify(body) : undefined - }).then(res => res.json()) + return this.thenToJSON(this.runMethod(RequestMethod.Patch, url, body)); } async put(url: string, body: unknown) { - const headers = this.getDiscordHeaders() + return this.runMethod(RequestMethod.Put, url, body); + } + + protected async thenToJSON (promise: Promise) { + return promise.then(response => response.json()); + } + + protected async runMethod (method: RequestMethod, url: string, body?: unknown) { + const headers = this.getDiscordHeaders(); return fetch(url, { - method: RequestMethod.Put, + method, headers, body: body ? JSON.stringify(body) : undefined - }).then(res => res.json()) + }); } // The Record type here plays nice with Deno's `fetch.headers` expected type.