Files
discordeno/rest/runProxyMethod.ts
Andreas Fink 88f7529dc4 feat: Modified processGlobalQueue to be able to handle results in runMethod (#2101)
* feat: Modified processGlobalQueue to be able to handle results in runMethod

* Apply suggestions from code review, step 1

Co-authored-by: ITOH <to@itoh.at>

* Apply suggestions from code review, step 2

* Update Files

* Update to resolve/reject

* Fixes & deno fmt

Co-authored-by: ITOH <to@itoh.at>
Co-authored-by: Skillz4Killz <23035000+Skillz4Killz@users.noreply.github.com>
2022-04-10 13:22:56 -04:00

48 lines
1.5 KiB
TypeScript

import { RestManager } from "../bot.ts";
import { RestRequestRejection, RestRequestResponse } from "./rest.ts";
export type ProxyMethodResponse<T> = Omit<RestRequestResponse | RestRequestRejection, "body"> & { body?: T };
// Left out proxy request, because it's not needed here
// this file could also be moved to a plugin.
export async function runProxyMethod<T = any>(
rest: RestManager,
method: "get" | "post" | "put" | "delete" | "patch",
url: string,
body?: unknown,
retryCount = 0,
bucketId?: string,
): Promise<ProxyMethodResponse<T>> {
rest.debug(
`[REST - RequestCreate] Method: ${method} | URL: ${url} | Retry Count: ${retryCount} | Bucket ID: ${bucketId} | Body: ${
JSON.stringify(
body,
)
}`,
);
// No proxy so we need to handle all rate limiting and such
return new Promise((resolve, reject) => {
rest.processRequest(
rest,
{
url,
method,
reject: (data: RestRequestRejection) => {
const { body: b, ...r } = data;
reject({ body: data.status !== 204 ? JSON.parse(b ?? "{}") : (undefined as unknown as T), ...r });
},
respond: (data: RestRequestResponse) => {
const { body: b, ...r } = data;
resolve({ body: data.status !== 204 ? JSON.parse(b ?? "{}") : (undefined as unknown as T), ...r });
},
},
{
bucketId,
body: body as Record<string, unknown> | undefined,
retryCount,
},
);
});
}