Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

moleculer-web

Package Overview
Dependencies
Maintainers
1
Versions
67
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

moleculer-web

Official API Gateway service for Moleculer framework

  • 0.2.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
14K
decreased by-8.09%
Maintainers
1
Weekly downloads
 
Created
Source

Moleculer logo

Build Status Coverage Status Codacy Badge Code Climate David Known Vulnerabilities Join the chat at https://gitter.im/ice-services/moleculer

Official API Gateway for Moleculer framework NPM version

The moleculer-web is the official API gateway service for Moleculer. Use it to publish your services.

Features

  • support HTTP & HTTPS
  • serve static files
  • multiple routes
  • alias names
  • whitelist
  • multiple body parsers (json, urlencoded)
  • Buffer & Stream handling
  • support authorization

Install

npm install moleculer-web --save

Usage

Run with default settings

This example uses API Gateway service with default settings. You can access to all services (including internal $node.) via http://localhost:3000/

let { ServiceBroker } = require("moleculer");
let ApiService = require("moleculer-web");

// Create broker
let broker = new ServiceBroker();

// Load your services
broker.loadService(...);

// Load API Gateway
broker.createService(ApiService);

// Start server
broker.start();

Example URLs:

  • Call test.hello action: http://localhost:3000/test/hello

  • Call math.add action with params: http://localhost:3000/math/add?a=25&b=13

  • Get health info of node: http://localhost:3000/~node/health

  • List all actions: http://localhost:3000/~node/actions

Whitelist

If you don't want to public all actions, you can filter them with a whitelist. You can use match strings or regexp.

broker.createService(ApiService, {
    settings: {
        routes: [{
            path: "/api",

            whitelist: [
                // Access to any actions in 'posts' service
                "posts.*",
                // Access to call only the `users.list` action
                "users.list",
                // Access to any actions in 'math' service
                /^math\.\w+$/
            ]
        }]
    }
});

Aliases

You can use alias names instead of action names.

broker.createService(ApiService, {
    settings: {
        routes: [{
            aliases: {
                // Call `auth.login` action with `GET /login` or `POST /login`
                "login": "auth.login"

                // Restrict the request method
                "POST users": "users.create",
            }
        }]
    }
});

With this you can create RESTful APIs.

broker.createService(ApiService, {
    settings: {
        routes: [{
            aliases: {
                "GET users": "users.list",
                "POST users": "users.create",
                "PUT users": "users.update",
                "DELETE users": "users.remove",
            }
        }]
    }
});

Serve static files

Serve assets files with the serve-static module like ExpressJS.

broker.createService(ApiService, {
    settings: {
        assets: {
            // Root folder of assets
            folder: "./assets",

            // Further options to `server-static` module
            options: {}
        }		
    }
});

Multiple routes

You can create multiple routes with different prefix, whitelist, alias & authorization

broker.createService(ApiService, {
    settings: {
        routes: [
            {
                path: "/admin",

                authorization: true,

                whitelist: [
                    "$node.*",
                    "users.*",
                ]
            },
            {
                path: "/",

                whitelist: [
                    "posts.*",
                    "math.*",
                ]
            }
        ]
    }
});

Authorization

You can implement your authorization method to Moleculer Web. For this you have to do 2 things.

  1. Set authorization: true in your routes
  2. Define the authorize method.

You can find a more detailed role-based JWT authorization example in full example

Example authorization

broker.createService(ApiService, {
    settings: {
        routes: [{
            // First thing
            authorization: true,
        }]
    },

    methods: {
        /**
         * Second thing
         * 
         * Authorize the user from request
         * 
         * @param {Context} ctx 
         * @param {IncomingMessage} req 
         * @param {ServerResponse} res 
         * @returns {Promise}
         */
        authorize(ctx, req, res) {
            // Read the token from header
            let auth = req.headers["authorization"];
            if (auth && auth.startsWith("Bearer")) {
                let token = auth.split(" ")[1];

                // Check the token
                if (token == "123456") {
                    // Set the authorized user entity to `ctx.meta`
                    ctx.meta.user = { id: 1, name: "John Doe" };
                    return Promise.resolve(ctx);

                } else {
                    // Invalid token
                    return Promise.reject(new CustomError("Unauthorized! Invalid token", 401));
                }

            } else {
                // No token
                return Promise.reject(new CustomError("Unauthorized! Missing token", 401));
            }
        }

    }
}

Service settings

List of all settings of Moleculer Web servie

settings: {

    // Exposed port
    port: 3000,

    // Exposed IP
    ip: "0.0.0.0",

    // HTTPS server with certificate
    https: {
        key: fs.readFileSync("ssl/key.pem"),
        cert: fs.readFileSync("ssl/cert.pem")
    },

    // Exposed path prefix
    path: "/api",

    // Routes
    routes: [
        {
            // Path prefix to this route  (full path: /api/admin )
            path: "/admin",

            // Whitelist of actions (array of string mask or regex)
            whitelist: [
                "users.get",
                "$node.*"
            ],

            // It will call the `this.authorize` method before call the action
            authorization: true,

            // Action aliases
            aliases: {
                "POST users": "users.create",
                "health": "$node.health"
            },

            // Use bodyparser module
            bodyParsers: {
                json: true,
                urlencoded: { extended: true }
            }
        },
        {
            // Path prefix to this route  (full path: /api )
            path: "",

            // Whitelist of actions (array of string mask or regex)
            whitelist: [
                "posts.*",
                "file.*",
                /^math\.\w+$/
            ],

            // No need authorization
            authorization: false,
            
            // Action aliases
            aliases: {
                "add": "math.add",
                "GET sub": "math.sub",
                "POST divide": "math.div",
            },
            
            // Use bodyparser module
            bodyParsers: {
                json: false,
                urlencoded: { extended: true }
            }
        }
    ],

    // Folder to server assets (static files)
    assets: {

        // Root folder of assets
        folder: "./examples/www/assets",
        
        // Options to `server-static` module
        options: {}
    }
}

Examples

  • Simple

    • simple gateway with default settings.
  • SSL server

    • open HTTPS server
    • whitelist handling
  • WWW with assets

    • serve static files from the assets folder
    • whitelist
    • aliases
    • multiple body-parsers
  • Authorization

    • simple authorization demo
    • set the authorized user to Context.meta
  • Full

    • SSL
    • static files
    • multiple routes with different roles
    • role-based authorization with JWT
    • whitelist
    • aliases
    • multiple body-parsers
    • metrics, statistics & validation from Moleculer

Test

$ npm test

In development with watching

$ npm run ci

Contribution

Please send pull requests improving the usage and fixing bugs, improving documentation and providing better examples, or providing some testing, because these things are important.

License

Moleculer-web is available under the MIT license.

Contact

Copyright (c) 2017 Ice-Services

@ice-services @MoleculerJS

Keywords

FAQs

Package last updated on 15 May 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc