mirror of
https://github.com/xHyroM/waki.git
synced 2024-11-10 01:18:07 +01:00
fix: clone body correctly
This commit is contained in:
parent
6b5fc7e5ce
commit
de12eb244f
2 changed files with 33 additions and 4 deletions
|
@ -1,4 +1,4 @@
|
|||
import { getMainProvider, parseProviders, verify } from "./utils";
|
||||
import { cloneFormData, getMainProvider, parseBody, parseProviders, verify } from "./utils";
|
||||
|
||||
export default {
|
||||
async fetch(request: Request, env: Env, _: ExecutionContext): Promise<Response> {
|
||||
|
@ -17,14 +17,14 @@ export default {
|
|||
|
||||
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;
|
||||
for (const provider of providers) {
|
||||
const url = new URL(provider.url);
|
||||
url.pathname += baseUrl.pathname;
|
||||
|
||||
if (request.body !== null) {
|
||||
if (body !== null) {
|
||||
// @ts-expect-error expected
|
||||
res = await fetch(url.toString(), {
|
||||
method: request.method,
|
||||
|
@ -32,7 +32,7 @@ export default {
|
|||
...request.headers,
|
||||
authorization: `Bearer ${btoa(provider.token)}`,
|
||||
},
|
||||
body: body,
|
||||
body: body(),
|
||||
});
|
||||
} else {
|
||||
// @ts-expect-error expected
|
||||
|
|
29
src/utils.ts
29
src/utils.ts
|
@ -28,3 +28,32 @@ export function parseProviders(providers: string): Provider[] {
|
|||
export function getMainProvider(providers: Provider[], main: string): Provider | undefined {
|
||||
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;
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue