简体   繁体   English

如何从 Lambda 返回 promise

[英]How to return a promise from Lambda

I'm trying to connect my NextJS application via AWS Amplify to the Google Calendar API. I added an API with "Amplify Add API".我正在尝试通过 AWS Amplify 将我的 NextJS 应用程序连接到 Google 日历 API。我添加了一个带有“Amplify Add API”的 API。 Selected "Rest" and chose "Serverless Express Function".选择“Rest”并选择“Serverless Express Function”。 So far so good.到目前为止,一切都很好。 The test function works.测试 function 有效。 I am utilizing Proxy integration to let lambda decide what to do with the code.我正在利用代理集成让 lambda 决定如何处理代码。 Here is my client side code:这是我的客户端代码:

 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;

Inside the Lambda function I started with the Proxy Integration sample and replaced with the code below.在 Lambda function 内部,我从代理集成示例开始,并替换为以下代码。 The issue is, the response is visible and correct from Google API but not received by the client from Lambda. I tried a callback, async/await, and res.send().问题是,来自 Google API 的响应是可见且正确的,但客户端未从 Lambda 收到响应。我尝试了回调、async/await 和 res.send()。 I know I'm missing something in this function below regarding the async nature of the request.我知道我在下面的 function 中遗漏了一些关于请求的异步性质的内容。 Getting 500 or 502 errors from Cloud Watch Logs.从 Cloud Watch Logs 获取 500 或 502 错误。 Lambda index.js code(with problem): 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"); });

Here is the working response from Google API to Lambda in Dev Tools:以下是开发者工具中从 Google API 到 Lambda 的工作响应: 在此处输入图像描述

I am receiving {"message": "Internal server error"} after completion.完成后我收到 {"message": "Internal server error"}。 Here is the failed attempted response to the client from Lambda:这是 Lambda 对客户端的失败尝试响应: 在此处输入图像描述

inside Cloud Watch Logs I get "no help", and a succeeded response:在 Cloud Watch Logs 中,我得到“无帮助”和成功响应: 在此处输入图像描述

Any help or suggestions would be greatly appreciated.任何帮助或建议将不胜感激。

I found out the answer was in both mixing promises with async await and also with res.send().我发现答案是将 promises 与 async await 以及 res.send() 混合使用。 After returning the data from Google API I still needed to format the response and set the correct headers.从 Google API 返回数据后,我仍然需要格式化响应并设置正确的标头。 Here is the working code.这是工作代码。

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