對於我的函數項目,我一直把我的可重用資源放入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,即將每個功能放入其自己的節點模塊中。那是你在找什麼? –