对于我的函数项目,我一直把我的可重用资源放入functions/lib
,并要求它们通常作为npm模块。我也一直从定义中分离出函数中使用的代码,这有助于测试。
例如,考虑这样的结构:
functions/
|-index.js
|-newWidget.function.js
|-lib/
| |-Widget.js
test/
|-newWidget.functions.spec.js
现在,如果我要声明一个触发器来处理新的窗口小部件,我像做了以下内容:
// functions/index.js:
const functions = require('firebase-functions');
exports.processNewWidget = functions.https.onRequest(require('./newWidget.function.js').process);
// functions/newWidget.function.js
exports.process = function(req, res) {
res.send('Hello world!');
};
// test/newWidget.function.spec.js
// Note how we can easily test our widget processor separate from
// the third-party dependencies!
const newWidget = require('../functions/newWidget.function.js');
describe('newWidget',() => {
describe('process',() => {
it('should send hello world', function() {
const req = {};
cost res = { send:() => {} };
spyOn(res.send);
newWidget.process(req, res);
expect(res.send).toHaveBeenCalledWith('Hello world!');
});
});
});
并包含类从newWidget.functions.js内部调用Widget,我做这样的事情:
// functions/lib/Widget.js
class Widget {
constructor(name) { this.name = name; }
}
exports.Widget = Widget;
// functions/newWidget.function.js
class Widget = require('./lib/Widget').Widget;
exports.process = function(req, res) => {
const widget = new Widget(req.param.name);
res.send(widget.name);
};
有几个问题如何为Firebase模块化Cloud Functions,即将每个功能放入其自己的节点模块中。那是你在找什么? –