-
-
Save hyuki/65854dae7fd2af33eccdd83955c9d16f to your computer and use it in GitHub Desktop.
index.js - BUCKETで指定したバケットの内容を Lambda Function URLs で表示する。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const AWS = require('aws-sdk'); | |
| const BUCKET = process.env.BUCKET; | |
| const ACCESS_KEY = process.env.ACCESS_KEY; | |
| const SECRET_KEY = process.env.SECRET_KEY; | |
| const REGION = process.env.REGION; | |
| AWS.config.update({ | |
| credentials: new AWS.Credentials(ACCESS_KEY, SECRET_KEY) | |
| }); | |
| const S3 = new AWS.S3({apiVersion: '2006-03-01'}); | |
| const TEXT_PLAIN = 'text/plain; charset=UTF-8'; | |
| exports.handler = async (event) => { | |
| const id = event.requestContext.http.path.substr(1); | |
| const promise = new Promise((resolve, reject) => { | |
| S3.getObject({ | |
| Bucket: BUCKET, | |
| Key: id, | |
| }).promise().then(data => { | |
| // https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getObject-property | |
| const content_type = id.endsWith(".txt") ? TEXT_PLAIN: data.ContentType; | |
| resolve({ | |
| statusCode: 200, | |
| headers: { | |
| 'Content-Type': content_type, | |
| }, | |
| body: Buffer.from(data.Body).toString('base64'), | |
| isBase64Encoded: true, | |
| }); | |
| }).catch(error => { | |
| console.log(`error = ${error}`); | |
| resolve({ | |
| statusCode: 404, | |
| headers: { | |
| 'Content-Type': TEXT_PLAIN, | |
| }, | |
| body: `Not Found`, | |
| }); | |
| }); | |
| }); | |
| return promise; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment