[英]How to reuse or factorize code?
我目前正在編寫許多Firebase函數,其中一些共享相同的變量和函數。 目前,我將它們粘貼到各自的倉庫中時將它們復制粘貼到每個Firebase Functions文件中,但是我不知道在它們之間共享代碼的最佳實踐是什么? 對於變量來說,配置文件會很酷,對於代碼來說,所有函數都可以繼承的類,但是我不確定如何清理它?
組織:目前,我有一個index.js文件,該文件引用了我擁有的所有Firebase函數。 每個Firebase功能都是一個JS文件。 那就是我所擁有的層次結構,不是最優的也不是可維護的...
例子
有人已經想到了嗎? 謝謝你的幫助!
對於我的Functions項目,我一直將可重用的資源放入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);
};
將功能放在GitHub存儲庫下並從master分支調用它們不是一種選擇嗎? 我目前正在package.json中這樣導入:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"cex-converter": "https://github.com/joaquinperaza/cex-converter/tarball/master"
},
"private": true
}
那么您只需要像require('cex-converter')
這樣的conde依賴項,就可以獲取依賴項的最新版本,而無需修改任何內容即可部署您的最新版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.