2017-10-11 55 views
-1

我目前正在編寫大量Firebase函數,其中一些共享相同的變量和函數。 目前我將它們複製粘貼到每個Firebase函數文件中,因爲它們是孤立的,但我不知道在它們之間共享代碼的最佳做法是什麼?對於變量來說,一個配置文件會很酷,對於代碼來說,所有的函數都可以繼承,但我不確定如何做到這一點乾淨?如何重用或分解代碼?

組織:目前我有一個引用所有Firebase函數的index.js文件。每個Firebase函數都是一個JS文件。這是我有層次,不是最佳的,也沒有維護...

例子

  • 變量: 我現在有寫Mailgun的API密鑰在我所有的火力地堡
  • 功能: getThisProcessDone()我目前複製了所有的Firebase功能

任何人都已經有這個想法?謝謝你的幫助!

+0

有幾個問題如何爲Firebase模塊化Cloud Functions,即將每個功能放入其自己的節點模塊中。那是你在找什麼? –

回答

1

讓你的函數在GitHub倉庫下並從主分支調用它們不是一種選擇嗎?我目前進口像這樣的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')孔德依賴,你會得到你的依賴的最後一個版本,不需要修改任何部署您的最後一個版本。

+1

感謝華金,我要先嚐試加藤解決方案,如果它足夠穩定,我一定會包裝一切,如你所說:) – ibox

3

對於我的函數項目,我一直把我的可重用資源放入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); 
}; 
+0

謝謝加藤,我會去你的建議,但看起來像類語法不工作。例如,當我嘗試做「class Widget = ...」時,出現錯誤「意外的標記=」,而建築:( – ibox

+0

聽起來像你有舊版本的節點? – Kato