Initial commit
This commit is contained in:
50
src/lib/api/upstreamProxy.ts
Normal file
50
src/lib/api/upstreamProxy.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
export const UPSTREAM_API =
|
||||
process.env.UPSTREAM_API_URL ?? "https://api.modstagram.ir";
|
||||
|
||||
type ProxyOptions = {
|
||||
stripAuth?: boolean;
|
||||
};
|
||||
|
||||
export async function proxyToUpstream(
|
||||
req: Request,
|
||||
upstreamPath: string,
|
||||
options?: ProxyOptions
|
||||
): Promise<Response> {
|
||||
const url = new URL(upstreamPath, UPSTREAM_API);
|
||||
const incoming = new URL(req.url);
|
||||
url.search = incoming.search;
|
||||
|
||||
const headers = new Headers();
|
||||
const contentType = req.headers.get("content-type");
|
||||
if (contentType) headers.set("content-type", contentType);
|
||||
|
||||
if (!options?.stripAuth) {
|
||||
const auth = req.headers.get("authorization");
|
||||
if (auth) headers.set("authorization", auth);
|
||||
}
|
||||
|
||||
const method = req.method;
|
||||
const body =
|
||||
method !== "GET" && method !== "HEAD" ? await req.arrayBuffer() : undefined;
|
||||
|
||||
const upstream = await fetch(url.toString(), {
|
||||
method,
|
||||
headers,
|
||||
body,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
const responseHeaders = new Headers();
|
||||
const upstreamType = upstream.headers.get("content-type");
|
||||
if (upstreamType) responseHeaders.set("content-type", upstreamType);
|
||||
|
||||
return new Response(upstream.body, {
|
||||
status: upstream.status,
|
||||
headers: responseHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
export function isPublicAuthPath(pathSegments: string[]): boolean {
|
||||
const path = pathSegments.join("/");
|
||||
return path.startsWith("login") || path.startsWith("register");
|
||||
}
|
||||
Reference in New Issue
Block a user