Skip to content

Instantly share code, notes, and snippets.

@baartch
Created March 19, 2024 11:08
Show Gist options
  • Save baartch/bb6f6045567de83d98eb853d7786897b to your computer and use it in GitHub Desktop.
Save baartch/bb6f6045567de83d98eb853d7786897b to your computer and use it in GitHub Desktop.
AWS Lambda for creating zip archive
// built-ins
import archiver = require('archiver');
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { Upload } from '@aws-sdk/lib-storage';
import { PassThrough, Readable } from 'stream';
const clientS3 = new S3Client();
interface IEventBody {
bucket: string;
target: string;
keys: { key: string; isDir: boolean }[];
}
async function createArchive(Bucket: string, zipFileName: string, fileKeys: IEventBody['keys']) {
const archive = archiver('zip', { zlib: { level: 1 } }); //https://www.zlib.net/manual.html
const passThrough = new PassThrough();
archive.pipe(passThrough);
const upload = new Upload({
client: clientS3,
params: {
Key: zipFileName,
Bucket,
Body: passThrough,
},
});
for (const fileKey of fileKeys) {
try {
const response = await clientS3.send(new GetObjectCommand({ Bucket, Key: fileKey.key }));
archive.append(response.Body as Readable, { name: fileKey.key });
} catch (error) {
console.error(`Error streaming file ${fileKey}: ${JSON.stringify(error)}`);
throw error;
}
}
archive.finalize();
const uploadResult = await upload.done();
console.log('Response: ', uploadResult);
console.log(`Zip file ${zipFileName} uploaded successfully to ${Bucket} bucket.`);
}
export const handler = async (event: IEventBody): Promise<void> => {
// Log the event
console.log('Lambda event: ', event);
// Extract the bucket and file keys from the event
const { bucket, target: zipFileName, keys: fileKeys } = event;
// Create the archive
await createArchive(bucket, zipFileName, fileKeys);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment