LoginSignup
1
0

More than 5 years have passed since last update.

APIGatewayからLambdaを経由してS3のコンテンツを取得する

Posted at

概要

S3に格納したHTLMファイルをLmabdaを経由してAPI Gatewayで取得します。

今作ってるアプリがAPI Gatewayから直接S3をつついているのですが、コンテンツをバックエンドで動的生成したくなったので間にLambdaの処理を噛ませることにしました。

バックエンドロジックを組む前にまずは素通りさせる方法を調査しました。

環境

Node.js 8.10

実装

1. Lamndaの実装

const AWS = require('aws-sdk');

exports.handler = async (event) => {
    AWS.config.region = 'ap-northeast-1';
    const s3 = new AWS.S3();
    try {
        let data = await s3.getObject({
            Bucket: 'bucket_name',
            Key: 'path/to/file.html'
        }).promise();

        return {
            statusCode: 200,
            headers: {"Content-Type": "text/html"},
            body: data.Body.toString(),
        };
    } catch (e) {
        return {
            statusCode: 500,
            body: JSON.stringify(e.message),
        };
    }
};

2. API Gatewayの設定

  1. 統合リクエストを LAMBDA_PROXY
  2. メソッドレスポンスのコンテンツタイプを text/html

apigateway.png

ポイント

  • Content-Typeを指定する

    Lambda側で Content-Type を明示的に指定しないと application/json として取り扱われる。

  • s3.getObject() の構造

    テキストデータを返すときは data.Body.toString() でデコードする。
    データ構造を詳しく知りたいならば JSON.stringify(data) を返してテストしたらわかりやすい。

参考文献

ここを読めば答えは書いてある
https://nkgr.hatenablog.com/entry/2018/06/26/220000

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0