import z from "zod";

/**
 * 
 * @param schema - The schema to parse the response with
 * @param url - The URL to request
 * @param headers - The headers to send with the request
 * @returns The parsed response or null if the request fails
 */
export async function request<S extends z.ZodType>(
  schema: S,
  url: string,
  headers: Record<string, string> = {}
): Promise<z.infer<S> | null> {
  try {
    const response = await fetch(url, { headers });
    if (!response.ok) {
      throw new Error(
        `Got HTTP error: ${response.statusText}, url: ${url}`
      );
    }
    const data = await response.json();
    return schema.parse(data);
  } catch (error) {
    console.error(error);
    return null;
  }
}