Lamda ends the process and it's not waiting for the API response. here is my code:
exports.handler = async (event, context, cb) => {
try {
console.log('FETCHING RECORDS FROM DATOCMS')
const allItems = await client.items.all({}, { allPages: true })
if (!fs.existsSync(backupDir)){
// Create backup directory
console.log('CRETING BACKUP DIRECTORY')
fs.mkdirSync(backupDir, { recursive: true });
}
console.log('FILL JSON WITH RECORDS FETCHED FROM DATOCMS')
fs.writeFileSync('backup/records.json', JSON.stringify(allItems, null, 2));
console.log('ADDING BACKUP FOLDER TO ZIP')
zip.addLocalFolder(backupDir);
const zipFileContents = zip.toBuffer();
const params = {
Bucket: S3_BUCKET,
Key: `backup_zip-${backupDate}`,
Body: zipFileContents,
ContentType: "application/zip",
ContentDisposition: `attachment; filename="${fileName}-${backupDate}"`
}
console.log('UPLOADING ZIP TO S3', params)
s3.putObject(params, (err, data) => {
if (err) {
cb(null, 'Error')
throw new Error('The zip file could not be uploaded', err);
}
console.log('Uploaded correctly')
cb(null, 'Success')
fs.rmdirSync(backupDir, { recursive: true });
})
} catch (err) {
cb(null, 'Error..')
throw new Error('An error occurred', err)
}
}
I also tried adding this two lines with no luck
setInterval(() => {}, 1000);
context.callbackWaitsForEmptyEventLoop = false;
Can anyone help me? I've been testing Promises, Async/Await, Callbacks and no luck with that. Thanks!
This is the response in CloudWatch
CodePudding user response:
Try to map the promises, then await
on Promise.all
. I'm not sure if all
returns array of promises.
const promises = client.items.map(it=>...)
const promises = client.items.all(it=>...)
await Promise.all(promises)
CodePudding user response:
You aren't waiting for s3.putObject
. It should be:
const data = s3.putObject(params).promise();
You handle the error in a try/catch.
CodePudding user response:
Remove the async
keyword from the handler. You can't use the callback function in the async/await function.
Try to use the aws sdk function with .promise();