Last active
December 18, 2018 07:25
-
-
Save kevyworks/9f385e78ce42877554ddc7b04276622a to your computer and use it in GitHub Desktop.
MoleculerJS "$repl" Middleware
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
"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 |
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
"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