我刚刚在我的Firebase项目(免费套餐)中部署了云功能。
这是代码的最小版本:
const admin = require('firebase-admin');
const functions = require('firebase-functions');
const Fuse = require('fuse.js');
const _ = require('lodash');
admin.initializeApp(functions.config().firebase);
exports.minimal = functions.https.onRequest((request, response) => {
let category = request.query.cat ? request.query.cat.toLowerCase().trim() : undefined;
let classification = request.query.class ? request.query.class.toLowerCase().trim() : undefined;
let catName, className;
return admin.database().ref('categories').once('value').then(snapshot => {
_.each(snapshot.val(), (value, key) => {
_.each(value, (value2, key2) => {
if ( key2 === 'id' && value2 == category ) catName = key;
else if ( value2.id == classification ) className = key2;
});
});
return _.split(request.query.q, ',');
})
.then(literals => {
return admin.database().ref(`mappings/${catName}/${className}`).once('value').then(snapshot => {
let mappings = _.map(snapshot.val(), (value, key) => {
return {
literal: key,
code: value
};
});
const options = {
shouldSort: true,
includeScore: true,
threshold: 0.3,
location: 0,
distance: 50,
maximumPatternLength: 64,
minMatchCharacterLength: 1,
keys: ["literal"]
};
let fuse = new Fuse(mappings, options);
let results = {};
let classCodes = {};
_.each(literals, literal => {
let searchResults = fuse.search(literal);
if ( ! searchResults.length ) {
results[literal] = { status: 'not-matched' };
}
else {
if ( ! classCodes[searchResults[0].item.code] ) {
classCodes[searchResults[0].item.code] = { code: searchResults[0].item.code, standard: '' };
}
results[literal] = {
status: 'matched',
mapping: classCodes[searchResults[0].item.code]
};
}
});
return admin.database().ref(`classification-systems/${catName}/${className}`).once('value').then(snapshot => {
_.each(snapshot.val(), (value, key) => {
if ( classCodes[key] ) classCodes[key].standard = value;
});
response.json(results);
});
});
})
.catch(error => { // Never gets triggered
if ( ! response._headerSent ) response.json(error)
else console.error(error);
});
});
我在本地运行它(但所有数据库操作都在实时数据库上执行),在数据库中2000+键中搜索的100个单词的平均响应时间为1.5秒。
在部署的功能上运行相同的测试代码导致平均响应时间为45秒!!!
为什么实时云功能表现如此糟糕?
无论如何都能实现与本地功能相同的响应时间吗?当前的响应时间是非常不可接受的。
感谢任何帮助。