I have created a simple Post API, Where I received the name, nameSpace, image_icon, and apk_attachment from the frontend, and then inside the controller, I extract(using apkinfo module) packageName from apk_attachment and validate accordingly, from the below code you will have the idea.
HERE IS THE CONTROLLER FUNCTION:
const apkinfo = require('apkinfo');
const appData = async (req, res) => {
try {
console.log('inside post controllers');
const { name, nameSpace, status } = req.body;
// Check if required fields are provided
if (!name || !nameSpace || !req.files['apk_attachment'] || req.files['apk_attachment'].length === 0 || !req.files['icon_image']) {
return res.status(400).json({
success: false,
error: 'Bad Request',
message: 'All fields (name, namespace, apk_attachment, icon_image) are required.',
data: null
});
}
const iconImage = req.files['icon_image'] ? req.files['icon_image'][0].filename : null;
const apkAttachment = req.files['apk_attachment'] ? req.files['apk_attachment'][0].filename : null;
// Extract information from the uploaded APK file
const apkFilePath = `uploads/${apkAttachment}`;
const apkInfo = await extractApkInfo(apkFilePath);
...rest of the code
} catch (error) {
console.log(error);
if (error.name === 'SequelizeDatabaseError' && error.message.includes('Data truncated')) {
return res.status(400).json({
success: false,
error: 'Bad Request',
message: 'One or more fields contain invalid data. Please check your input.',
data: null
});
}
return res.status(500).json({
success: false,
error: error,
message: 'An unexpected error occurred | Internal Server Error',
data: null
});
}
}
fucntion to extrect APK information using apkinfo
const extractApkInfo = async (apkFilePath) => {
return new Promise((resolve, reject) => {
apkinfo.get(apkFilePath, (error, info) => {
if(error) {
console.error('Error in apkinfo.get:', error);
reject(error)
} else {
console.log('APK Info from apkinfo.get:', info);
resolve({
appName: info.appName,
packageName: info.packageName,
versionCode: info.versionCode,
versionName: info.versionName,
});
}
});
});
};
NOTE: without apk_attachment it returns ‘All fields (name, namespace, apk_attachment, icon_image) are required.’ because of the validation but with apk_attachemt it shows the below ERROR from catch block:
{
"success": false,
"error": {
"killed": false,
"code": 127,
"signal": null,
"cmd": "/www/wwwroot/deazitech.com/updater/node_modules/apkinfo/lib/aapt_linux d badging uploads/9be87de64c55cc4276c80e5a33ee601a"
},
"message": "An unexpected error occurred | Internal Server Error",
"data": null
}
The same code on the local machine works perfectly fine.
