Search code examples
typescriptasynchronousaxiosrequestes6-promise

Typescript: How do I hande axios requests properly?


I am sort of new to requests in TS/JS. I am making a function that generates a unique id call 'key'. In my function, I must make a request to an api that checks to see if the generated key exists. When making this request, I am having problems doing it asynchronously. I know requests are supposed to be async, so I am not sure how I would go about handling this. I have reviewed this stackoverflow post about making requests synchronous, but that would be a last resort for me as I would like to accomplish this the 'right' way. I am also new to Typescript, so my typings are also a bit off. More details about this are in my code as follows:

const KEYLEN: number = 10
const axios = require('axios').default;

/**
 * Function that creates, validates uniqueness, and returns a key
 * @param apiHost string host of the api
 * @param userEmail string user's email
 * @returns string new unused and random key
 */
export function getKey(apiHost: string, userEmail: string) {
    let key: string = ''
    // I set to type any because function checkKeyExistance can have return type Promise<void> - Should be Promise<number>
    // flag that is set upon existance of key
    let existsFlag: any = 0
    // let existsFlag: number | Promise<number>

    while((!existsFlag)){
        // api.key_gen just returns a random string of length KEYLEN
        key = api.key_gen(KEYLEN)
        // Attempting to handle the promise returned from checkKeyExistance
        checkKeyExistance(apiHost, key)
            .then(function(response) {
                console.log(`Response: ${response}`)
                existsFlag = response
            })
    }
    
    return key 
}

/**
 * Function that checks if key exists already
 * @param apiHost string host of the api
 * @param key string
 * @returns integer - 1 if the key does not exist and 0 if the key exists
 */
export async function checkKeyExistance(apiHost: string, key: string) {
    // This route returns an array of user emails with the specified key. 
    // I want to see if this array is of length 0 (or === []), then I know this new random key does not exist
    const getUrl:string = `${apiHost}/user/getKey/${key}`
    let flag = 0
    console.log(`Checking availability of ${key}`)

    // I am using axios to run the query - maybe there is a better tool?
    try {
        axios.get(getUrl)    
            .then(function (response: any) {
                // If there is reponse, then 
                console.log(response.data)
                if(response.data.email) {
                    console.log(`API Key ${key} already exists! Generating another one..`)
                    flag = 0
                } else {
                    console.log(`API Key ${key} does not exist. Assigning it..`)
                    flag = 1
                }
            })
            .catch(function (error: Error) {
                console.log(`ERROR requesting details for ${key}`)
                console.log(error)
                flag = 0
            })
            .then(function () {
                console.log(`Returning flag ${flag}`)
                return flag
            })
    } catch (error: any){
            console.log(error)
    }
}

// Run the function
getKey('http://localhost:5005', 'test@test.com')

When executing the code, I get a rapid running output of:

Checking availability of sRl@bj%MBJ
Checking availability of RYXNL^rL#(
Checking availability of %co)AVgB(!
Checking availability of JhtnzIQURS
Checking availability of ^vxPkAvr#f
Checking availability of J*UR^rySb@
Checking availability of e%IXX@(Tp@
Checking availability of (e@(!R^n%C

It appears that axios is never even making any requests or I am not handling errors or responses correctly. Is axios even the best tool for api requests in TS/JS? Any help or insight would be greatly appreciated.

I used these axios docs as my source: https://github.com/axios/axios#example


Solution

  • You could try to turn your function getKey into async, and then wait for the response of checkKeyExistance:

    export async function getKey
    ....
    await checkKeyExistance(apiHost, key)
    ....