Skip to content

This template generates a server using your AsyncAPI document. It supports multiple different protocols, like Kafka or MQTT. It is designed in the way that generated code is a library and with it's API you can start the server, send messages or register a middleware for listening incoming messages. Runtime message validation included.

Notifications You must be signed in to change notification settings

asyncapi/nodejs-template

Repository files navigation

AsyncAPI logo

npm npm

Overview

This template generates a Node.js application with any of the supported protocols endpoint, based on Hermesjs.

Other files are for the setup of developer environment, like .editorconfig or .eslint.

Technical requirements

Specification requirements

Property name Reason Fallback Default
operationId Operation ID must be set for every operation to generate proper functions as there is no fallback in place - -

Supported protocols

How to use the template

This template must be used with the AsyncAPI Generator. You can find all available options here.

In case you use X509 security and need to provide certificates, either place them in the root of the generated server with the following names: ca.pem, service.cert, service.key. You can provide a custom directory where cert files are located using certFilesDir parameter like -p certFilesDir=../not/in/my/app/dir.

Since you can have multiple different security schemes, to use the one of X509 type, you need to pass the name of the scheme like this: -p securityScheme=SCHEME_NAME.

You can find a complete tutorial on AsyncAPI Generator using this template here.

CLI

# Install the AsyncAPI CLI
# Follow https://www.asyncapi.com/docs/tools/generator/installation-guide for more installation options
$ npm install -g @asyncapi/cli

# Run generation from the root of the template to use tes MQTT example
# To use the template
$ asyncapi generate fromTemplate test/mocks/mqtt/asyncapi-v3.yml @asyncapi/nodejs-template -o test/output -p server=production

# OR

# To test your local changes provided inside template
$ asyncapi generate fromTemplate test/mocks/mqtt/asyncapi-v3.yml ./ -o test/output -p server=production

##
## Install dependencies of generated library
##

# Go to the generated server
$ cd test/output

# Build generated application
$ npm i

##
## Start an example script that uses generated library
##

# Go back to root
$ cd ../..

# Start the script
# It is located in test/example/script.js
$ npm run test:example

##
## Install MQTT client locally to start simulating some traffic on the broker, to test if sample code works
##

# for testing your server you can use mqtt client. Open a new terminal and install it using:
$ npm install mqtt -g

#You should see the sent message in the logs of the started example.

#publish a valid message
$ mqtt pub -t 'smartylighting/streetlights/1/0/event/123/lighting/measured' -h 'test.mosquitto.org' -m '{"id": 1, "lumens": 3, "sentAt": "2017-06-07T12:34:32.000Z"}'

#you can also restart the example app that on startup produces some messages as well. Before you do it, subscribe with MQTT client to selected topic, to see actuall messages comming in from the broker
$ mqtt sub -t 'smartylighting/streetlights/1/0/action/1/turn/on' -h 'test.mosquitto.org'

Adding custom code / handlers

It's highly recommended to treat the generated template as a library or API for initializing the server and integrating user-written handlers. Instead of directly modifying the template, leveraging it in this manner ensures that its regenerative capability is preserved. Any modifications made directly to the template would be overwritten upon regeneration.

Consider a scenario where you intend to introduce a new channel or section to the AsyncAPI file, followed by a template regeneration. In this case, any modifications applied within the generated code would be overwritten.

To avoid this, user code remains external to the generated code, functioning as an independent entity that consumes the generated code as a library. By adopting this approach, the user code remains unaffected during template regenerations.

Facilitating this separation involves creating handlers and associating them with their respective routes. These handlers can then be seamlessly integrated into the template's workflow by importing the appropriate methods to register the handlers. In doing so, the template's client.register<operationId>Middleware method becomes the bridge between the user-written handlers and the generated code. This can be used to register middlewares for specific methods on specific channels.

Look closely into example script that works with library generated using this MQTT based AsyncAPI document. Look at available handlers API for reading incomming messages and processing outgoing messages. Learn how to start generated server with init() and also learn how to send messages, if needed.

Template configuration

You can configure this template by passing different parameters in the Generator CLI: -p PARAM1_NAME=PARAM1_VALUE -p PARAM2_NAME=PARAM2_VALUE

Name Description Required Example
server The server you want to use in the code. Yes production
securityScheme Name of the security scheme. Only scheme with X509 and Kafka protocol is supported for now. No 'mySchemeName'
certFilesDir Directory where application certificates are located. This parameter is needed when you use X509 security scheme and your cert files are not located in the root of your application. No ../not/in/my/app/dir

Development

The most straightforward command to use this template is:

$ ag https://bit.ly/asyncapi @asyncapi/nodejs-template -o output -p server=production

Setup locally

# Run following commands in terminal:
$ git clone https://github.com/{username}/nodejs-template
$ cd nodejs-template
$ npm install
$ ag https://bit.ly/asyncapi ./ -o output -p server=production

For local development, you need different variations of this command. First of all, you need to know about three important CLI flags:

  • --debug enables the debug mode in React rendering engine what makes filters debugging simpler.
  • --watch-template enables a watcher of changes that you make in the template. It regenerates your template whenever it detects a change.
  • --install enforces reinstallation of the template.

There are two ways you can work on template development:

  • Use global Generator and template from your local sources:
    # assumption is that you run this command from the root of your template
    $ ag https://bit.ly/asyncapi ./ -o output -p server=production
  • Use Generator from sources and template also from local sources. This approach enables more debugging options with awesome console.log in the Generator sources or even the Parser located in node_modules of the Generator:
    # assumption is that you run this command from the root of your template
    # assumption is that generator sources are cloned on the same level as the template
    $ ../generator/cli.js https://bit.ly/asyncapi ./ -o output -p server=production

Contributors

Thanks goes to these wonderful people (emoji key):

Fran Méndez
Fran Méndez

💻 🤔
Lukasz Gornicki
Lukasz Gornicki

🚇 💻
Khuda Dad Nomani
Khuda Dad Nomani

📖 💻
Samriddhi
Samriddhi

💻 📖
Julius Jann
Julius Jann

💻 ⚠️
Rishi
Rishi

💻 📖 ⚠️

This project follows the all-contributors specification. Contributions of any kind welcome!

About

This template generates a server using your AsyncAPI document. It supports multiple different protocols, like Kafka or MQTT. It is designed in the way that generated code is a library and with it's API you can start the server, send messages or register a middleware for listening incoming messages. Runtime message validation included.

Topics

Resources

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published