Seneca FAQ
最近在学习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 协议》,转载必须注明作者和本文链接