在我构建的应用中,用户可以请求一个单词,应用程序会转到在线牛津词典API以获取定义,发音等。我使用Firebase云功能进行HTTP请求,并将响应写入Cloud Firestore。有时候它很慢......十分之九的数据都没有写入Firestore。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const request = require('request'); // node module to send HTTP requests
admin.initializeApp();
exports.oxford_English_US = functions.firestore.document('Users/{userID}/English_American/Word_Request').onUpdate((change, context) => {
console.log(change.before.data());
console.log(change.after.data());
console.log(context.params.userID);
if (change.after.data().word != undefined) {
let options = {
url: 'https://od-api.oxforddictionaries.com/api/v1/entries/en/' + change.after.data().word + '/pronunciations%3Bregions%3Dus',
headers: {
"Accept": "application/json",
'app_id': 'TDK',
'app_key': 'swordfish'
}
};
function callback(error, response, body) {
console.log(response.statusCode);
if (error) {
console.log(error)
}
if (!error && response.statusCode == 200) {
var word = JSON.parse(body);
console.log(word);
admin.firestore().collection('Users').doc(context.params.userID).collection('English_American').doc('Word_Response').set({
'metadata': word.metadata,
'results': word.results
})
.then(function() {
console.log("Document written.");
})
.catch(function(error) {
console.log("Error writing document: ", error);
})
}
}
request(options, callback);
} else {
console.log("change.after.data().word === undefined");
}
return 0;
});
这里是一个函数调用的日志:
12:55:12.780 PM oxford_English_US { metadata: { provider: 'Oxford University Press' }, results: [ { id: 'to', language: 'en', lexicalEntries: [Object], type: 'headword', word: 'to' } ] }
12:55:12.480 PM oxford_English_US 200
12:55:09.813 PM oxford_English_US Function execution took 3888 ms, finished with status: 'ok'
12:55:09.739 PM oxford_English_US bcmrZDO0X5N6kB38MqhUJZ11OzA3
12:55:09.739 PM oxford_English_US { word: 'to' }
12:55:09.732 PM oxford_English_US { word: 'have' }
12:55:05.926 PM oxford_English_US Function execution started
该功能在四秒钟内执行。功能完成后三秒钟," 200"状态代码返回,带有数据。数据永远不会写入Firestore。
看起来Cloud功能不会等待HTTP响应。
这是另一个功能日志,其中Cloud Function在发出HTTP请求之前似乎已完成执行:
1:02:29.319 PM oxford_English_US Function execution took 3954 ms, finished with status: 'ok'
1:02:29.218 PM oxford_English_US bcmrZDO0X5N6kB38MqhUJZ11OzA3
1:02:29.218 PM oxford_English_US { word: 'to' }
1:02:29.213 PM oxford_English_US { word: 'the' }
1:02:25.365 PM oxford_English_US Function execution started
是否有更好的Node模块用于发送HTTP请求? request
具有以下语法:
request(options, callback);
我宁愿回复承诺而不是回电。
答案 0 :(得分:3)
您的Google云端功能应始终返回Promise。如果您未能返回Promise,您将面临竞争条件,在该条件下,应用程序容器可能会在代码完成之前被拆除。
来自您的示例代码:
exports.oxford_English_US = functions.firestore.document('Users/{userID}/English_American/Word_Request').onUpdate((change, context) => {
return new Promise(function(resolve, reject) {
// put your code here and resolve() or reject() based on outcome
});
}
来自Firebase YouTube频道(2.后台触发器 - 返回承诺)"当该功能中的待处理工作完成后,您必须返回已履行或拒绝的承诺。这让Cloud Functions知道何时可以安全地清理函数调用并转移到下一个函数调用。"
答案 1 :(得分:0)
我将节点模块request
更改为request-promise
。它现在可靠而快速地执行。这是我的新代码:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const rp = require('request-promise');
admin.initializeApp();
exports.oxford_English_US = functions.firestore.document('Users/{userID}/English_American/Word_Request').onUpdate((change, context) => {
if (change.after.data().word != undefined) {
let options = {
uri: 'https://od-api.oxforddictionaries.com/api/v1/entries/en/' + change.after.data().word + '/pronunciations%3Bregions%3Dus',
headers: {
"Accept": "application/json",
'app_id': 'TDK',
'app_key': 'swordfish'
},
json: true
};
rp(options)
.then(function (word) {
admin.firestore().collection('Users').doc(context.params.userID).collection('English_American').doc('Word_Response').set({
'metadata': word.metadata,
'results': word.results
})
.then(function() {
console.log("Document written.");
})
.catch(function(error) {
console.log("Error writing document: ", error);
})
})
.catch(function (error) {
console.log(error);
})
} else {
console.log("change.after.data().word === undefined");
}
return 0;
});