使用 then-request 模块,在 Lambda 上对 HTTP 请求进行同步处理

首先

当Lambda通过同步请求调用API时,它发现了一个模块sync-request,但该模块在商业环境中不被推荐使用,而推荐使用的是then-request。

使用then-request时是异步处理的,但是通过使用await,可以将其转换为同步处理。以下是使用Lambda函数来使用then-request进行同步API调用并返回结果的方法总结。

如果需要同时获取网页和API的参考,我认为这个选择很有用。

然后请求模块

为了使用then-request模块,需要在本地安装then-request模块。

$ mkdir nodejs
$ cd nodejs
$ npm init -y
$ ls
package.json

$ npm install then-request

$ touch index.js

$ tree
.nodejs
├── index.js
├── node_modules
├── package-lock.json
└── package.json

$ zip -r nodejs.zip *

需要在创建Lambda后上传被压缩的nodejs.zip文件。
为此,我还创建了index.js文件。

使用Lambda创建

スクリーンショット 2022-10-14 11.39.37.png
スクリーンショット 2022-10-14 11.41.09.png
スクリーンショット 2022-10-14 12.15.04.png

我将介绍在请求时使用的POST和GET两种不同的方式。

选项1:
如果是POST请求的代码1

const request = require('then-request');

exports.handler = async (event, context, callback) => {
  const data = {
    title: 'user',
    api_key: 'testest',
  };
  // awaitで同期処理
  const apiResponse = await request('POST', 'https://example.co.jp/', { json: data })
    .getBody('utf8')
    .then(JSON.parse);
  console.log('Received apiResponse:', JSON.stringify(apiResponse, null, 2));
};

这是一个简单的POST请求。
如果以json格式进行POST,需要以{ json: data }的形式传递。同时也需要使用.then(JSON.parse)。

以下是(使用POST方法的)代码2。

這是(使用POST方法的)代碼 2。

const request = require('then-request');

exports.handler = async (event, context, callback) => {
  const apiData = [
    {
      api_url: 'https://fuga.com',
      api_key: 'fugafuga',
    },
    {
      api_url: 'https://example.com',
      api_key: 'testest',
    },
  ];

  let userIds = [];

  await Promise.all(
    apiData.map(async (item, index) => {
      const data = {
        title: 'user',
        api_key: item.api_key,
      };
      // awaitで同期処理
      const apiResponse = await request('POST', item.api_url, { json: data })
        .getBody('utf8')
        .then(JSON.parse);

      userIds.push(apiResponse.user_id);
    })
  );
  console.log('Received userIds:', JSON.stringify(userIds, null, 2));
  return userIds;
};

在使用map方法时,如果要使用async和await,必须使用Promise.all()。

如果是GET请求, 请提供代码(Code)。

const request = require('then-request');

exports.handler = async (event, context, callback) => {
  const apiResponse = await request('GET', 'https://example.co.jp/', { timeout: 2000 })
    .getBody('utf8');

  console.log('Received apiResponse:', JSON.stringify(apiResponse, null, 2));
};

如果在2秒内没有回应,{ timeout: 2000 }将会超时。

请参考。

 

广告
将在 10 秒后关闭
bannerAds