Search code examples
node.jsasync-awaitapi-design

How to write a GET api that calls a function to insert data into the db before running the actual select by Id statement?


I wrote a scanMetadata function that takes the id passed in the url, does some computation and inserts data into the file metadata table. The api I'm creating is get_metadata, which has to run this function first before it runs Filemetadata.findById which selects the record in fileMetadata table based on the id. I tried writing it like this, but it'll always return "Incomplete response received from application". Both functions when run individually works fine.

exports.getMetadata = async (req, res, next) => {
   await scanMetadata(req.params.fileId);
    FileMetadata.findById(req.params.fileId, (err, data) => {
        if (err) {
            if (err.kind === "not_found") {
                res.status(404).send({
                    message: `Not found file with id ${req.params.fileId}.`
                });
            } else {
                res.status(500).send({
                    message: `Error retrieving file with id ${req.params.fileId}.`
                });
            }
        } else res.send(data);

    });
};

My api route is this

app.get('/get_metadata/:fileId', files.getMetadata); 

Scan metadata function

let scanMetadata = async function scanMetadata (fileId) {
        let file = await get_files(fileId);

        let serverFilePath = file.serverFilePath;
        //TODO:Change hereto read serverFilePath after all record from table is apk
        let reader = ApkReader.readFile("C:\\Users\\user\\Source\\Repos\\ApkScanner\\backend\\app\\files\\Instagram_v1550037107_apkpurecom.apk");
        let manifest = reader.readManifestSync();
        let versionCode = manifest.versionCode;
        let versionName = manifest.versionName;
        let package = manifest.package;
        let minSdk = manifest.usesSdk.minSdkVersion;
        let targetSdk = manifest.usesSdk.targetSdkVersion;
        let launcherActivityName = manifest.application.launcherActivities[0].name;
        let icon = manifest.application.icon;
        await insert_metadata(versionCode, versionName, package, fileId, minSdk, targetSdk,launcherActivityName, icon);
        await update_files();
    
}

Solution

  • Its the problem with serverFilePath. I hardcoded the file path which are local files but not the absolute file path in the server.