Created
December 15, 2018 15:20
-
-
Save varlal/b7ed2851aabece748fe681c1d8d89ca3 to your computer and use it in GitHub Desktop.
S3に保存したjsonファイルに変更を加え別のS3バケットに保存するサンプル
This file contains 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
{ "accessKeyId": "<id>", "secretAccessKey": "<key>", "region": "ap-northeast-1" } |
This file contains 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'); | |
//config.jsonは以下のようなAPIアクセスキーとリージョン情報を含むjsonファイル | |
//{ "accessKeyId": "<id>", "secretAccessKey": "<key>", "region": "ap-northeast-1" } | |
AWS.config.loadFromPath('./config.json'); | |
const s3 = new AWS.S3(); | |
exports.handler = async (event) => { | |
//eventからPUTされたバケットと、keyを取得 | |
console.log(event['Records'][0]['s3']['bucket']['name']); | |
console.log(event['Records'][0]['s3']['object']['key']); | |
//putされた内容を取得(jsonファイル→jsonObject); | |
const getObjectParams = { | |
Bucket: event['Records'][0]['s3']['bucket']['name'], | |
Key: event['Records'][0]['s3']['object']['key'] | |
}; | |
let jsonObject = await S3GetObjectAsync(getObjectParams); | |
//jsonを加工(メインの処理) | |
jsonObject["testkey"] = "add json"; | |
//S3へアップロード | |
const putObjectparams = { | |
Bucket: '<保存先のバケット名>', | |
Key: 'json/' + getObjectParams['Key'], | |
Body: JSON.stringify(jsonObject) | |
}; | |
await S3PutObjectAsync(putObjectparams); | |
//レスポンス(このコードではあまり意味はない) | |
const response = { | |
statusCode: 200, | |
body: JSON.stringify('Hello from Lambda!'), | |
}; | |
return response; | |
}; | |
function S3PutObjectAsync(params) { | |
return new Promise(function(resolve, reject) { | |
s3.putObject(params, function(err, data) { | |
if (err) { | |
console.log(err); | |
reject(err); | |
} else { | |
console.log("Successfully uploaded data to '" + params['Bucket'] + "'/" + params['Key']); | |
resolve(data); | |
} | |
}); | |
}); | |
} | |
function S3GetObjectAsync(params) { | |
return new Promise(function(resolve, reject) { | |
s3.getObject(params, function(err, data) { | |
if (err) { | |
console.log(err, err.stack); | |
reject(err); | |
} else { | |
var object = JSON.parse(data.Body.toString()); | |
resolve(object); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment