Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(compileRest): allow to reuse the rest settings, to generate rest path from parameters #336

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/alias.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
25 changes: 24 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading