AWS Lambdaの書き方でわからない部分があります。
awsのElasticSearchから検索結果を返すAPIをAPI Gatewayで作成しました。
LambdaFunctionが以下になります。
node.js
1'use strict'; 2const https = require('https'); 3module.exports.h = (event, context, callback) => { 4 5 var json = {"query": {"match_all": {}}} 6 7 const options = { 8 protocol: 'https:', 9 host: 'ap-northeast-1.elasticsearch.amazonaws.com', 10 path: '/index/type/_search', 11 method: 'GET', 12 headers: { 13 'Content-Type': 'application/json', 14 'Content-Length': Buffer.byteLength(JSON.stringify(json)) 15 } 16 }; 17 18 const req = https.request(options, (res) => { 19 res.setEncoding("utf-8"); 20 res.on('data', (chunk) => { 21 callback(null, `${chunk}`); 22 }); 23 }); 24 req.write(JSON.stringify(json)); 25 req.end(); 26};
問題なくElasticSearchの検索結果が返ってきます。
しかしこれでは、「Lambdaプロキシ統合の使用」Lambda Proxy Integrationの機能が有効にならないため、
https://qiita.com/_mogaming/items/2bd83204e212e35b2c6c
を参考に以下に書き換えました
node.js
1'use strict'; 2const https = require('https'); 3module.exports.hello = (event, context, callback) => { 4 5 var json = {"query": {"match_all": {}}} 6 const response = new Response(); 7 response.body = JSON.stringify({ 8 "event": json, 9 "context": context 10 }); 11 12 const options = { 13 protocol: 'https:', 14 host: 'ap-northeast-1.elasticsearch.amazonaws.com', 15 path: '/index/type/_search', 16 method: 'GET', 17 headers: { 18 'Content-Type': 'application/json', 19 'Content-Length': Buffer.byteLength(response) 20 } 21 }; 22 23 const req = https.request(options, (res) => { 24 res.setEncoding("utf-8"); 25 res.on('data', (chunk) => { 26 callback(null, `${chunk}`); 27 }); 28 }); 29 req.write(response); 30 req.end(); 31}; 32 33class Response{ 34 constructor(){ 35 this.statusCode = 200; 36 this.headers = {}; 37 this.body = ""; 38 } 39}
しかし、これではLambdaFunctionはerrorを表示します。
errorcode
1Response: 2{ 3 "errorMessage": "RequestId: 666bb666-666b-66b6-666d-6666bbb6b666 Process exited before completing request" 4}
どの様に書けば、「Lambdaプロキシ統合の使用」に対応した形に書き換えることができるでしょうか?
あなたの回答
tips
プレビュー