I’ve upload 2 json file under Assets (as private) on Twilio serverless, I know that I need a function to let the code access this file, but it seams not working my code:
exports.handler = async function(context, event, callback) {
const fileName = event.fileName || ''; // Expect a fileName parameter in the request
const assets = Runtime.getAssets();
const fs = require('fs').promises;
// Define the path for known private assets
const assetPaths = {
'abc.json': assets['/abc.private.json'].path,
'def.json': assets['/def.private.json'].path,
};
// Check if the requested file is a known private asset
if (assetPaths[fileName]) {
try {
const fileContent = await fs.readFile(assetPaths[fileName], 'utf8');
// Return the file content with appropriate content type
let contentType = 'application/json';
if (fileName.endsWith('.bin')) {
contentType = 'application/octet-stream';
}
return callback(null, new Twilio.Response({
statusCode: 200,
headers: {
'Content-Type': contentType,
},
body: fileContent,
}));
} catch (err) {
console.error('Error reading asset:', err);
return callback(null, new Twilio.Response({
statusCode: 500,
body: 'Internal Server Error',
}));
}
} else {
// If the requested file is not a known private asset, return a 404
return callback(null, new Twilio.Response({
statusCode: 404,
body: 'Not Found',
}));
}
};
In more in my main html code I have this:
const abcURL = "my twilio function url ?fileName=abc.private.json";
const defURL = "my twilio function url ?fileName=def.private.json";
What I’m missing?
The purpose of all is to give access to those private file only to the code, making unreachable from others.
Hope You can help with the code!
With different try, I get or the 403 error or the 404 error, instead the code should load the json files.
Alan One is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.