返回空结果的 Firebase 可调用函数

Firebase callable function returning null result

下面的 google 云函数 returns 为空结果。

相同的代码可以正常处理 onRequest 和 returns 数据,符合预期。我想使用可调用函数以便轻松地将参数发送给函数。有人知道这里出了什么问题吗?

const functions = require('firebase-functions');
const mysql = require('mysql');

exports.getUserData = functions.https.onCall((data, context) => {

const connectionName =
  process.env.INSTANCE_CONNECTION_NAME || 'instance';
const dbUser = process.env.SQL_USER || 'root';
const dbPassword = process.env.SQL_PASSWORD || 'password';
const dbName = process.env.SQL_NAME || 'someDb';

const mysqlConfig = {
  connectionLimit: 1,
  user: dbUser,
  password: dbPassword,
  database: dbName,
};
if (process.env.NODE_ENV === 'production') {
  mysqlConfig.socketPath = `/cloudsql/${connectionName}`;
}

let mysqlPool;

if (!mysqlPool) {
    mysqlPool = mysql.createPool(mysqlConfig);
}

mysqlPool.query('SELECT * from table where id = 1', (err, results) => {

if (err) {
  console.error(err);
} else {     
  data.send(JSON.stringify(results)); 
}

});
})

正如您将在官方 Firebase 视频系列 (https://firebase.google.com/docs/functions/video-series/) 中关于 "JavaScript Promises" 的三个视频中看到的那样,您必须 return 您的 Cloud Function 中的一个 Promise 或一个值,以向平台表明它已经完成。

您使用的 mysqljs/mysql 库没有 return Promise,所以一种方法是使用 promise-mysql,"is a wrapper for mysqljs/mysql that wraps function calls with Bluebird promises"。

我还没有尝试过,但按照以下几行应该可以解决问题:

const functions = require('firebase-functions');
const mysql = require('mysql');
const mysqlPromise =require('promise-mysql'); 

exports.getUserData = functions.https.onCall((data, context) => {

    //.....

    const connectionOptions = ...;

    return mysqlPromise.createPool(connectionOptions)   //you must return the Promises chain
    .then(pool => {
       return pool.query('SELECT * from table where id = 1')
    })
    .then(results => {
       return(results: JSON.stringify(results)); 
       //send back the response with return() not with data.send(), see the doc
    })
    .catch(error => {
        //See the Callable Functions doc: https://firebase.google.com/docs/functions/callable#handle_errors_on_the_client
    });

});

你也可以mysqljs/mysql给你一个承诺。

return new Promise((resolve, reject) => {

    if (!id) {
        resolve({success: false, customer: null, msg: 'No id provided.'});
    }

    let connection = mysql.createConnection({
        host: db.host,
        user: db.user,
        password: db.password,
        database: db.database
    });

    connection.connect(function (err) {
        
        if (err) {
            resolve({success: false, customer: null, msg: err});
        }

        let sql = "SELECT * FROM customers WHERE uid = ?);"
        let values = [id];

        connection.query(sql, values, function (error, result) {
            if (error) {
                console.log(error);
                return {success: false, customer: null, msg: error};
            } else {
                if (result.length) {
                    connection.destroy();
                    resolve({success: true, customer: customer});

                } else {
                    connection.destroy();
                    resolve({success: false, customer: null, msg: 'No customer details'});
                }

            }
            
        });
    });
});