How to use async and await to unify Access Token-fetching functions for combinatorial design

Keywords: Front-end JSON

Recently, I've been integrating SAP systems with machine learning APIs using the SAP Cloud Platform Leonardo because the machine term APIs on SAP Cloud Platform require an Access Token to be passed on each consumption, so I need to send a request to get the response of the Access Token. This request, in addition to returning the actualIn addition to token of, there is an expire time, expires_in field:

As defined by the OAuth 2.0 standard, the expires_in field represents the token issued by the server in seconds remaining from the expiration time.

My code is as follows:

const request = require('request-promise-native');

var config = require('../config.js');
 
var TOKEN = undefined;
var EXPIRES_IN = undefined;
var TOKEN_FETCHED_SINCE = undefined;


function isCurrentDateExpired(){
    var current = new Date();

    var diffInMilliSeconds = current - TOKEN_FETCHED_SINCE;
    var diffInSecond = Math.ceil(diffInMilliSeconds/1000);
    var expired = diffInSecond >= EXPIRES_IN ? true:false;
    // for debug;
    // expired = true; 
    return expired;
}

async function getAccessToken(){
    if( TOKEN === undefined || isCurrentDateExpired()){
        var raw = new Buffer(config.username + ":" + config.password);
        const accessToken = await request({
            method: 'GET',
            headers: {
                'Authorization': 'Basic ' + raw.toString('base64')
            },
            url: config.ACCESS_TOKEN,
            json: false
        });
        var oToken = JSON.parse(accessToken);
        EXPIRES_IN = oToken.expires_in;
        TOKEN = oToken.access_token;
        TOKEN_FETCHED_SINCE = new Date();
        return oToken.access_token;
    }
    else{
        return TOKEN;
    }
}

var request1 = getAccessToken();
var freshNewToken, secondTimeToken;

request1.then(function(o){
    // console.log("token1: " + o);
     freshNewToken = o;
});

function test2(){
    var b = getAccessToken();
    b.then(function(o){
    // console.log("token2: " + o);
        secondTimeToken = o;
        console.log("they should be equal: " + (freshNewToken == secondTimeToken));
    });
}

setTimeout( test2, 6000);

For more original articles by Jerry, please pay attention to the public slogan "Wong Zixi":

Posted by WeAnswer.IT on Sun, 29 Sep 2019 21:11:17 -0700