Coder Social home page Coder Social logo

kndt84 / aws-api-gateway-client Goto Github PK

View Code? Open in Web Editor NEW
130.0 7.0 55.0 1.44 MB

A client module of AWS API gateway both for Node.js and browsers

Home Page: https://www.npmjs.com/package/aws-api-gateway-client

License: MIT License

JavaScript 100.00%
aws api-gateway nodejs

aws-api-gateway-client's Introduction

dependencies Status Build Status npm

Overview

A module for AWS API gateway client based on auto-generated JavaScript SDK. This module can be used not only for Node.js but for front-end. In addition, it generalizes original SDK's endpoint specific methods.

Reference: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-generate-sdk.html

Prerequisites

For the JavaScript SDK to work your APIs need to support CORS. The Amazon API Gateway developer guide explains how to setup CORS for an endpoint.

Install

npm install aws-api-gateway-client

Use the SDK in your project

Require module

var apigClientFactory = require('aws-api-gateway-client').default;

Set invokeUrl to config and create a client. For authorization, additional information is required as explained below.

config = {invokeUrl:'https://xxxxx.execute-api.us-east-1.amazonaws.com'}
var apigClient = apigClientFactory.newClient(config);

Calls to an API take the form outlined below. Each API call returns a promise, that invokes either a success and failure callback

var pathParams = {
    //This is where path request params go.
    userId: '1234',
};
// Template syntax follows url-template https://www.npmjs.com/package/url-template
var pathTemplate = '/users/{userID}/profile'
var method = 'GET';
var additionalParams = {
    //If there are query parameters or headers that need to be sent with the request you can add them here
    headers: {
        param0: '',
        param1: ''
    },
    queryParams: {
        param0: '',
        param1: ''
    }
};
var body = {
    //This is where you define the body of the request
};

apigClient.invokeApi(pathParams, pathTemplate, method, additionalParams, body)
    .then(function(result){
        //This is where you would put a success callback
    }).catch( function(result){
        //This is where you would put an error callback
    });

Using AWS IAM for authorization

To initialize the SDK with AWS Credentials use the code below. Note, if you use credentials all requests to the API will be signed. This means you will have to set the appropriate CORS accept-* headers for each request.

var apigClient = apigClientFactory.newClient({
    invokeUrl:'https://xxxxx.execute-api.us-east-1.amazonaws.com', // REQUIRED

    region: 'eu-west-1',                                           // REQUIRED: The region where the API is deployed.

    accessKey: 'ACCESS_KEY',                                       // REQUIRED

    secretKey: 'SECRET_KEY',                                       // REQUIRED

    sessionToken: 'SESSION_TOKEN',                                 // OPTIONAL: If you are using temporary credentials
                                                                                you must include the session token.

    systemClockOffset: 0,                                          // OPTIONAL: An offset value in milliseconds to apply to signing time

    retries: 4,                                                    // OPTIONAL: Number of times to retry before failing. Uses axios-retry plugin.

    retryCondition: (err) => {                                     // OPTIONAL: Callback to further control if request should be retried.
      return err.response && err.response.status === 500;          //           Uses axios-retry plugin.
    },

    retryDelay: 100 || 'exponential' || (retryCount, error) => {   // OPTIONAL: Define delay (in ms) as a number, a callback, or
      return retryCount * 100                                      //           'exponential' to use the in-built exponential backoff
    },                                                             //           function. Uses axios-retry plugin. Default is no delay.

    shouldResetTimeout: false                                      // OPTIONAL: Defines if the timeout should be reset between retries. Unless
                                                                   //           `shouldResetTimeout` is set to `true`, the request timeout is
                                                                   //           interpreted as a global value, so it is not used for each retry,
                                                                   //           but for the whole request lifecycle.
});

Using API Keys

To use an API Key with the client SDK you can pass the key as a parameter to the Factory object. Note, if you use an apiKey it will be attached as the header 'x-api-key' to all requests to the API will be signed. This means you will have to set the appropriate CORS accept-* headers for each request.

var apigClient = apigClientFactory.newClient({
    invokeUrl:'https://xxxxx.execute-api.us-east-1.amazonaws.com', // REQUIRED
    apiKey: 'API_KEY', // REQUIRED
    region: 'eu-west-1' // REQUIRED
});

aws-api-gateway-client's People

Contributors

alexneamtu avatar aneihouse avatar dagnello avatar davispuh avatar dependabot[bot] avatar dturnergs avatar emonhaider avatar eumpek avatar jonnyshaw89 avatar jozr avatar kndt84 avatar manishrana87 avatar marcelpanse avatar mattbryce93 avatar medington avatar mgarod avatar ngoyal16 avatar twoslick avatar willvincent avatar zeroasterisk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

aws-api-gateway-client's Issues

Support for custom headers

I'm using a combination of Auth0 with an API-gateway custom authenticator. In this situation you need to send an authorization header with a Bearer idToken.

Currently, I don't see a way to send this header. I think it could be solved relatively easy by allowing a new field 'customHeaders' in the config and passing that to axios in the simpleHttpClient.js.

I can make a fork and make a PR.

Idea's?

TypeError: newClient is not a function

I am using your library with angular2 and node. I have following error in runtime:

TypeError: WEBPACK_IMPORTED_MODULE_2_aws_api_gateway_client.newClient is not a function

I am calling your code like this:

...
import * as AWSApiGatewayClient from 'aws-api-gateway-client'
...
let config = {
          invokeUrl: 'XXX',
          accessKey: iamCredentials.accessKey,
          secretKey: iamCredentials.secretKey,
          sessionToken: iamCredentials.sessionToken,
          region: iamCredentials.region
        }

        let apigClient: any = AWSApiGatewayClient.newClient(config);

Thanks!

Sigv4 Client does not sign requests correctly when there are special characters

We've been using this client for some time now and have just run into an issue with special characters. Our API Gateway requests are of the form:

https://api-url/stage/method/*/*
https://api-url/stage/method?query-params

We've recently needed to add IAM for authorizing these requests and when doing so, we recieve the following message as a response from API Gateway:

"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."

When we exchange the '*'s with other alpha-numeric characters, everything works correctly. When we move the query params into the additional parameters section and remove the '?' everything works fine as well.

Is there some way to fix the signing so that it can handle these special characters? Is there something I'm missing in getting this to work?

Some errors from webpack

Hi, I'm having some errors while importing the module, just like this:

import Apig from 'aws-api-gateway-client'

And later in webpack console throws this warnings:

WARNING in ./~/jsdom/lib/jsdom/living/xmlhttprequest.js
Critical dependencies:
24:23-30 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/jsdom/lib/jsdom/living/xmlhttprequest.js 24:23-30

WARNING in ./~/jsdom/lib/jsdom/living/window/History.idl
Module parse failed: /home/my-project/node_modules/jsdom/lib/jsdom/living/window/History.idl The keyword 'enum' is reserved (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: The keyword 'enum' is reserved (1:0)
at Parser.pp.raise.....

WARNING in ./~/jsdom/~/acorn/dist/acorn.js
Critical dependencies:
1:478-485 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
 @ ./~/jsdom/~/acorn/dist/acorn.js 1:478-485

WARNING in ./~/acorn-globals/~/acorn/dist/walk.js
Critical dependencies:
1:503-510 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
 @ ./~/acorn-globals/~/acorn/dist/walk.js 1:503-510

WARNING in ./~/acorn-globals/~/acorn/dist/acorn.js
Critical dependencies:
1:478-485 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
 @ ./~/acorn-globals/~/acorn/dist/acorn.js 1:478-485

And this errors:

ERROR in ./~/jsdom/lib/jsdom.js
Module not found: Error: Cannot resolve module 'fs' in /home/my-cms/node_modules/jsdom/lib
 @ ./~/jsdom/lib/jsdom.js 6:11-24

ERROR in ./~/jsdom/lib/jsdom/browser/resource-loader.js
Module not found: Error: Cannot resolve module 'fs' in /home/my-cms/node_modules/jsdom/lib/jsdom/browser
 @ ./~/jsdom/lib/jsdom/browser/resource-loader.js 6:11-24

ERROR in ./~/tough-cookie/lib/cookie.js
Module not found: Error: Cannot resolve module 'net' in /home/my-cms/node_modules/tough-cookie/lib
 @ ./~/tough-cookie/lib/cookie.js 32:10-24

ERROR in ./~/jsdom/lib/jsdom/living/xmlhttprequest.js
Module not found: Error: Cannot resolve module 'child_process' in /home/my-cms/node_modules/jsdom/lib/jsdom/living
 @ ./~/jsdom/lib/jsdom/living/xmlhttprequest.js 4:18-42

ERROR in ./~/jsdom/lib/jsdom/living/xhr-utils.js
Module not found: Error: Cannot resolve module 'fs' in /home/my-cms/node_modules/jsdom/lib/jsdom/living
 @ ./~/jsdom/lib/jsdom/living/xhr-utils.js 5:11-24

ERROR in ./~/cssstyle/lib/CSSStyleDeclaration.js
Module not found: Error: Cannot resolve module 'fs' in /home/my-cms/node_modules/cssstyle/lib
 @ ./~/cssstyle/lib/CSSStyleDeclaration.js 7:9-22

ERROR in ./~/jsdom/lib/jsdom/living/generated/FileReader.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../file-api/FileReader-impl.js in /home/my-cms/node_modules/jsdom/lib/jsdom/living/generated
 @ ./~/jsdom/lib/jsdom/living/generated/FileReader.js 261:13-54

ERROR in ./~/jsdom/lib/jsdom/living/generated/MutationEvent.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../events/MutationEvent-impl.js in /home/my-cms/node_modules/jsdom/lib/jsdom/living/generated
 @ ./~/jsdom/lib/jsdom/living/generated/MutationEvent.js 174:13-55

ERROR in ./~/forever-agent/index.js
Module not found: Error: Cannot resolve module 'net' in /home/my-cms/node_modules/forever-agent
 @ ./~/forever-agent/index.js 6:10-24

ERROR in ./~/forever-agent/index.js
Module not found: Error: Cannot resolve module 'tls' in /home/my-cms/node_modules/forever-agent
 @ ./~/forever-agent/index.js 7:10-24

ERROR in ./~/request/lib/har.js
Module not found: Error: Cannot resolve module 'fs' in /home/my-cms/node_modules/request/lib
 @ ./~/request/lib/har.js 3:9-22

ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'net' in /home/my-cms/node_modules/tunnel-agent
 @ ./~/tunnel-agent/index.js 3:10-24

ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'tls' in /home/my-cms/node_modules/tunnel-agent
 @ ./~/tunnel-agent/index.js 4:10-24

What's the issue?

Thanks by the way...

Request Signing Error

Since upgrading to version 0.2.17 we are getting signing errors on our requests. I believe it may be related to this change:
https://github.com/kndt84/aws-api-gateway-client/pull/70/files#diff-7de6072e915823a140a4447fa80cd3d5R215

headers[HOST] = parser.hostname; was changed to headers[HOST] = parser.host;
This is only in the case that host was not supplied.

Difference in documentation for url.parse indicates the only difference being the port returned. This could presumably cause the signing issue.

Example error:

error: Error response was:
{
    "message": "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been\n'POST\n/v3/v1/send-message\n\naccept:application/json\ncontent-type:image/jpeg\nhost:api.url.com\nx-amz-date:20190722T075057Z\n\naccept;content-type;host;x-amz-date\na3e98aa8b2745ffccdf3ff64cc5b13bebe5eff5da9cb2bfac2d28a49d242515f'\n\nThe String-to-Sign should have been\n'AWS4-HMAC-SHA256\n20190722T075057Z\n20190722/eu-west-1/execute-api/aws4_request\nd076d394b89d64ca99dd9b600792ce06815927bd97bcbc0018a362f901f14986'\n"
}

when I updated `aws-api-gateway-client` from 0.2.17 to version 0.3.3 my Requests failed with status code 403 however it was working well before updating

export function apiRequest(options, cred, result, error) {
  var apigClientFactory = require("aws-api-gateway-client").default;
  var apigClient = apigClientFactory.newClient({
    invokeUrl: BASE_URL, // REQUIRED
    region: "us-east-1", // REQUIRED: The region where the API is deployed.
    accessKey: cred.accessKeyId, // REQUIRED
    secretKey: cred.secretAccessKey, // REQUIRED
    sessionToken: cred.sessionToken, // OPTIONAL: If you are using temporary credentials
    systemClockOffset: 0, // OPTIONAL: An offset value in milliseconds to apply to signing time
    retries: 2, //           function. Uses axios-retry plugin. Default is no delay.
    retryDelay: "exponential"
  });
  var pathParams = {};
  // Template syntax follows url-template https://www.npmjs.com/package/url-template
  var method = "POST";
  var additionalParams = {
    //If there are query parameters or headers that need to be sent with the request you can add them here
    headers: {
      "Content-Type": "application/json"
    },
    queryParams: {}
  };
  console.log("api client", apigClient);
  apigClient
    .invokeApi(
      pathParams,
      `/default/${options.pathTemplate}`,
      method,
      additionalParams,
      options.body
    )
    .then(response => {
      //This is where you would put a success callback
      console.log(`${options.pathTemplate} invoke api result`, response);
      result(response);
    })
    .catch(err => {
      //This is where you would put an error callback
      console.log(`${options.pathTemplate} invoke api error`, err);
      error(err);
    });
}

Utils.js Buffer is not defined

the copy function from the utils.js file is using Buffer however i was getting an error within my react-native project that it wasn't defined / referenced within utils.js.

my workaround was to install the npm module buffer (instead of relying on the node.js core module buffer) and explicitly require it within utils.js:

var Buffer = require('buffer/').Buffer

Running on react-native causes TransformError

TransformError: [omitted]/node_modules/aws-api-gateway-client/dist/apigClient.js: Unknown plugin "transform-es5-property-mutators" specified in "[omitted]/node_modules/aws-api-gateway-client/package.json" at 0, attempted to resolve relative to "[omitted]/node_modules/aws-api-gateway-client"

RCTFatal
-[RCTBatchedBridge stopLoadingWithError:]
__25-[RCTBatchedBridge start]_block_invoke_2
_dispatch_call_block_and_release
_dispatch_client_callout
_dispatch_main_queue_callback_4CF
__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__
__CFRunLoopRun
CFRunLoopRunSpecific
GSEventRunModal
UIApplicationMain
main
start
0x0

Any ideas on how to get it working?

Query Parameters not being passed to API

Hi,

I have the below code to call an AWS API Endpoint that generates a random number between given min and max numbers. min and max are being passed to API as query parameters.

let AWS = require('aws-sdk');
AWS.config.loadFromPath('./config.json');
//AWS.config.region = 'ap-south-1';
let lambda = new AWS.Lambda();
let apigClientFactory = require('aws-api-gateway-client').default;
let config = {
    invokeUrl: 'https://abcdefgh.execute-api.ap-south-1.amazonaws.com/DEV',
    accessKey: '<access-key>',
    secretKey: '<secret-key>',
    region: 'ap-south-1'
};
let apigClient = apigClientFactory.newClient(config);
let apiParams = {min: 20,max: 40};
let body = {
    
}

let additionalParams = {
   
}
apigClient.invokeApi(apiParams, '/number', 'GET', additionalParams, body)
    .then(function (result) {
        console.log(result);
    })
    .catch(function (error) {
        console.log(error);
    });

Body mapping Template in API gateway for get method:

{
    "min" : $input.params('min'),
    "max" : $input.params('max')
}

But when I check Cloudwatch logs I see my query string parameters getting empty strings :

{ min: '', max: '' }

So my lambda is returning null as the value.

Please let me know how to pass query strings to aws api.

Thanks in advance.

Issue with '@babel/runtime/helpers/interopRequireDefault'

When execute:
var apigClientFactory = require('aws-api-gateway-client').default;
i get the error message:
'Error: Cannot find module '@babel/runtime/helpers/interopRequireDefault''
It looks like a version compatibility issue. Should I downgrade any module?

Fails to copy body when body is a Buffer

I've encountered this issue when trying to send an image as the body of the request.
The error I'm getting is:

buffer.js:208
throw new TypeError('must start with number, buffer, array or string');
^

TypeError: must start with number, buffer, array or string
at fromObject (buffer.js:208:11)
at new Buffer (buffer.js:65:10)
at Object.copy (.../node_modules/aws-api-gateway-client/dist/lib/apiGatewayCore/utils.js:71:20)
at Object.simpleHttpClient.makeRequest (.../node_modules/aws-api-gateway-client/dist/lib/apiGatewayCore/simpleHttpClient.js:79:32)
at Object.apiGatewayClient.makeRequest (.../node_modules/aws-api-gateway-client/dist/lib/apiGatewayCore/apiGatewayClient.js:67:24)
at Object.apigClient.invokeApi (.../node_modules/aws-api-gateway-client/dist/apigClient.js:109:29)
at .../tester.js:23:16
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)

Example:

var apigClientFactory = require('aws-api-gateway-client').default;
var fs = require('fs');

var config = {
invokeUrl:'## API Gateway ##',
defaultContentType: 'image/jpeg',
defaultAcceptType: 'application/json',
region: '## AWS Region ##',
};
var apigClient = apigClientFactory.newClient(config);

fs.readFile('## Path to Image ##', function(err, data) {

if (err) console.log(err);
else {

apigClient.invokeApi(
    {},
    {},
    'POST',
    { headers: { 'Content-Type': "image/jpeg"} },
    data
)
.then(function(result){
    console.log(result);
}).catch( function(result){
    console.log(result);
});

}

});

Solution?:

Changing the code on utils.js copy method from:

copy: function(obj) {
if (null === obj || 'object' !== typeof obj) return obj;
let copy = obj.constructor();
let attr = null;
for (attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}

to:

copy: function copy(obj) {
if (null == obj || 'object' != (typeof obj === 'undefined' ? 'undefined' : _typeof(obj))) return obj;
if (Buffer.isBuffer(obj)) return Buffer.from(obj);
var copy = obj.constructor();
var attr = null;
for (attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}

does work, now, I'm not Nodejs expert so I'm not sure is the best way of solving this.

Many thanks.

Alternative to MobileHub?

Hello,

Sorry in advanced - I appreciate this isn't a direct issue but I'm new to AWS and I'm building both a mobile app and admin dashboard (React Native and React JS Respectively).

Being new to AWS, I've noticed MobileHub but it seems that there's a great deal going on behind the scenes, and whilst attempting the MobileHub approach, I ended up implementing the various services independently all be it API Gateway, Lambda, and DynamoDB.

So my question is does Amplify provide a means to interact with independently implemented Lambda functions i.e. not via MobileHub but via AWS Services? Or does Amplify only work with everything implemented via MobileHub?

The reason I ask is that there seems to be a number of guides out there for getting a mobile app started but they all seem to use MobileHub services rather than independently implemented services.

I've tried various implementations of interfacing the react native app with AWS and in the future I would like to do the same for the react js dashboard. The working approach is the use of this library aws-api-gateway-client which works very well.

var apigClientFactory = require('aws-api-gateway-client').default;

Having my Access key, secret key, endpoint, and api key each defined as const.

And then the following

apigClientFactoryConfig = { 
    invokeUrl : ENDPOINT,
    accessKey : ACCESS_KEY,
    secretKey : SECRET_KEY,
    region: 'eu-west-2',
    apiKey : API_KEY,
  }
var apigClient = apigClientFactory.newClient(apigClientFactoryConfig);

And then the following function

export async function getMenus() {
    // let apiName = 'Menus';
    // let path = '/';
    // let myInit = { // OPTIONAL
    //     headers: {} // OPTIONAL
    // }
    // return await API.get(apiName, path, myInit);

    console.log('getMenus');

    let response = null;

    var params = {
        //This is where any header, path, or querystring request params go. The key is the parameter named as defined in the API
        TableName: 'Menus',
    };
    // Template syntax follows url-template https://www.npmjs.com/package/url-template
    var pathTemplate = '/Development/menus/'
    var method = 'GET';
    var additionalParams = {
        //If there are any unmodeled query parameters or headers that need to be sent with the request you can add them here
        headers: {
            param0: '',
            param1: ''
        },
        queryParams: {
          TableName: 'Menus'
        }
    };
    var body = {
        //This is where you define the body of the request
    };
  
    return await apigClient.invokeApi(params, pathTemplate, method, additionalParams, body)
    .then(function(result){
    // console.log('result', result.data);
        return result;
        //This is where you would put a success callback
    }).catch( function(result){
    // console.log('result', result);
        //This is where you would put an error callback
        return result;
    });
    return false;
}

_The commented out code represents use of aws-amplify api and storage _

_The query provides a means to GET data from a giving path where development is my deployed API Gateway and menus is the desired resource.

Please note the method implemented isn't finalized here, its just an initial example to illustrate

And with this in mind, how do I initialize aws-api-gateway-client but for the entire application?

apigClientFactoryConfig = { 
    invokeUrl : ENDPOINT,
    accessKey : ACCESS_KEY,
    secretKey : SECRET_KEY,
    region: 'eu-west-2',
    apiKey : API_KEY,
  }
var apigClient = apigClientFactory.newClient(apigClientFactoryConfig);

Currently the initialising lies inside my API functions class where I make my various API calls but I expect its better to perform this initalization in the main component App.js? Please do correct me if I'm wrong.

I guess further questions would be

  • Do I need to or can I make Amplify and aws-api-gateway-client work together particularly from a credentials and authentication point of view?
  • Why would you implement using the MobileHub approach when you can implement the services individually? Other than perhaps being quicker and project based?

Other libraries reviewed were the aws-sdk such as

aws-sdk/dist/aws-sdk-react-native
and
var APIGateway = require('aws-sdk/clients/apigateway');

where again something such as

    var myConfig = new AWS.Config({
      credentials: credentials, region: 'eu-west-2'
    });

    console.log('myconfig', myConfig);

    var apigateway = new AWS.APIGateway();

will follow.

Thank you for your help and support - I'm trying to get the best start to AWS but I'm a bit confused between the various libraries and approaches to interfacing a mobile app and dashboard with the AWS Services such as Lambda, DynamoDB, and API Gateway.

npm modul not found

Hey guys,

if I want to use aws-api-gateway-client in react-native i get this error:
Unknown plugin "transform-es5-property-mutators" specified in "/Users/marcel/Desktop/Allgaier/allgaier_app/node_modules/aws-api-gateway-client/package.json"
and if i remove that line in the package.json i get the next error:
Unknown npm modul "@ava/stage-4" specified in "/Users/marcel/Desktop/Allgaier/allgaier_app/node_modules/aws-api-gateway-client/package.json"

Any ideas?

version: 0.2.14 (latest)

How can I get custom headers from API Gateway?

I get custom header "X-Pagination-Total-Count" from my backend. And I have header mapping in AWS gateway, so I get X-Pagination-Total-Count header from API gateway. But I don't see this header in aws-api-gateway-client sdk.
Here is my code:

this.apigClient.invokeApi({}, '/some_resource', 'GET').then(res => {
    console.log(res); // res.headers has only content-type: "application/json"
})

Query Parameters with single quotes fails signature

When passing a query parameter with a single quote, authorization fails. According to the latest SDK generated from one of my API gateway API's, the following function should be used in place of encodeURIIComponent:

function fixedEncodeURIComponent (str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}

Single quotes should be escaped.

Adding retry capability

Has there been any thought to adding retry capability to the client. In particular, occasionally we get a 503 error returned from API gateway. This is a retriable error likely due to a transient error. It would be nice if we could specify retriable error conditions and counts. axios-retry could be used to configure axios with these parameters.

Request for HTTPS resource fails with SSL23_GET_SERVER_HELLO:unknown protocol when an HTTPS_PROXY has been configured in HTTPS over HTTP mode

Error: write EPROTO 140735491711808:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:825:

at _errnoException (util.js:1024:11)
at WriteWrap.afterWrite (net.js:867:14)

Steps to reproduce:

// This is a sample request that doesn't even use IAM authentication.
const apigClient = apigClientFactory.newClient({
    accessKey: '',
    invokeUrl: 'https://abcdefghij.execute-api.us-east-1.amazon.com/stage',
    region,
    secretKey: ''
});
const response = apigClient.invokeApi({}, '/api/something', 'GET', {}, {});

I've tested the same request through the new axios pre-release and it works:

const response = await axios.get('https://abcdefghij.execute-api.us-east-1.amazon.com/stage/api/something', {});

Signing still broken. Also, retries fail if retry condition is not explicitly defined.

Since other issues on the subject have been closed, despite still being an issue...

Signing fails if retries are enabled, after v0.2.17

The cause of this, is that the alternate retry logic does not properly utilize the signed request payload, causing a signature mismatch.

My PR #102 resolves this, and additionally handles the scenario where retries are defined, but no retryCondition is defined in the config, which given it's 'optional' status should naturally fallback to utilize the default axios-retry condition -- which is does with this PR.

{message: "The security token included in the request is invalid."}

Version 0.2.7 is showing {message: "The security token included in the request is invalid."} randomly for any API call after the initialization and the reason behind this is that the x-amz-security-token not being set and sent to the API Gateway as undefined

Header:
x-amz-security-token:undefined

Couldn't catch error status codes

Unable to catch the error status code, i could only catch error message as 'Network Error', Even though the console shows the status codes as 403(), 502()... I am unable to catch that.

Error doesn't let you capture any response data

In our API we like to return information about errors especially 400 bad requests. For example:
{ "email": [ "Missing data for required field." ] }

However, the error thrown seems to only contain the status code:
Error: Request failed with status code 400

Burying the response data on error makes it more tedious to troubleshoot errors during implementation. Could a second parameter be added to the error callback that contains the response?

Audit issue

Hello,

We use the package "aws-api-gateway-client" and we get the following audit issue even with the last version:

  High            Server-Side Request Forgery                                   
                                                                                
  Package         axios                                                         
                                                                                
  Patched in      >=0.21.1                                                      
                                                                                
  Dependency of   aws-api-gateway-client                                        
                                                                                
  Path            aws-api-gateway-client > axios                                
                                                                                
  More info       https://npmjs.com/advisories/1594 

When you plan to merge the MR #106 ?

Import with Weback

Are there any known issues with importing this using Webpack?

import { apigClientFactory } from 'aws-api-gateway-client'

This builds ok, but returns:

TypeError: Cannot read property 'newClient' of undefined

When I try the following:

var apigClient = apigClientFactory.newClient({

What am I doing wrong here?

edit:

This syntax works ok:

var awsApiGatewayClient = require('aws-api-gateway-client')
var apigClient = awsApiGatewayClient.newClient({

headers/queryParams getting set to empty objects

https://github.com/kndt84/aws-api-gateway-client/blob/master/apigClient.js#L96-L97

apigClient.invokeApi = function (params, pathTemplate, method, additionalParams, body) {
	if (additionalParams===undefined) additionalParams={};
	if (body===undefined) body='';
        
        var request = {
            verb: method.toUpperCase(),
            path: pathComponent + uritemplate.parse(pathTemplate).expand(params),
            headers: apiGateway.core.utils.parseParametersToObject(params, []), // here
            queryParams: apiGateway.core.utils.parseParametersToObject(params, []), // here
            body: body
        };
        
        return apiGatewayClient.makeRequest(request, authType, additionalParams, config.apiKey);
    };
parseParametersToObject: function (params, keys) {
        if (params === undefined) {
            return {};
        }
        var object = { };
        for (var i = 0; i < keys.length; i++) {
            object[keys[i]] = params[keys[i]];
        }
        return object;
    }

The AWS generated SDK would have hard coded the keys expected into those empty arrays. As this stands, I expect every request headers and queryParams to be set to {}.

Not sure what a solution would be, but I simple eliminated the use of parseParametersToObject, and passed the params directly since I knew the structure I was expecting in my API.

response data is null

I am trying to make a PUT API call, and i need to now the row ID created by current PUT API call.

I could see using postman that data was successfully save in DB. But however in the response the data is null.

formResponsePushAPI(type) {
let client = this.client_build(
"https://api.test.cernerweatherman.com/v1/questionnaireresponse"
);

    let pathParams = {};
    // Template syntax follows url-template https://www.npmjs.com/package/url-template
    let pathTemplate = "";
    let method = "PUT";
    let additionalParams = {};
    let body = {
      Status: ",
      CreatedBy: ""
    };

    client
      .invokeApi(pathParams, pathTemplate, method, additionalParams, body)
      .then(res => {
          console.log("res", res);
        let response_id = res.data["Id"];
        console.log("res", response_id);
      })
      .catch(function(result) {
        console.log(result);
        // console.log("res");
        //This is where you would put an error callback
      });
  }

"POST body payload" issue

Hi takashi ! I am using you aws api client for my project and I have an problem, maybe, I 'm doing something wrong. I am using an API made by me. This API has an POST endpoint. but when I trying to invoke to me API from your client, happens that is not pass the "body", this is my code:

static getUserList(idList) {
    const pathParams = {};
    const pathTemplate = '/common/users/list';
    const method = 'POST';
    const additionalParams = {
      headers: {}
    };
    const body = { //"users": ["bfq3vjthebt34r7fjt20", "bhq2o55hebt2hu1np3b0"]};
      //This is where you define the body of the request
      users: idList
    };

    return apigClient.invokeApi(pathParams, pathTemplate, method, additionalParams, body);
  }

Apigateway returns {"message":"Missing Authentication Token"}

Hi,
I passed those three tokens in
apigwClient = apigwClientFactory.newClient({
accessKey: awsCredentails.accessKeyId,
secretKey: awsCredentails.secretAccessKey,
sessionToken: awsCredentails.sessionToken,
invokeUrl: JSON.parse(awsmobile.aws_cloud_logic_custom)[0].endpoint
});

with API gateway auth on with IAM, the API service can not load the data from dynamodb. Return a {"message":"Missing Authentication Token"}

InvalidSignatureException on POST

Hi, I am developing an angular2 application and started using this client. I am able to call GET API without problem, however API gateway returns InvalidSignatureException when POST API is called.

Can't seem to find the reason for the failure. Only the method type is changed between these 2 requests.
Would really appreciate some help here.

Response:
Connection:keep-alive Content-Length:913 Content-Type:application/json Date:Fri, 28 Apr 2017 09:00:22 GMT Via:1.1 cd506e499a8d4ba06493f1ac8ef2cb9c.cloudfront.net (CloudFront) X-Amz-Cf-Id:L3DRIihKtz28zy3wOM5_AUpCqSWp9VWvamJeajq0JHqyhfLV31wEMg== x-amzn-ErrorType:InvalidSignatureException x-amzn-RequestId:1c5b0889-2bf1-11e7-8dcc-038e5a6b122f X-Cache:Error from cloudfront

Request:
Accept and Content-Type is 'application/json'
Body is a JSON string

Add typescript types

Thanks for this super library. Please could you add the typescript types either to this repository or publish them to DefinitelyTyped

post to APIGATEWAY

Hi - is it possible to use the library to POST and aws api gateway endpoint with node?

If I do this:
let resp = await apigClient.invokeApi(pathParamaters, pathTemplate, 'POST' , {}, body )

I get get back:

'The request signature we calculated does not match the signature you provided.....

If I do this:

let resp = await apigClient.invokeApi(pathParamaters, pathTemplate, 'POST' , {} )

The call succeeds with a 200 - but the body is empty and my function needs to pass data in the body to Lambda event

What am I doing wrong?

Thanks for any help!

[React Native Android]: Method GET must not have a request body

I'm using this module on my react-native project to connect to my respective AWS services (IAM, lambda, dynamoDB). It seems to be working fine on the IOS side but fails on Android.

const listServices = (id) => api.invokeApi({ id }, '/services/{id}', 'GET', undefined, undefined)

When sending a GET request via the code above, it throws an error 'Method GET must not have a request body'.

  1. Is this module appropriate for react-native? In the documentations, it mentions that this 'module can be used not only for Node.js but for front-end.' Should I be using aws-sdk-js instead?
  2. I replaced 'undefined' with 'null' but that does not solve the issue.It only throws an error on the javascript side. Undefined throws an error on the Java side.

Thank you (in advance) for any assistance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.