npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@spailybot/moleculer-auto-openapi

v1.3.1

Published

Generate openapi scheme for moleculer

Downloads

187

Readme

Moleculer logo


Why Use OpenAPI:

OpenAPI standardizes and documents RESTful APIs, streamlines development, improves team communication, and automates testing. Moreover, it can be used to generate client SDKs. It allows for a focus on business logic, making it a valuable tool in a microservices environment.

This project is a fork of moleculer-auto-openapi by grinat.

Big thanks to grinat for the original work, and also to everyone who has contributed to it!

🌟 Features

  • Supports multiple Moleculer-Web servers, allowing API separation
  • Fastest-Validator support for direct OpenAPI generation from parameters, complete with examples
  • OpenAPI 3.1 compatibility
  • Cached OpenAPI with efficient regeneration when needed
  • Granular and reusable configuration
  • TypeScript exports of mixin settings and OpenAPI parameters
  • Get your first openapi in less a minute

🚀 Getting Started

📦 Prerequisites

To use this library, you must have the Moleculer framework installed along with the Moleculer-Web module. Additionally, the listAliases action must be available (which is the default setting).

🔧 Installation

Install the package using your preferred package manager:

npm install @spailybot/moleculer-auto-openapi

Optional

If you wish to use a local instance of Swagger UI, install it like this:

npm install swagger-ui-dist@^5

For the full TypeScript autocompletion experience, install the openapi-types package in addition to the above:

npm install --save-dev openapi-types

📁 Setting Up Your Service

Note: The following examples use the ESM syntax.

Depending on your environment and requirements, you may need to adapt these examples, possibly to the CommonJS (CJS) syntax, or to your specific coding standard.

Create an OpenApi service

import { OpenApiMixin, type OpenApiMixinSettings, type MoleculerWebTypes } from '@spailybot/moleculer-auto-openapi';
import { Service, type ServiceBroker } from 'moleculer';

/**
 * MoleculerWebTypes are typings created from moleculer-web to enhance included typings; their use is totally optional.
 */

export default class OpenApiService extends Service<OpenApiMixinSettings & MoleculerWebTypes.RestServiceSettings> {
    public constructor(public broker: ServiceBroker) {
        super(broker);

        this.parseServiceSchema({
            // Choose your preferred name
            name: 'openapi',
            mixins: [mixin],
            settings: {
                // Set the path as you prefer
                rest: '/openapi',
                // Path to the endpoint that returns the JSON
                // With autoalias, it's exposed on /openapi.json
                schemaPath: '/openapi/openapi.json',
                // This will be the root of your document
                // use it to define some default informations
                openapi: {
                    info: {
                        title: "My API",
                        version: "0.0.1"
                    }
                }
            }
        });
    }
}
import { OpenApiMixin, type OpenApiMixinSettings, type MoleculerWebTypes } from '@spailybot/moleculer-auto-openapi';
import { Service, type ServiceBroker } from 'moleculer';

const OpenApiService: ServiceSchema<OpenApiMixinSettings & MoleculerWebTypes.RestServiceSettings> = {
    // Choose your preferred name
    name: 'openapi',
    mixins: [mixin],
    settings: {
        // Set the path as you prefer
        rest: '/openapi',
        // Path to the endpoint that returns the JSON
        // With autoalias, it's exposed on /openapi.json
        schemaPath: '/openapi/openapi.json',
        // This will be the root of your document
        // use it to define some default informations
        openapi: {
          info: {
            title: "My API",
            version: "0.0.1"
          }
        }
    }
};
export default OpenApiService;
import { OpenApiMixin } from '@spailybot/moleculer-auto-openapi';
import { Service } from 'moleculer';

export default class OpenApiService extends Service {
    public constructor(broker) {
        super(broker);

        this.parseServiceSchema({
            // Choose your preferred name
            name: 'openapi',
            mixins: [OpenApiMixin],
            settings: {
                // Set the path as you prefer
                rest: '/openapi',
                // Path to the endpoint that returns the JSON
                // With autoalias, it's exposed on /openapi.json
                schemaPath: '/openapi/openapi.json',
                // This will be the root of your document
                // use it to define some default informations
                openapi: {
                    info: {
                        title: "My API",
                        version: "0.0.1"
                    }
                }
            }
        });
    }
}
import { OpenApiMixin } from '@spailybot/moleculer-auto-openapi';
import { Service } from 'moleculer';

const OpenApiService = {
  // Choose your preferred name
  name: 'openapi',
  mixins: [mixin],
  settings: {
    // Set the path as you prefer
    rest: '/openapi',
    // Path to the endpoint that returns the JSON
    // With autoalias, it's exposed on /openapi.json
    schemaPath: '/openapi/openapi.json',
    // This will be the root of your document
    // use it to define some default informations
    openapi: {
      info: {
        title: "My API",
        version: "0.0.1"
      }
    }
  }
};
export default OpenApiService;
const OpenApiMixin = require('@spailybot/moleculer-auto-openapi');
// or
// const { OpenApiMixin } = require('@spailybot/moleculer-auto-openapi');
import { Service } from 'moleculer';

module.exports = {
   // Choose your preferred name
   name: 'openapi',
   mixins: [mixin],
   settings: {
       // Set the path as you prefer
       rest: '/openapi',
       // Path to the endpoint that returns the JSON
       // With autoalias, it's exposed on /openapi.json
       schemaPath: '/openapi/openapi.json',
       // This will be the root of your document
       // use it to define some default informations
       openapi: {
         info: {
           title: "My API",
           version: "0.0.1"
         }
       }
   }
};

You can find detailed information about all the settings of the mixin in the technical documentation.

Update your moleculer-web service

import type { ApiSettingsSchemaOpenApi } from '@spailybot/moleculer-auto-openapi';
import ApiGateway from "moleculer-web";
import { Service, type ServiceBroker } from 'moleculer';

/**
 * Note that ApiSettingsSchemaOpenApi is a re-export of ApiSettingsSchema because moleculer-web doesn't allow to extend it.
 */

export default class WebApiService extends Service<ApiSettingsSchemaOpenApi> {
    public constructor(public broker: ServiceBroker) {
        super(broker);

        this.parseServiceSchema({
            name: "api",
            mixins: [mixin],
            settings: {
                // Place other settings here
                openapi: {
                    // Define an OpenAPI specification that will be applied to all routes of this api
                },
                routes: [
                    // Place additional route configurations here
                    {
                        openapi: {
                            // Define an OpenAPI specification that will apply to all aliases within this route
                        },
                        path: '/openapi',
                        aliases: {
                            'GET /openapi.json': 'openapi.generateDocs',
                            'GET /ui': 'openapi.ui',
                            'GET /assets/:file': 'openapi.assets',
                            'GET /oauth2-redirect': 'openapi.oauth2Redirect',
                        },
                    },
                    // To use autoAliases, refer to the following configuration
                    // {
                    //     path: '/openapi',
                    //     whitelist: ['openapi.*'],
                    //     autoAliases: true
                    // }

                ]
                // Insert other settings here
            }
        });
    }
}
import ApiGateway from "moleculer-web";
import { Service } from 'moleculer';

export default class WebApiService extends Service {
    public constructor(broker) {
        super(broker);

        this.parseServiceSchema({
            name: "api",
            mixins: [mixin],
            settings: {
                // Place other settings here
                openapi: {
                    // Define an OpenAPI specification that will be applied to all routes of this api
                },
                routes: [
                    // Place additional route configurations here
                    {
                        openapi: {
                            // Define an OpenAPI specification that will apply to all aliases within this route
                        },
                        path: '/openapi',
                        aliases: {
                            'GET /openapi.json': 'openapi.generateDocs',
                            'GET /ui': 'openapi.ui',
                            'GET /assets/:file': 'openapi.assets',
                            'GET /oauth2-redirect': 'openapi.oauth2Redirect',
                        },
                    },
                    // To use autoAliases, refer to the following configuration
                    // {
                    //     path: '/openapi',
                    //     whitelist: ['openapi.*'],
                    //     autoAliases: true
                    // }

                ]
                // Insert other settings here
            }
        });
    }
}

Launch Your Project

Your setup is now complete.

To view your API documentation via Swagger UI, you can navigate to http://127.0.0.1/openapi/ui in your web browser (adjust the URL according to your configuration).

What's Next?

With your project now up and running, there are several resources available to help you develop further:

  1. Examples: Check out the examples in the examples folder. These provide practical code snippets and usage scenarios that can help you understand how to leverage this tool in various situations.
  2. Wiki: Visit our Wiki for a comprehensive guide on different features, advanced topics, and best practices.
  3. FAQs: The Frequently Asked Questions section can provide quick answers to common queries and issues others have encountered.

Remember, the journey of mastering any tool involves experimentation, learning from examples, reading documentation, and continuous practice. Happy coding!

📝 TODO

  • $$oa
    • allow to define a ref, and use the ref instead of creating a new one
    • allow to define a "to ref", and create the ref with this name
    • allow to define examples
  • investigate the needs of requestBodyAndResponseBodyAreSameOnMethods / requestBodyAndResponseBodyAreSameDescription
  • support multiple openapi version on generator ? (will need converters)

📄 License

This project is protected under the MIT License. For more details, refer to the LICENSE file.