Firebase可调用函数返回空结果

时间:2019-08-09 15:17:01

标签: javascript firebase google-cloud-functions google-cloud-sql

以下Google Cloud函数返回空结果。

相同的代码可以与onRequest一起正常工作,并按预期返回数据。我想使用可调用函数,以便轻松地将参数发送到该函数。有人知道这是怎么回事吗?

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)); 
}

});
})

2 个答案:

答案 0 :(得分:2)

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

您使用的mysqljs/mysql库不会返回Promises,因此一种方法是使用promise-mysql,它“是mysqljs/mysql的包装器,其中包装了带有Bluebird Promise的函数调用”。 / p>

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

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
    });

});

答案 1 :(得分:0)

您还可以将Promise封装在mysqljs / mysql中。

position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); max-width: 100%; max-height: 100%;