Skip to content

Instantly share code, notes, and snippets.

@edwardoboh
Last active June 25, 2023 06:56
Show Gist options
  • Save edwardoboh/1776d4f006e6ffb510f237fe362721c0 to your computer and use it in GitHub Desktop.
Save edwardoboh/1776d4f006e6ffb510f237fe362721c0 to your computer and use it in GitHub Desktop.
Test Faker API for browser and Nodejs

Faker API test

/**
 * 1. Using Fetch API with Browser
 */
function makeApiCalls(){
    return (async () => {
        try{
            const fakerResponse = await Promise.all([
                fetch('https://fakerapi.it/api/v1/books'),
                fetch('https://fakerapi.it/api/v1/persons'),
                fetch('https://fakerapi.it/api/v1/companies')
            ])

            const jsonVals = await Promise.all([
                fakerResponse[0].json(),
                fakerResponse[1].json(),
                fakerResponse[2].json()
            ])
            
            const result = {
                books: jsonVals[0].data,
                persons: jsonVals[1].data,
                companies: jsonVals[2].data,
            }

            return result;
        }catch(error){
            console.error(error)
            return null
        }
    })()
}

makeApiCalls()

/**
 * 2. Using Axios with Nodejs
 */
const axios = require('axios')

function makeApiCalls(){
    return (async () => {
        try{
            const fakerResponse = await Promise.all([
                axios.get('https://fakerapi.it/api/v1/books'),
                axios.get('https://fakerapi.it/api/v1/persons'),
                axios.get('https://fakerapi.it/api/v1/companies')
            ])
            
            const result = {
                books: fakerResponse[0].data.data,
                persons: fakerResponse[1].data.data,
                companies: fakerResponse[2].data.data,
            }

            return result;
        }catch(error){
            console.error(error)
            return null
        }
    })()
}

makeApiCalls()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment