Search code examples
amazon-web-servicesaws-lambdaaws-sdk-nodejs

Lambda function with UpdateRestApiCommand, how to update to work in version node 18


I updated a lambda function to node 18, but there are changes to do with my UpdateRestApiCommand.

Here's the original that worked in the older version:

    const request = apigateway.updateRestApi(params);
    request
      .on('success', function(response) {
        console.log("Success!");
        resolve(response.data);
      }).
      on('error', function(error, response) {
        console.log("Error!");
        reject(response.error);
      }).
      on('complete', function(response) {
        console.log("Done!");
      })
      .send()
  });

Here's my imports:

const https = require("https");
const env = process.env.ENV;
const resource = process.env.RESOURCE;
const restApiId = process.env.REST_API_ID;
const ce_base_url = process.env.CE_BASE_URL;
const { APIGatewayClient, UpdateRestApiCommand  } = require("@aws-sdk/client-api-gateway");
const stage = process.env.STAGE;

And now I've found I need to use UpdateRestApiCommand I think so I've got this:

    new  UpdateRestApiCommand(params)
      .on('success', function(response) {
        console.log("Success!");
        resolve(response.data);
      }).
      on('error', function(error, response) {
        console.log("Error!");
        reject(response.error);
      }).
      on('complete', function(response) {
        console.log("Done!");
      })
      .send()
  });

Here's the error I'm getting:

ERROR   Invoke Error    
{
    "errorType": "TypeError",
    "errorMessage": "(intermediate value).on is not a function",
    "stack": [
        "TypeError: (intermediate value).on is not a function",
        "    at /var/task/index.js:64:8",
        "    at new Promise (<anonymous>)",
        "    at exports.handler (/var/task/index.js:36:25)",
        "    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"
    ]
}

Solution

  • The nodejs18.x runtime has the AWS JS SDK v3 pre-installed. Earlier runtime versions came with v2.

    Here's the basic pattern to use the v3 SDK clients in a Lambda handler:

    const client = new APIGatewayClient({
      region: process.env.AWS_REGION,
    });
    
    export async function handler(event, context) {
      // ...
    
      const cmd = new UpdateRestApiCommand(params);
    
      const response = await client.send(cmd);
    }