Skip to content

Commit

Permalink
Simplify promise code in s3-lambda-copyzip (pulumi#256)
Browse files Browse the repository at this point in the history
Use `async` to simplify the code.
  • Loading branch information
lukehoban committed Mar 11, 2019
1 parent f1fd9f2 commit 954b4c0
Showing 1 changed file with 8 additions and 27 deletions.
35 changes: 8 additions & 27 deletions aws-ts-s3-lambda-copyzip/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,21 @@ const tpsReports = new aws.s3.Bucket("tpsReports");
const tpsZips = new aws.s3.Bucket("tpsZips")

// Anytime a new TPS Report is uploaded, archive it in a zipfile.
tpsReports.onObjectCreated("zipTpsReports", (e) => {
tpsReports.onObjectCreated("zipTpsReports", async (e) => {
const AdmZip = require("adm-zip");
const ops = [];
const s3 = new aws.sdk.S3();
for (const rec of e.Records || []) {
const zip = new AdmZip();
const [ buck, key ] = [ rec.s3.bucket.name, rec.s3.object.key ];
console.log(`Zipping ${buck}/${key} into ${tpsZips.bucket.get()}/${key}.zip`);
const zipOp = new Promise((resolve, reject) => {
s3.getObject(
{ Bucket: buck, Key: key },
(err, data) => {
if (err) {
reject(err);
return;
}
zip.addFile(key, data.Body);
// console.log(`Report: ${data.ContentLength}, Zip: ${zip.toBuffer().length}`);
s3.putObject(
{
Bucket: tpsZips.bucket.get(),
Key: `${key}.zip`,
Body: zip.toBuffer(),
},
(err) => {
if (err) reject(err);
else resolve();
},
);
});
});
ops.push(zipOp);
const data = await s3.getObject({ Bucket: buck, Key: key }).promise();
zip.addFile(key, data.Body);
await s3.putObject({
Bucket: tpsZips.bucket.get(),
Key: `${key}.zip`,
Body: zip.toBuffer(),
}).promise();
}
return Promise.all(ops).then(() => Promise.resolve());
});

// Finally, export the zipfile bucket name, for ease of access.
Expand Down

0 comments on commit 954b4c0

Please sign in to comment.