All files / src/services/elevenLabsFirebase/exchangeRefreshTokenForIDToken index.ts

66.66% Statements 12/18
33.33% Branches 2/6
100% Functions 1/1
66.66% Lines 12/18

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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57                  1x 1x 1x   1x       1x 1x                               1x 1x   1x                     1x   1x       1x    
import { requestHeaders } from "@/requestHeaders";
import { ELEVEN_LABS_FIREBASE_API_KEY } from "../constants";
import { RequestType } from "./request";
import { Response, fetch as undiciFetch } from "undici";
import { NoThrow } from "@/utils/NoThrow";
import { ResponseSchema } from "./response";
 
// TODO: Handle errors properly
export async function exchangeRefreshTokenForIDToken(req: RequestType) {
    const data = new URLSearchParams();
    data.append("grant_type", "refresh_token");
    data.append("refresh_token", req.refreshToken);
 
    const url = `https://securetoken.googleapis.com/v1/token?key=${ELEVEN_LABS_FIREBASE_API_KEY}`;
 
    let response: Response;
 
    try {
        response = await undiciFetch(url, {
            method: "POST",
            body: data.toString(),
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                ...requestHeaders,
                Origin: "https://elevenlabs.io",
                Referer: "https://elevenlabs.io/",
            },
        });
    } catch (error) {
        return NoThrow.error(error);
    }
 
    let json: unknown;
 
    try {
        json = await response.json();
 
        Iif (response.status !== 200) {
            return NoThrow.error(new Error("Response status !== 200", { cause: json }));
        }
    } catch (error) {
        if (error instanceof SyntaxError) {
            return NoThrow.error(error);
        }
 
        return NoThrow.error(error);
    }
 
    const validatedDataResult = await ResponseSchema.safeParseAsync(json);
 
    Iif (!validatedDataResult.success) {
        return NoThrow.error(validatedDataResult.error);
    }
 
    return NoThrow.success(validatedDataResult.data);
}