All files / src/utils proxy.ts

100% Statements 20/20
100% Branches 3/3
100% Functions 1/1
100% Lines 20/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 331x                   1x 3x 3x 3x 3x 3x 3x   3x 3x 1x 1x   3x 3x 3x 3x 3x 3x   3x 3x  
import { ENV } from '@/constants';
 
/**
 * Proxies an incoming request from Astro middleware to the target API endpoint.
 *
 * @param context - The Astro middleware context containing the original request.
 * @param targetPath - The path to append to the API endpoint (e.g., "/rpc" or "/ws").
 * @param options - Optional fetch options to override the default request init.
 * @returns A Promise resolving to the proxied fetch Response object.
 */
export const proxyRequest = async (
  context: { request: Request },
  targetPath: string,
  options?: RequestInit,
) => {
  const url = new URL(ENV.API_ENDPOINT + targetPath);
  const { method, headers } = context.request;
 
  let body: BodyInit | undefined;
  if (method !== 'GET' && method !== 'HEAD') {
    body = await context.request.arrayBuffer();
  }
 
  const proxyReq = new Request(url.toString(), {
    method,
    headers,
    body,
    ...options,
  });
 
  return fetch(proxyReq);
};