'Best way to call external API's one for getting token and other for fetching details with token using node js lambda

const got = require('got');   
 var config = {
      url: '/authorization/tokenrequest',
      body: data,
      // method: 'post',
      headers: {
        'Content-Type': 'application/json', 
      }
    }

module.exports.hello = async() => {
  const response = await got.post(config).then(ok => {
    console.log(ok.body);
    var parsedJson = JSON.parse(ok.body);
    if(parsedJson.Value.Success){
      var token = 'Bearer ' + parsedJson.Value.AuthenticationToken;
      
      var data = JSON.stringify({"userid","test"});
      var configs = {
        method: 'post',
        url: '/user/userprofile',
        headers: {
          'Authorization': 'Bearer oYi1hP9p20LUi8DIERHhITGXEsVNkEweEshN6VMNsssCTBy8iYBxbcH3GJDyNJ9KILejscff5kQrM3V9uTecgaS1cu90xXmcb4L0NiVY4gHvotbazG8ARDZ5vE29bkQhaxaZunqZyb6mwLtGVz3IpYJxAg7hR9zi6x3tWE3Ir56wiFoXnZfgUgYJKdn8FMeC+Yyj6a7B19/MDqTs85rqN1V4RflNEy+tZr2c+lCicMarQdjMLOs2GISEFuouXDRdl4J8cYWRHIE/aVNwkhB5g4sHMlYdO+Lcva6bmowl8WrPUoCOzgxEzV9PzGHmjKY1sgn5HLv85MYySx1Y6XliKZ/lBW9N4L75iwm87rFbjhVJxzSEqRQEt9c6e71fc5fxkv01ITnmdnD57eFkZzLqV2A1NbUBId8qb2dh1rfjq7PD8ohFtMFSOcB4tuHbUx8k8NQn+ws/MW/hItOSnqF2/pj8UR/Sf8txm3ncAHr2GLaoYbfRg++GrVusk/wFhjzmm8jzbJR0acJN01XLxBX7zhO8xzQCKgjXruonnSGF821Vl1F328GvwMLDpwKOTbi/zlPZA2G7d++mkGaiW6hH2/n3TKSXurVcnpAeVEvEaCAvLoMZvucNIAkSuD9mhEOq', 
          'Content-Type': 'application/json',
        },
        data : data
      };

      console.log(configs);
      const userResponse = got.post(configs).then(ok => {
      console.log(ok.userResponse);
      var userResponseJson = JSON.parse(ok.userResponse);
      console.log(userResponseJson);
      })
      .catch(function (error) {
        console.log(error);
      });
    }
  }).catch(reject);
}

Getting below error HTTPError: Response code 500 (Internal Server Error) at Request.request.once (\node_modules\got\dist\source\as-promise\index.js:117:42) at process._tickCallback (internal/process/next_tick.js:68:7)

Best way to fetch token and then use it in another end point in node js.



Solution 1:[1]

You may write something like this. You can get a instance from ApiInstance class. You can reach getUserProfile function which is async and promise structured. You don't always need to run token function with this structure. You can also add token expire date check for it. This structure also enable encapsualtion. I hope, you mean something like this and it helps.

const apiInstance = new ApiInstance();

module.exports.hello = async () => {
  const data = '';
  let userProfile;

  try {
    userProfile = await apiInstance.getUserProfile(data);
  } catch (error) {
    console.error(error);
  }

  if (userProfile) {
    console.info('User Profile:', userProfile);
  } else {
    console.info('User profile not found!');
  }
}

function ApiInstance() {
  const got = require('got');
  let token = null;

  const getToken = async () => {

    if (token) {
      return token;
    } else {
      const data = '';
      const config = {
        url: '/authorization/tokenrequest',
        body: data,
        headers: {
          'Content-Type': 'application/json',
        }
      }

      return got.post(config)
        .then(response => {
          return JSON.parse(response.body).Value.AuthenticationToken;
        })
        .catch(error => {
          console.error(error);
          return null;
        })
    }
  }

  this.getUserProfile = async (data) => {
    token = await getToken();
    const config = {
      method: 'post',
      url: '/user/userprofile',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      data: data
    };

    return got.post(config)
      .then(response => response.userResponse)
      .catch(error => {
        console.error(error);
        return null;
      })
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1