Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
moleculer-web
Advanced tools
The moleculer-web
is the official API gateway service for Moleculer. Use it to publish your services.
npm install moleculer-web --save
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
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+$/
]
}]
}
});
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 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: {}
}
}
});
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.*",
]
}
]
}
});
You can implement your authorization method to Moleculer Web. For this you have to do 2 things.
authorization: true
in your routesauthorize
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));
}
}
}
}
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: {}
}
}
assets
folderContext.meta
$ npm test
In development with watching
$ npm run ci
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.
Moleculer-web is available under the MIT license.
Copyright (c) 2017 Ice-Services
0.2.1 (2017-05-23)
You can use Moleculer-Web as a middleware for ExpressJS.
Usage
const svc = broker.createService(ApiGatewayService, {
settings: {
middleware: true
}
});
// Create Express application
const app = express();
// Use ApiGateway as middleware
app.use("/api", svc.express());
// Listening
app.listen(3000);
// Start server
broker.start();
Example: examples/express
<a name="0.2.0"></a>
FAQs
Official API Gateway service for Moleculer framework
The npm package moleculer-web receives a total of 11,126 weekly downloads. As such, moleculer-web popularity was classified as popular.
We found that moleculer-web demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
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.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.