Search code examples
javascriptfirebasegoogle-cloud-functionsappsflyer

Firebase cloud functions error - Function returned undefined, expected Promise or value


I'm trying to log a purchase event on Appsflyer with a Google Cloud Function when a new document is created but I have this error.

All my interpolations seems to be good in my logs. My function is

exports.validatePaymentAppsflyer = functions.firestore.document('_orderFinishedSuccessfully/{id}').onCreate((snap, context) => {

    console.log(snap, context);

    const newValue = snap.data();
    const requestData = newValue;
    console.log(requestData.platform);

    if ( requestData.platform === 'ios' ) {
        appId = 'id1303984176';                
    } else {
        appId = 'com.myapp';                
    }

    var request = require("request");

    var options = { method: 'POST',
    url: 'https://api2.appsflyer.com/inappevent/' + appId,
    headers: 
    { 
        "authentication": 'M762jn36Bb7kBt70jNdtrU',
        'Content-Type': 'application/json' 
        },
    body: 
    { appsflyer_id: requestData.appsflyerId,
        customer_user_id: requestData.customerUserId,
        eventName: 'af_purchase',
        eventValue: {
            "af_revenue":requestData.totalTTC,
            "af_order_id":requestData.orderId,
            "af_city":requestData.city,
            "af_date_b":requestData.date
        },
        eventCurrency: 'EUR',
        ip: requestData.userIp,
        eventTime: requestData.date,
        af_events_api: 'true' },
    json: true };

    console.log(options);


    request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
    });
});

I need your help


Solution

  • Cloud functions are expected to return something meaningful, most often you'd want to return a Promise. That way the engine will know that your async operations have finished and doesn't have to wait for a timeout to happen.

    To fix your code, just return a Promise:

    return new Promise((resolve, reject) => {
        request(options, function (error, response, body) {
            if (error) reject(error);
            else resolve(response);
        });
    });