Created
November 12, 2018 13:51
-
-
Save yura415/ffff731c215569e3d3b2ab820589c74c to your computer and use it in GitHub Desktop.
moleculer client ip example. based on https://github.com/moleculerjs/moleculer-web/blob/master/examples/rest/index.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let path = require("path"); | |
let { ServiceBroker } = require("moleculer"); | |
let ApiGatewayService = require("../../index"); | |
// Create broker | |
let broker = new ServiceBroker({ | |
logger: console, | |
cacher: "memory", | |
metrics: true, | |
validation: true | |
}); | |
// Load other services | |
broker.loadService(path.join(__dirname, "..", "post.service")); | |
// Load API Gateway | |
broker.createService({ | |
mixins: ApiGatewayService, | |
settings: { | |
routes: [ | |
{ | |
// RESTful aliases | |
aliases: { | |
"REST posts": "posts" | |
/* | |
"GET posts": "posts.find", | |
"GET posts/:id": "posts.get", | |
"POST posts": "posts.create", | |
"PUT posts/:id": "posts.update", | |
"DELETE posts/:id": "posts.remove" | |
*/ | |
}, | |
// Disable direct URLs (`/posts/find` or `/posts.find`) | |
mappingPolicy: "restrict", | |
onBeforeCall(ctx, route, req, res) { | |
ctx.meta.clientIp = | |
req.headers["x-forwarded-for"] || | |
req.connection.remoteAddress || | |
req.socket.remoteAddress || | |
req.connection.socket.remoteAddress; | |
console.log("client ip", ctx.meta.clientIp); | |
} | |
} | |
] | |
} | |
}); | |
// Start server | |
broker.start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment