Hooks

Found an error? Have a suggestion?Edit this page on GitHub

Hooks are functions called by the generator on a specific moment in the generation process. Hooks can be anonymous functions but you can also add function names. These hooks can have arguments provided to them or being expected to return a value.

Types

The following types of hooks are currently supported:

Hook typeDescriptionReturn typeArguments
generate:beforeCalled after registration of all filters and before the generator starts processing of the template.void : Nothing is expected to be returned.The generator instance
generate:afterCalled at the very end of the generation.void : Nothing is expected to be returned.The generator instance
setFileTemplateName Called right before saving a new file generated by file template.string : a new filename for the generator to use for the file template.The generator instance and object in the form of { "originalFilename" : string }

Location

The generator parses:

  • All the files in the .hooks directory inside the template.
  • All modules listed in the template configuration and triggers only hooks whose names were added to the config. You can use an official hooks library that is bundled together with the generator. To learn how to add hooks to configuration read more about the configuration file.

Examples

Some of the examples have names of hook functions provided and some not. Keep in mind that hook functions kept in template in default location do not require a name. Name is required only if you keep hooks in non default location or in a separate library, because such hooks need to be explicitly configured in the configuration file. For more details on hooks configuration read more about the configuration file.

Most basic modules with hooks look like this:

1module.exports = {
2  'generate:after': generator => console.log('This runs after generation is complete')
3}

Below you have an example Hook that after generation creates an AsyncAPI file.

1const fs = require('fs');
2const path = require('path');
3
4module.exports = {
5  'generate:after': generator => {
6    const asyncapi = generator.originalAsyncAPI;
7    let extension;
8
9    try {
10      JSON.parse(asyncapi);
11      extension = 'json';
12    } catch (e) {
13      extension = 'yaml';
14    }
15
16    fs.writeFileSync(path.resolve(generator.targetDir, `asyncapi.${extension}`), asyncapi);
17  }
18};

And here an example Hook that before generation switches publish and subscribe operations for each channel.

1module.exports = {
2  'generate:before': function switchOperations(generator) {
3    const asyncapi = generator.asyncapi;
4    for (let [key, value] of Object.entries(asyncapi.channels())) {
5      let publish = value._json.publish;
6      value._json.publish = value._json.subscribe;
7      value._json.subscribe = publish;
8      if (!value._json.subscribe) {
9        delete value._json.subscribe;
10      }
11      if (!value._json.publish) {
12        delete value._json.publish;
13      }
14    }
15  };
16};

Example hook for changing the filename of a template file. Replaces all '-' characters with '_'.

1module.exports = {
2	'setFileTemplateName': (generator, hookArguments) => {
3		const currentFilename = hookArguments.originalFilename ;
4		return currentFilename.replace('-', '_')
5	};
6};

Official library

It is a library of reusable hooks that you can use in your templates. You only have to add its name to the configuration: @asyncapi/generator-hooks and specify which hook you want to enable.

This library consists of the following hooks:

Hook nameHook typeDescription
createAsyncapiFilegenerate:afterIt creates an AsyncAPI file with the content of the spec file passed to the generator. By default, it creates the file in the root of the generation output directory. This hook also supports custom parameters that the user can pass to template generation. The parameter called asyncapiFileDir allows the user to specify the location where the spec file should be created. To make your template users use this parameter, you need to add it to the configuration of your template like other parameters
  1. In your template configuration in package.json specify you want to use this library and what hook exactly:
    1{
    2  "generator": {
    3      "hooks": {
    4          "@asyncapi/generator-hooks": "createAsyncapiFile"
    5      }
    6  }
    7}
  2. Some hooks support custom parameters that template's user can use to specify different behaviour of the hook. To enable these, you need to also add them to the list of your template's parameters:
    1{
    2  "generator": {
    3      "parameters": {
    4        "asyncapiFileDir": {
    5            "description": "This template by default also outputs the AsyncAPI document that was passed as input. You can specify with this parameter what should be the location of this AsyncAPI document, relative to specified template output."
    6        }
    7    }
    8  }
    9}
Was this helpful?
Help us improve the docs by adding your contribution.
OR
Github:AsyncAPICreate Issue on GitHub