私はexpress.jsフレームワーク上に構築されたnode.jsアプリケーションを持っています。我々は設定をインスタンス化再初期化エクスプレスアプリケーション
const app = express();
require('./config')(app);
require('./services')(app);
./config/config.js:我々はサービスインスタンス(シングルトン)
module.exports = (app) => {
app.set('apiService', new APIService(app));
};
function APIService(app) {
const config = app.get('config');
this.key = config.APIKey;
};
APIService.prototype.sendRequest =() => {
const config = app.get('config');
this._send(config.url, 'some text');
};
または、サービス2を作成
module.exports = function (app) {
const conf = {APIKey: 1234567890, url: '<someurl>'};
app.set('config', conf);
};
./services/APIService.js
module.exports = function(app) {
const config = app.get('config');
const myMod = require('myMod')(config.APIKey);
}
クール、すべて正常に動作します。しかし、いつか管理者がいくつかの設定データを変更します。だから、私たちは新しい設定を作成し、CHANGED URLにリクエストを送信します
newConf = {APIKey: 1234000000, url: '<some_new_url>'};
app.set('config', newConf);
APIService.sendRequest、に彼を設定しますが、APIService.keyまだ変わりません。 myModは既に古い設定データでインスタンス化されています。
は、我々は、この
//for APIService
APIService.prototype.setConfig =() => {
const config = app.get('config');
this.key = config.APIKey;
};
//for service 2
/* change const myMod to let myMod and create method for overriding */
または強打のように、いくつかのsetterメソッドを書く必要があります! node.jsサーバープロセスを終了して再起動します。悪いアイデア。アプリケーション(または多分、彼の部品)を安全に再初期化するためのapp.restart()のような何らかの方法がこの目標のために存在するのでしょうか?
はい、私は新しい設定値ですべてのエンティティを上書きする必要があるようです(または依存関係ごとにセッターを作成する)。しかし、IMHO、より良い方法と私はより洗練されたアプローチを、多分ネイティブの明示的な方法を探しています –
Expressはミドルウェアに関するすべてですhttp://expressjs.com/en/guide/writing-middleware.html(私の例のコードのような) –