From 4e14ab1c592edbb806f9b448c0dbd8cf4e1ef5dc Mon Sep 17 00:00:00 2001 From: Semen Date: Thu, 30 Apr 2020 15:35:17 +0300 Subject: [PATCH] feat: add hooks before (#315) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add hooks before * Rephrasing of description. * Apply suggestions from code review fix typos Co-authored-by: Fran Méndez Co-authored-by: Semen Tenishchev Co-authored-by: Fran Méndez --- docs/authoring.md | 31 ++++++++++++++++++++++++++++++- lib/generator.js | 1 + 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/docs/authoring.md b/docs/authoring.md index c0aca779a..db909bfad 100644 --- a/docs/authoring.md +++ b/docs/authoring.md @@ -76,8 +76,16 @@ In case you have more than one template and want to reuse filters, you can put t ## Hooks -Hooks are functions called by the generator on a specific moment in the generation process. For now there is one hook supported called `generate:after` that is called at the very end of the generation. The generator will parse all the files in the `.hooks` directory. +Hooks are functions called by the generator on a specific moment in the generation process. +The following types of hooks are currently supported: +|Hook name|Description| +|---|---| +| `generate:before` | Called after registration of all filters and before generator starts processing of the template.| +| `generate:after` | Called at the very end of the generation. | + +The generator will parse all the files in the `.hooks` directory. +#### Examples Below you have an example Hook that after generation creates an AsyncAPI file. ```js @@ -100,6 +108,27 @@ module.exports = register => { }); }; ``` +And here an example Hook that before generation switches `publish` and `subscribe` operations for each channel. + +```js +module.exports = register => { + register('generate:before', generator => { + const asyncapi = generator.asyncapi; + for (let [key, value] of Object.entries(asyncapi.channels())) { + let publish = value._json.publish; + value._json.publish = value._json.subscribe; + value._json.subscribe = publish; + if (!value._json.subscribe) { + delete value._json.subscribe; + } + if (!value._json.publish) { + delete value._json.publish; + } + } + }); +}; +``` + ## Partials diff --git a/lib/generator.js b/lib/generator.js index 45ef3ddfd..5052928d6 100644 --- a/lib/generator.js +++ b/lib/generator.js @@ -147,6 +147,7 @@ class Generator { await this.loadTemplateConfig(); this.registerHooks(); await registerFilters(this.nunjucks, this.templateConfig, this.templateDir, FILTERS_DIRNAME); + await this.launchHook('generate:before'); if (this.entrypoint) { const entrypointPath = path.resolve(this.templateContentDir, this.entrypoint);