diff --git a/src/alias.js b/src/alias.js index 932d3935..b5b07d85 100644 --- a/src/alias.js +++ b/src/alias.js @@ -12,7 +12,7 @@ const kleur = require("kleur"); const _ = require("lodash"); const { PayloadTooLarge } = require("./errors"); -const { MoleculerClientError } = require("moleculer").Errors; +const { MoleculerClientError, MoleculerError } = require("moleculer").Errors; const { removeTrailingSlashes, addSlashes, decodeParam, compose } = require("./utils"); class Alias { @@ -89,6 +89,25 @@ class Alias { } } + + /** + * Compiles a path using the given path parameters and returns the compiled string. + * + * @param {Object} pathParameters - The path parameters to be replaced in the path. + * @return {string} - The compiled path with replaced path parameters. + */ + compile(pathParameters) { + const missingParameters = this.keys.filter((key) => !key.optional && (!pathParameters || !pathParameters.hasOwnProperty(key.name))); + const missingParametersNames = missingParameters.map(param => param.name); + if(missingParametersNames.length > 0) { + throw new MoleculerError(`parameters are missing : ${missingParametersNames.join(", ")}`, 400, "MISSING_PARAMETERS", { + parameters: missingParametersNames + }); + } + + return pathToRegexp.compile(this.fullPath, this.route.opts.pathToRegexpOptions || {})(pathParameters, { validate: false }); + } + /** * * @param {*} url diff --git a/src/index.js b/src/index.js index ad8f0d60..a900ea45 100644 --- a/src/index.js +++ b/src/index.js @@ -279,8 +279,31 @@ module.exports = { return this.removeRoute(ctx.params.path); } }, - }, + compileRest: { + params: { + action: { + type: "string" + }, + params: { + type: "record", + optional: true, + key: { type: "string", pattern: /[A-Za-z0-9_]+/ }, + value: { type: "string", convert: true, optional: true } + } + }, + visibility: "public", + handler(ctx) { + const actionName = ctx.params.action; + const foundAlias = this.aliases.find(alias => alias.action === actionName); + + if(!foundAlias) { + return; + } + return foundAlias.compile(ctx.params.params); + } + } + }, methods: { /** * Create HTTP server