使用扩展插件
Midway FaaS 工具链提供了完整兼容Serverless插件的能力,只需要在 f.yml 文件中进行配置工具链即可自动加载,目前有如下几种插件加载方式:
plugins:- npm::fcli-plugin-test # 已发布npm的插件- local::../../test # 本地的插件
开发扩展插件
通过工具链插件能力,可以将你自定义的CLI命令添加到 f 命令中,也可以对现有的调用、打包、发布等命令进行扩展。
添加新的子命令
Midway FaaS 提供了很方便的CLI扩展基类,继承此基类可以快速地创建工具链扩展:
import { BasePlugin } from '@midwayjs/fcli-command-core';export class TestPlugin extends BasePlugin {commands: { // 用于定义提供哪些命令ttt: { // 命令名称,插件加载后可以通过 f ttt 这样调用usage: 'test command'; // 命令使用提示lifecycleEvents: ['a', 'b', c]; // 生命周期,会依次执行,详见下文options: { // 参数列表,参数会自动绑定到 this.options 上name: { // 参数名,可以通过 f ttt --name=xxx 传入usage: 'test name'; // 参数提示shortcut: 'n'; // 参数缩写,可以通过 f ttt -n=xxx 传入}};};};constructor(core, options) {super(core, options);// 可以通过 this.core 来获取全局共享的 内核数据// 可以通过 this.options 来获取全局共享的 参数列表}// 生命周期钩子列表,在执行对应命令时依次执行其生命周期。// 在次添加的生命周期钩子可以是当前插件提供的命令的生命周期,如 ttt 命令的 a、b、c 中某几个生命周期。// 也可以添加其他插件提供的命令的生命周期,如 invoke 命令的 clean 生命周期等。// 每个钩子都支持 asynchooks = {'ttt:a': async () => {}, // 在执行到ttt命令的a生命周期 时 执行的逻辑'after:ttt:c': async () => {}, // 在ttt命令的c生命周期执行 之后 执行的逻辑'before:ttt:b': async () => {}, // 在ttt命令的b生命周期执行 之前 执行的逻辑};}
同时,BasePlugin 基类还提供了几个内置方法:
getName()string用于返回当前插件名称,默认为 ClassNamesetStore(type: string, value: any)void用于全局数据存储,会自动拼接当前插件名(getName方法获取)getStore(type: string, name?: string)any用于获取已存储的全局数据,可传入存入数据的插件名,默认为当前插件名,即当前插件存入的数据。
另外, this.core 定义:
{classes: { // 内置类Error, // 错误类},store, // 全局存储,也就是提供 getStore 和 setStore 的底层cli, // 命令行IO,类似于 console 对象,有log、error等方法config, // 配置数据getProvider(providerName: string), // 通过 provider name,获取provider// 通过 provider name,设置providersetProvider(providerName: string,providerInstance),// 调用某命令// - commandsArray 为多级命令,如 [invoke, local] 则执行 invoke的二级子命令 local// - allowEntryPoints 为是否可以调用 entryPoints// - options 调用参数invoke(commandsArray?: string[],allowEntryPoints?: boolean,options?: any),// 调用某命令// - commandsArray 可以为多级命令,如invoke参数,也可以为多级命令字符串,如 invoke:local,与多级命令等价// - options 调用参数spawn(commandsArray: string | string[],options?: any),// debug (verbose)输出,仅当传入 -V 参数时才会进行输出// 此方法会同时输出调用栈,及每一步调用时长,便于调试debug(...args),// Yaml 文件数据service,}
扩展现有命令
通过插件不新增命令,仅对现有的命令进行一些功能性的补全:
import { BasePlugin } from '@midwayjs/fcli-command-core';export class TestHooksPlugin extends BasePlugin {// 仅定义 hookshooks = {'after:invoke:clean': async () => {console.log('after clean');},};}
