Skip to content

Instantly share code, notes, and snippets.

@kevyworks
Last active December 18, 2018 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevyworks/9f385e78ce42877554ddc7b04276622a to your computer and use it in GitHub Desktop.
Save kevyworks/9f385e78ce42877554ddc7b04276622a to your computer and use it in GitHub Desktop.
MoleculerJS "$repl" Middleware
"use strict";
let { ServiceBroker } = require("moleculer");
let ApiService = require("moleculer-web");
let broker = new ServiceBroker({
transporter: "TCP",
middlewares: [
require("./ReplMiddleware")
]
});
broker.createService({
name: "api",
mixins: [
ApiService
],
settings: {
etag: true,
routes: [{
path: "/api",
mappingPolicy: "restrict",
autoAliases: true,
bodyParsers: {
json: false,
urlencoded: false
}
}]
}
});
broker.createService({
name: "greeting",
version: 1,
settings: {
rest: true
},
actions: {
hello: {
rest: true,
handler(ctx) {
if (ctx.meta.$repl) {
return "HELLO FROM REPL!";
} else {
ctx.meta.$responseType = "text/html";
return "<p><b>HELLO FROM WEB!</b></p>";
}
}
}
}
});
broker.start().then(() => broker.repl());
// PORT=8080 node index.js
"use strict";
const _ = require("lodash");
module.exports = {
call(next) {
return function(actionName, params, opts = {}) {
if (!opts.meta) {
opts.meta = {};
}
if (opts.parentCtx) {
const service = opts.parentCtx.service;
opts.meta.$repl = opts.parentCtx.meta.$repl = _.isUndefined(service.server);
} else {
opts.meta.$repl = true;
}
return next(actionName, params, opts);
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment