0
votes

Function code below

prepay.post('/' , (req, res) => { 

    req.on("data", function (chunk) {
        strdat += chunk;
        console.log(strdat);
        
    }).on("end", function()
    {
        var data = JSON.parse(strdat);
        var cryp = crypto.createHash('sha512');
        var text = \\ some data;
        cryp.update(text);
        var hash = cryp.digest('hex');      
        res.setHeader("Content-Type", "text/json");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end(JSON.stringify(hash));      
    });
     req.on('error', function(err){
        console.log(err.message)
    });
    
});

exports.prepay = functions.https.onRequest(prepay); 

================================= this is tried on emulator in the logs getting ! functions: Your function timed out after ~60s. To configure this timeout, see https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memory_allocation.

\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:660 throw new Error("Function timed out.");

works fine when ran locally with nodejs using node server.js

not sure if req.on supported by firebase will be helpful if I get some reference on req.on in firebase functions

1
Add logging that demonstrates how the code executes, up until the very end of every code path. What does that reveal about what's actually happening?Doug Stevenson

1 Answers

0
votes

Your event-based sample of code won't work due to the preprocessing of the request that is done by the Firebase Functions SDK. Simply put, all of the 'data' and 'end' events have occurred prior to your code being executed.

Inside of functions.https.onRequest, the request is consumed and parsed according to it's content type automatically as documented here. If your request body is one of the below recognised types, it will be parsed and available as request.body. If you wish to work with the raw buffer of data, it is exposed as a Buffer as request.rawBody.

Content Type                        Request Body        Behavior
application/json                    '{"name":"John"}'   request.body.name equals 'John'
application/octet-stream            'my text'           request.body equals '6d792074657874' (the raw bytes of the request; see the Node.js Buffer documentation)
text/plain                          'my text'           request.body equals 'my text'
application/x-www-form-urlencoded   'name=John'         request.body.name equals 'John'

This preprocessing allows you to get to the actual function of your code faster.

prepay.post('/' , (req, res) => { 
    const data = req.body;
    const cryp = crypto.createHash('sha512');
    const text = \\ some data;
    cryp.update(text);
    const hash = cryp.digest('hex');
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.json(hash);
});

exports.prepay = functions.https.onRequest(prepay);