@@ -5,8 +5,6 @@ import { z } from "zod";
5
5
* Fetches a new access token from the Hume API using the provided API key and Secret key.
6
6
*
7
7
* @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.
10
8
* @example
11
9
* ```typescript
12
10
* async function getToken() {
@@ -27,11 +25,11 @@ export const fetchAccessToken = async ({
27
25
apiKey : string ;
28
26
secretKey : string ;
29
27
host ?: string ;
30
- } ) : Promise < string | null > => {
28
+ } ) : Promise < string > => {
31
29
const authString = `${ apiKey } :${ secretKey } ` ;
32
30
const encoded = base64Encode ( authString ) ;
33
31
34
- const response = await fetch ( `https://${ host } /oauth2-cc/token` , {
32
+ const res = await fetch ( `https://${ host } /oauth2-cc/token` , {
35
33
method : "POST" ,
36
34
headers : {
37
35
"Content-Type" : "application/x-www-form-urlencoded" ,
@@ -41,36 +39,13 @@ export const fetchAccessToken = async ({
41
39
grant_type : "client_credentials" ,
42
40
} ) . toString ( ) ,
43
41
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 ( ) ,
52
46
} )
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 ;
63
49
} )
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 ( ) ) ;
76
51
} ;
0 commit comments