Skip to content

Commit f4e1165

Browse files
authored
Dont swallow errors in fetchAccessToken (#364)
1 parent 8f36305 commit f4e1165

File tree

1 file changed

+9
-34
lines changed

1 file changed

+9
-34
lines changed

src/wrapper/fetchAccessToken.ts

+9-34
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@ import { z } from "zod";
55
* Fetches a new access token from the Hume API using the provided API key and Secret key.
66
*
77
* @param args - The arguments for the request.
8-
* @returns Promise that resolves to the new access token or null.
9-
* @throws If the base64 encoding fails.
108
* @example
119
* ```typescript
1210
* async function getToken() {
@@ -27,11 +25,11 @@ export const fetchAccessToken = async ({
2725
apiKey: string;
2826
secretKey: string;
2927
host?: string;
30-
}): Promise<string | null> => {
28+
}): Promise<string> => {
3129
const authString = `${apiKey}:${secretKey}`;
3230
const encoded = base64Encode(authString);
3331

34-
const response = await fetch(`https://${host}/oauth2-cc/token`, {
32+
const res = await fetch(`https://${host}/oauth2-cc/token`, {
3533
method: "POST",
3634
headers: {
3735
"Content-Type": "application/x-www-form-urlencoded",
@@ -41,36 +39,13 @@ export const fetchAccessToken = async ({
4139
grant_type: "client_credentials",
4240
}).toString(),
4341
cache: "no-cache",
44-
})
45-
.then((res) => {
46-
// if reading response as json fails, return empty object
47-
// this can happen when request returns XML due to server error
48-
return res
49-
.json()
50-
.then((d: unknown) => d)
51-
.catch(() => ({}));
42+
});
43+
return z
44+
.object({
45+
access_token: z.string(),
5246
})
53-
.then((data: unknown) => {
54-
// extract access_token value from received object
55-
return z
56-
.object({
57-
access_token: z.string(),
58-
})
59-
.transform((data) => {
60-
return data.access_token;
61-
})
62-
.safeParse(data);
47+
.transform((data) => {
48+
return data.access_token;
6349
})
64-
.catch(
65-
() =>
66-
({
67-
success: false,
68-
}) as const,
69-
);
70-
71-
if (!response.success) {
72-
return null;
73-
}
74-
75-
return response.data;
50+
.parse(await res.json());
7651
};

0 commit comments

Comments
 (0)