1

I have a node.js app that has a few files that I am working with, but the main two javascript files are a RestController and AuthController. The RestController is supposed to call the AuthController to pull a new access token from Salesforce, the server that I am attempting to hit.

I currently set up my AuthController.js to work with promises so that I can wait to get my access token. The problem is I have no idea how to get my RestController.js file to wait for the access token from the AuthController.js file.

I am also very very new to Javascript and Promises, so I am not sure if I even set up my functions correctly. Basically, I want my AuthController to handle getting the access token and the RestController to handle the Rest request to our server.

AuthController.js

var fs = require('fs');
var jwt = require('jsonwebtoken');
var request = require('request');
var querystring = require('querystring');
var config = require('../../configs/config.json');
var filename = __dirname + '/../../' + config.key_path;

var access_token;

var readFilePromise = function(file) {
    return new Promise(function(ok, notOk) {
        fs.readFile(file, function(err,data) {
            if (err) {
                notOk(err);
            } else {
                ok(data);
            }
        });
    });
}

var getAccessToken = function(key) {
    return new Promise(function(ok,notOk) {

        var jwtparams = {
            iss : config.client_id,
            sub: config.username,
            aud: 'https://' + config.host,
            exp : Date.now() + 300
        };

        var token = jwt.sign(jwtparams, key, {algorithm: 'RS256'});

        var data = querystring.stringify({
            grant_type : 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            assertion : token
        });

        request.post({
            headers: {
                'Content-Type' : 'application/x-www-form-urlencoded',
                'Content-Length' : data.length
            },
            url: 'https://' + config.host + '/services/oauth2/token',
            body: data
        }, function(error, response, body) {
            if (error) {
                return notOk(error);
            } 
            try {
                ok(JSON.parse(body).access_token);
            } catch (e) {
                notOk(e);
            }
        });
    });
}

function main() {
    readFilePromise(filename).then(function(data) {
        getAccessToken(data.toString()).then(function(data) {
            access_token = data.toString();
        });
    });
}

module.exports = {main};

RestController.js

var https = require('https');
var request = require('request');
var auth = require('./authController.js');

class SystemController {
    doProcessPostStatus (req,res) {
        if (!req.body.systemId) {
            return res.status(400).send([
                {
                    'errorCode' : 'INVALID_REQUEST_BODY',
                    'message' : 'System Id  "systemId" variable is required.'
                }
            ]);
        } else if (typeof req.body.success === 'undefined') {
            return res.status(400).send([
                {
                    'errorCode' : 'INVALID_REQUEST_BODY',
                    'message' : 'Success "success" variable is required'
                }
            ]);
        } else if (!req.body.message) {
            return res.status(400).send([
                {
                    'errorCode' : 'INVALID_REQUEST_BODY',
                    'message' : 'Message "message" variable is required'
                }
            ]);
        }

        var access_token = auth.main();
        console.log(access_token);
    }
}

var systemControllerVar = new SystemController();
module.exports = systemControllerVar;

Any help is greatly appreciated as I am currently stuck, thanks!

user7100889
  • 201
  • 2
  • 3
  • 2
    What is the error or problem you are having? – Mike Cheel Aug 26 '19 at 21:16
  • one thing Promises were made for is to avoid callback pyramid of doom ... flatten the code in `main` :p – Jaromanda X Aug 26 '19 at 21:32
  • Like @JaromandaX said you should [flatten your nested promises into a chain](https://stackoverflow.com/a/22000931/1048572). And you need to avoid that global `access_token` variable. Instead, return a promise from `main()` which fulfills with that value, then use `auth.main().then(console.log)` in your `SystemController`. – Bergi Aug 27 '19 at 00:49
  • 4 space indentation. Ugh. Is that your problem? ;) – vol7ron Aug 27 '19 at 01:40
  • The problem that I am hitting is I need to be able to access the "access_token" attribute or return it to my RestController.js function that is calling it but I keep getting undefined. – user7100889 Aug 27 '19 at 14:42
  • I am not sure exactly how I could flatten my `main()` function as the data returned from it is needed for the child function/promise. Sorry if I am just not understanding, completely new to Javascript and Promises are very foreign to me. – user7100889 Aug 27 '19 at 14:55

0 Answers0