Wednesday, April 12, 2017

AWS config getCredentials as a promise

Getting AWS to work with async/await took some doing.   Finally have a nice little library using 
aws-sdk and aws-api-gateway-client.


// AWS API Gateway Setup - Test Inventory Callconst AWS = require('aws-sdk');
const apigClientFactory = require('aws-api-gateway-client');

const { INVENTORYLOOKUP } = appSettings.service_endpoints;

async function getAwsConfig() {
    return new Promise(function (resolve, reject) {
        AWS.config.getCredentials(async function(err) {
            if (err) {
                console.log('Error getting credentials', err);
                return reject(err);
            } else {
                resolve({
                    accessKey: AWS.config.credentials.accessKeyId,
                    secretKey: AWS.config.credentials.secretAccessKey,
                    sessionToken: AWS.config.credentials.sessionToken,
                    region: 'us-west-2'                });
            }
        });
    });
}

async function invokeAWS(targetURL, body) {

        let config = await getAwsConfig();
        config.invokeUrl = targetURL;

        console.log('config=', config);

        const apigClient = apigClientFactory.newClient(config);

        // config, url, method, header, body        let prom = apigClient.invokeApi({}, '/', 'POST', {
            'Content-Type': 'application/json',
            'Accept': 'application/json'        }, body);

        return prom;
    }
}

2 comments: