最近在學習Senecajs,讀英文件總該留點什麼,如是有了這些技術概要
structure
- 業務邏輯分離進外掛
- 執行指令碼編排應用
- 外掛載入順序很重要,控制訊息組合
- 在Seneca中使用第三方框架極小化
var SOME_CONFIG = process.env.SOME_CONFIG || 'some-default-value'
require('seneca')({ some_options: 123 })
// existing Seneca plugins
.use('community-plugin-0')
.use('community-plugin-1', {some_config: SOME_CONFIG})
.use('community-plugin-2')
// your own plugins with your own business logic
.use('project-plugin-module')
.use('../plugin-repository')
.use('./lib/local-plugin')
.listen( ... )
.client( ... )
.ready( function() {
// your own custom code - executed once Seneca is spun up
})
Fatal error
- 所有外掛必須被載入且初始化成功,否則微服務處於無定義狀態
- Seneca 載入, 先定義外掛,後初始化(可選)
- 外掛定義同步進行
// file: foo.js
// The string `foo` will be the name of the plugin.
module.exports = function foo(options) {
// `this` === context Seneca instance with fatal$ === true
// the pattern is `a:1`
this.add('a:1', function (msg, reply) {
reply({x: msg.x})
})
}
- 外掛初始化[可選]
init:<plugin-name>
行為內建於外掛定義 - 初始化部分負責外掛與外部世界互動,非同步執行
// file: foo.js
// The function `foo` will be the name of the plugin.
module.exports = function foo(options) {
this.add('a:1', function (msg, reply) {
reply({x: msg.x})
})
this.add('init:foo', function (msg, reply) {
// do something asynchronous 與外部世界互動
database_setup(options, function(err) {
// call reply to indicate that the plugin is initialized,
// no need for response data
reply(err)
})
})
}
seneca.ready
直到所有外掛完成定義並初始化後才會被回撥
Respond message
一旦訊息模式被匹配,將會觸發與之關聯的行為函式執行,該函式有如下三引數
msg
reply
原型callback(err, result)
meta
元物件debug追蹤
const Seneca = require('seneca')
const seneca = Seneca()
seneca
.add({a: 1}, function(msg, reply) {
reply(null, {x: msg.y})
})
seneca.act({a: 1, y: 2}, function(err, out) {
console.log(err) // prints null, as there was no error
console.log(out) // prints {x: 2}, as that was the response given to `reply`
})
reply
回撥支援以下形式簽名
reply(null, {z: 3})
reply({z: 3})
reply(new Error('my error message')
reply()
實操中,與之有相同簽名可以這樣用
const Fs = require('fs')
seneca
.add({file: 'read'}, function(msg, reply) {
Fs.stat(msg.path, reply)
})
本作品採用《CC 協議》,轉載必須註明作者和本文連結