Amit
Amit

Reputation: 7035

restructure string in javascript

I have this string in which i need to re-structure using JavaScript.

Label=11121212&TopicArn=test&AWSAccountId.member.1=YYYYYYY&ActionName.member.1=createTopic&Action=AddPermission&Version=2010-03-31&AWSAccessKeyId=XXXXXXXXX&SignatureVersion=2&SignatureMethod=HmacSHA1&Timestamp=2012-05-02T16%3A06%3A09.000Z&Signature=C3uIh%2Bz%2Fik

For this example, AWSAccessKeyId should be the first part of the string and label should be 2nd last. There are others as well, similar to this.

Expected output --AWSAccessKeyId=XXXXXXXXX&AWSAccountId.member.1=YYYYYYYYY&Action=AddPermission&ActionName.member.1=Publish&Label=ios-sns-permission-label&Signature=dEaNL0ibP5c7xyl4qXDPFPADW0meoUX9caKyUIx1wkk%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-05-02T00%3A51%3A23.965Z&TopicArn=arn%3Aaws%3Asns%3Aus-east-1%3A335750469596%3AiOSGoesWooooo-1335919882&Version=2010-03-31

Code that creates this incorrect string

exports.generatePayload = function(params, accessKeyId, secretKey, endpoint) {
    var host = endpoint.replace(/.*:\/\//, "");
    var payload = null;

    var signer = new AWSV2Signer(accessKeyId, secretKey);
    params = signer.sign(params, new Date(), {
        "verb" : "POST",
        "host" : host,
        "uriPath" : "/"
    });

    var encodedParams = [];
    for(var key in params) {
        if(params[key] !== null) {
            encodedParams.push(encodeURIComponent(key) + "=" + encodeURIComponent(params[key]));
        } else {
            encodedParams.push(encodeURIComponent(key));
        }
    }
    payload = encodedParams.join("&");
    return payload;
}

I tried putting this in an array and restructure it but it didn't work for me.

Please advice how this can be done easily using JavaScript

Upvotes: 0

Views: 197

Answers (1)

dweiss
dweiss

Reputation: 832

exports.generatePayload = function(params, accessKeyId, secretKey, endpoint) {
    var host = endpoint.replace(/.*:\/\//, "");
    var payload = null;

    var signer = new AWSV2Signer(accessKeyId, secretKey);
    params = signer.sign(params, new Date(), {
        "verb" : "POST",
        "host" : host,
        "uriPath" : "/"
    });

    var encodedParams = [];
    if(params["AWSAccessKeyId"] != null)
    {
        encodedParams.push(encodeURIComponent("AWSAccessKeyId") + "=" + encodeURIComponent(params["AWSAccessKeyId"]));

    }
    if(params["AWSAccountId.member.1"] != null)
    {
        encodedParams.push(encodeURIComponent("AWSAccountId.member.1") + "=" + encodeURIComponent(params["AWSAccountId.member.1"]));

    }
    //other_ifs_for_param_keys_here
    payload = encodedParams.join("&");
    return payload;

Upvotes: 1

Related Questions