Search code examples
vue.jsaxioshttprequestaws-api-gatewayaws-amplify

Proper way to call a lambda function?


I am building an app with vue.js, severless and aws lambda function. I dont know what is the proper way to call a lambda function, and so far my initial solution is:

  1. set up an api in api gateway for that function which generates a link.
  2. hard code that link inside my vue frontend and use axios as my http client to make request.

But my problem is:

  1. Is hard coding the url inside the frontend a proper thing to do?
  2. if I have multiple lambda functions then I will have a bunch of urls, and that does not seem like a good way to implement this.

in my main.js of the vue frontend I had this set up:

Amplify.configure({
  Auth: {
    mandatorySignIn: true,
    region: config.cognito.REGION,
    userPoolId: config.cognito.USER_POOL_ID,
    identityPoolId: config.cognito.IDENTITY_POOL_ID,
    userPoolWebClientId: config.cognito.APP_CLIENT_ID
  },
  Storage: {
    region: config.s3.REGION,
    bucket: config.s3.BUCKET,
    identityPoolId: config.cognito.IDENTITY_POOL_ID
  },
  API: {
    endpoints: [
      {
        name: "Test",
        endpoint: config.apiGateway.URL,
        region: config.apiGateway.REGION
      },
    ]
  }
});

if my approach is correct, do I add multiple endpoints under the API config since i have more then one lambda function? and if not whats the proper way to implement this?

thanks in advance.


Solution

  • A quick glance at the docs here shows that the recommended setup is to set endpoint to the base URL of the Api Gateway. For example, if you navigate to the Api Gateway, under "Dashboard", you should see a link similar to the following:

    https://1234567.execute-api.us-east-2.amazonaws.com/Stage

    This is the link that you should be setting endpoint to.

    Then, you would use it like so:

    API
      .get("Test", "/path/to/lambda")
      .then(response => {
        // Add your code here
      })
    

    Reference here for usage

    However, if you're using regional endpoints, as referenced here, then your setup is correct, and you would then need to create a new entry for each lambda you have. This is recommended against by the Amplify team though.

    Rather than hardcoding, I would recommend setting these URLs as environment variables, which give you a lot more flexibility on deployments.