mirror of
https://github.com/discordeno/discordeno.git
synced 2026-06-02 17:00:08 +00:00
* feat: standalone rest server * desc * fmt * <3 vlad * Update src/rest/README.md Co-authored-by: Ayyan <ayyantee@gmail.com> * Update src/rest/README.md Co-authored-by: Ayyan <ayyantee@gmail.com> * Update README.md * Update src/rest/deps.ts Co-authored-by: Ayyan <ayyantee@gmail.com> * Update src/rest/queue.ts Co-authored-by: Ayyan <ayyantee@gmail.com> * chore: ignore no-explicit-any rule * fix(rest): replace with correct import paths * deno fmt * fixes * fmt * use user agent cons * fix typings * Update src/rest/cache.ts Co-authored-by: Ayyan <ayyantee@gmail.com> * Update src/rest/cache.ts Co-authored-by: Ayyan <ayyantee@gmail.com> Co-authored-by: Ayyan <ayyantee@gmail.com>
60 lines
1.8 KiB
TypeScript
60 lines
1.8 KiB
TypeScript
// SERVERLESS REST CLIENT THAT CAN WORK ACROSS SHARDS/WORKERS TO COMMUNICATE GLOBAL RATE LIMITS EASILY
|
|
import { restCache } from "./cache.ts";
|
|
import { serve, ServerRequest } from "./deps.ts";
|
|
import { processRequest } from "./request.ts";
|
|
import { RestServerOptions } from "./types/mod.ts";
|
|
|
|
/** Begins an http server that will handle incoming requests. */
|
|
export async function startRESTServer(options: RestServerOptions) {
|
|
const server = serve({ port: options.port });
|
|
|
|
for await (const request of server) {
|
|
handlePayload(request, options).catch((error) => {
|
|
restCache.eventHandlers.error("processRequest", error);
|
|
});
|
|
}
|
|
}
|
|
|
|
/** Handler function for every request. Converts to json, verified authorization & requirements and begins processing the request */
|
|
async function handlePayload(
|
|
request: ServerRequest,
|
|
options: RestServerOptions,
|
|
) {
|
|
// INSTANTLY IGNORE ANY REQUESTS THAT DON'T HAVE THE SECRET AUTHORIZATION KEY
|
|
const authorization = request.headers.get("authorization");
|
|
if (authorization !== options.authorization) return;
|
|
|
|
// READ BUFFER AFTER AUTH CHECK
|
|
const buffer = await Deno.readAll(request.body);
|
|
|
|
try {
|
|
// CONVERT THE BODY TO JSON
|
|
const data = JSON.parse(new TextDecoder().decode(buffer));
|
|
if (!data.url) {
|
|
return request.respond(
|
|
{
|
|
status: 400,
|
|
body: JSON.stringify({ error: "No URL was provided." }),
|
|
},
|
|
);
|
|
}
|
|
if (!data.method) {
|
|
return request.respond(
|
|
{
|
|
status: 400,
|
|
body: JSON.stringify({ error: "No METHOD was provided." }),
|
|
},
|
|
);
|
|
}
|
|
|
|
// PROCESS THE REQUEST
|
|
await processRequest(
|
|
request,
|
|
{ method: data.method, url: data.url, body: data.body, retryCount: 0 },
|
|
options,
|
|
);
|
|
} catch (error) {
|
|
restCache.eventHandlers.error("serverRequest", error);
|
|
}
|
|
}
|