繁体   English   中英

如何从 Lambda 返回 promise

[英]How to return a promise from Lambda

我正在尝试通过 AWS Amplify 将我的 NextJS 应用程序连接到 Google 日历 API。我添加了一个带有“Amplify Add API”的 API。 选择“Rest”并选择“Serverless Express Function”。 到目前为止,一切都很好。 测试 function 有效。 我正在利用代理集成让 lambda 决定如何处理代码。 这是我的客户端代码:

 import React from "react"; import { API } from "aws-amplify"; const getCalendar = () => { React.useEffect(() => { getCal(); async function getCal() { const apiName = 'gcal'; // api name. const path = '/events'; // API path await API.get(apiName, path).then(response => { console.log(response) }).then(() => console.log(` the resopnse returned successfully as: ${JSON.stringify(response.body) }`)).catch(error => { console.log(`there was an error returning the response from the lambda function: ${error}`); }); } },[]) } export default getCalendar;

在 Lambda function 内部,我从代理集成示例开始,并替换为以下代码。 问题是,来自 Google API 的响应是可见且正确的,但客户端未从 Lambda 收到响应。我尝试了回调、async/await 和 res.send()。 我知道我在下面的 function 中遗漏了一些关于请求的异步性质的内容。 从 Cloud Watch Logs 获取 500 或 502 错误。 Lambda index.js 代码(有问题):

 const awsServerlessExpress = require("aws-serverless-express"); require("dotenv").config(); var express = require("express"); var bodyParser = require("body-parser"); var awsServerlessExpressMiddleware = require("aws-serverless- express/middleware"); const { google } = require("googleapis"); const calendar = google.calendar("v3"); var app = express(); const server = awsServerlessExpress.createServer(app, null); app.use(bodyParser.json()); app.use(awsServerlessExpressMiddleware.eventContext()); app.use(function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "*"); res.header("Content-Type", "*"); next(); }); exports.handler = (event, context) => { return awsServerlessExpress.proxy(server, event, context, "PROMISE").promise; }; app.post("/events", function () { main(); async function main() { const auth = new google.auth.GoogleAuth({ keyFilename: "./<my-secret-file>.json", scopes: [ "https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly", ], }); const now = new Date().toISOString(); // Acquire an auth client, and bind it to all future calls const authClient = await auth.getClient(); google.options({ auth: authClient }); // Do the magic let response = await calendar.events.list({ calendarId: process.env.API_CALENDAR_ID, showHiddenInvitations: false, timeMin: now, showDeleted: false, }); return await response.json(); } return res.send(response); }); app.listen(3000, function () { console.log("Google Calendar Function Is Running"); });

以下是开发者工具中从 Google API 到 Lambda 的工作响应: 在此处输入图像描述

完成后我收到 {"message": "Internal server error"}。 这是 Lambda 对客户端的失败尝试响应: 在此处输入图像描述

在 Cloud Watch Logs 中,我得到“无帮助”和成功响应: 在此处输入图像描述

任何帮助或建议将不胜感激。

我发现答案是将 promises 与 async await 以及 res.send() 混合使用。 从 Google API 返回数据后,我仍然需要格式化响应并设置正确的标头。 这是工作代码。

const awsServerlessExpress = require("aws-serverless-express");
require("dotenv").config();
var express = require("express");
var bodyParser = require("body-parser");
var awsServerlessExpressMiddleware = require("aws-serverless- 
express/middleware");
var app = express();
const server = awsServerlessExpress.createServer(app, null);

app.use(awsServerlessExpressMiddleware.eventContext());
app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("Content-Type", "application/json");
  next();
});
app.use(bodyParser.json());

const { google } = require("googleapis");
const calendar = google.calendar("v3");
exports.handler = (event, context) => {

  return awsServerlessExpress.proxy(server, event, context, 
"PROMISE").promise;
};
app.get("/events", function( req, res ) {

  async function main() {
    try {
    const auth = new google.auth.GoogleAuth({
      keyFilename: "./my-secret-file.json",
      // Scopes can be specified either as an array or as a single, 
space-delimited string.
  scopes: [
    "https://www.googleapis.com/auth/calendar",
    "https://www.googleapis.com/auth/calendar.readonly",
  ],
});
const now = new Date().toISOString();
// Acquire an auth client, and bind it to all future calls
const authClient = await auth.getClient();
google.options({ auth: authClient });


let responseBody = await calendar.events.list({
  calendarId: process.env.API_CALENDAR_ID,
  showHiddenInvitations: false,
  timeMin: now,
  showDeleted: false,
});
// Do the magic
let response =
{
  "isBase64Encoded": "false",
  "statusCode": "200",
   "headers": {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers": "*",
      "Content-Type": "application/json",
      "Access-Control-Allow-Methods": "*"

   },
  "body": responseBody,
};

   return res.send(JSON.stringify(response))
  } catch (error) {
  console.log(error);
}}
main();
});

app.listen(3000, function () {
  console.log("The Google Calendar Function Is Running");
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM