我正在创建一个API,该API使用Node.js,Serverless,Javascript更新Firebase Realtime数据库。
我的.js文件:
var admin = require("firebase-admin");
var serviceAccount = require("../xxxxxxx-firebase-adminsdk-xxxxxxx.json");
module.exports.saveState = (event, context, callback) => {
const body = JSON.parse(event.body);
var timestamp_create = body.timestamp_create;
try {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://xxxxxxx.firebaseio.com"
});
} catch (err) {
console.log('Firebase initialization error', err.stack);
}
var db = admin.database();
var ref = db.ref('item/');
ref.child(timestamp_create).set({
state: 'empty'
}, function (error) {
if (error) {
console.log("Data could not be saved." + error);
} else {
console.log("Data saved successfully.");
return callback(null, {
headers: {
"Access-Control-Allow-Origin": "*",
},
statusCode: 200,
body: JSON.stringify({ msg: "Data saved successfully." })
});
}
});
};
我将API部署到AWS并在Postman上进行测试:
问题和我的尝试:
("Data saved successfully.")
,但根本没有执行return callback
。API在AWS环境(lambda)中不返回回调。
任何建议都值得赞赏。
答案 0 :(得分:0)
经过长时间的Google和测试,我找到了一个解决方案,请留在此处以供参考:
保存数据后不会释放firebase数据库连接,因此AWS Lambda无法返回回调。简单的解决方案是任务完成后关闭数据库连接
var ref = db.ref('item/');
ref.child(timestamp_create).set({
state: 'empty'
}, function (error) {
if (error) {
console.log("Data could not be saved." + error);
} else {
console.log("Data saved successfully.");
db.gpOffline(); // this line will release database connection
return callback(null, {
headers: {
"Access-Control-Allow-Origin": "*",
},
statusCode: 200,
body: JSON.stringify({ msg: "Data saved successfully." })
});
}
});