1
0
Fork 0
mirror of https://github.com/xHyroM/waki.git synced 2024-11-24 07:31:06 +01:00

fix: clone body correctly

This commit is contained in:
Jozef Steinhübl 2024-05-20 13:23:51 +02:00
parent 6b5fc7e5ce
commit de12eb244f
No known key found for this signature in database
GPG key ID: E6BC90C91973B08F
2 changed files with 33 additions and 4 deletions

View file

@ -1,4 +1,4 @@
import { getMainProvider, parseProviders, verify } from "./utils"; import { cloneFormData, getMainProvider, parseBody, parseProviders, verify } from "./utils";
export default { export default {
async fetch(request: Request, env: Env, _: ExecutionContext): Promise<Response> { async fetch(request: Request, env: Env, _: ExecutionContext): Promise<Response> {
@ -17,14 +17,14 @@ export default {
providers.sort((a, _) => (a.name === mainProvider?.name ? 1 : -1)); providers.sort((a, _) => (a.name === mainProvider?.name ? 1 : -1));
const body = request.body !== null ? request.body : null; const body = request.body ? await parseBody(request) : null;
let res: Response; let res: Response;
for (const provider of providers) { for (const provider of providers) {
const url = new URL(provider.url); const url = new URL(provider.url);
url.pathname += baseUrl.pathname; url.pathname += baseUrl.pathname;
if (request.body !== null) { if (body !== null) {
// @ts-expect-error expected // @ts-expect-error expected
res = await fetch(url.toString(), { res = await fetch(url.toString(), {
method: request.method, method: request.method,
@ -32,7 +32,7 @@ export default {
...request.headers, ...request.headers,
authorization: `Bearer ${btoa(provider.token)}`, authorization: `Bearer ${btoa(provider.token)}`,
}, },
body: body, body: body(),
}); });
} else { } else {
// @ts-expect-error expected // @ts-expect-error expected

View file

@ -28,3 +28,32 @@ export function parseProviders(providers: string): Provider[] {
export function getMainProvider(providers: Provider[], main: string): Provider | undefined { export function getMainProvider(providers: Provider[], main: string): Provider | undefined {
return providers.find((provider) => provider.name === main) ?? providers[0]; return providers.find((provider) => provider.name === main) ?? providers[0];
} }
export async function parseBody(request: Request): Promise<() => BodyInit> {
const contentType = request.headers.get("content-type");
if (contentType === "multipart/form-data" || contentType === "application/x-www-form-urlencoded") {
const data = await request.formData();
return () => cloneFormData(data);
}
if (contentType === "application/json") {
const data = await request.json();
return () => JSON.stringify(data);
}
const text = await request.text();
return () => text;
}
export function cloneFormData(data: FormData) {
const form = new FormData();
for (const [key, value] of data.entries()) {
if (value instanceof File) {
form.append(key, value, value.name);
} else {
form.append(key, value);
}
}
return form;
}