Skip to content

Commit

Permalink
added possibility for multiple REST interfaces on each action
Browse files Browse the repository at this point in the history
  • Loading branch information
mariusbackes committed Nov 23, 2020
1 parent 03847a6 commit ab2bb78
Show file tree
Hide file tree
Showing 4 changed files with 108 additions and 37 deletions.
76 changes: 49 additions & 27 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1385,41 +1385,33 @@ module.exports = {

_.forIn(service.actions, action => {
if (action.rest) {
let alias = null;

// Check visibility
if (action.visibility != null && action.visibility != "published") return;

// Check whitelist
if (route.hasWhitelist && !this.checkWhitelist(route, action.name)) return;

if (_.isString(action.rest)) {
if (action.rest.indexOf(" ") !== -1) {
// Handle route: "POST /import"
const p = action.rest.split(/\s+/);
alias = {
method: p[0],
path: basePath + p[1]
};
} else {
// Handle route: "/import". In this case apply to all methods as "* /import"
alias = {
method: "*",
path: basePath + action.rest
};
}
} else if (_.isObject(action.rest)) {
// Handle route: { method: "POST", path: "/other", basePath: "newBasePath" }
alias = Object.assign({}, action.rest, {
method: action.rest.method || "*",
path: (action.rest.basePath ? action.rest.basePath : basePath) + (action.rest.path ? action.rest.path : action.rawName)
});
let restRoutes = [];
if (!_.isArray(action.rest)) {
restRoutes = [action.rest];
} else {
restRoutes = action.rest;
}

if (alias) {
alias.path = removeTrailingSlashes(normalizePath(alias.path));
alias._generated = true;
this.aliases.push(this.createAlias(route, alias, action.name));
for (let restRoute of restRoutes) {
let alias = null;

if (_.isString(restRoute)) {
alias = this.parseActionRestString(restRoute, basePath);
} else if (_.isObject(restRoute)) {
alias = this.parseActionRestObject(restRoute, action.rawName, basePath);
}

if (alias) {
alias.path = removeTrailingSlashes(normalizePath(alias.path));
alias._generated = true;
this.aliases.push(this.createAlias(route, alias, action.name));
}
}
}

Expand All @@ -1433,6 +1425,36 @@ module.exports = {
}
},

/**
*
*/
parseActionRestString(restRoute, basePath) {
if (restRoute.indexOf(" ") !== -1) {
// Handle route: "POST /import"
const p = restRoute.split(/\s+/);
return {
method: p[0],
path: basePath + p[1]
};
}
// Handle route: "/import". In this case apply to all methods as "* /import"
return {
method: "*",
path: basePath + restRoute
};
},

/**
*
*/
parseActionRestObject(restRoute, rawName, basePath) {
// Handle route: { method: "POST", path: "/other", basePath: "newBasePath" }
return Object.assign({}, restRoute, {
method: restRoute.method || "*",
path: (restRoute.basePath ? restRoute.basePath : basePath) + (restRoute.path ? restRoute.path : rawName)
});
},

/**
* Optimize order of alias path.
*/
Expand Down
31 changes: 30 additions & 1 deletion test/integration/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -3794,7 +3794,8 @@ describe("Test auto aliasing", () => {
"posts.*",
"test.hello",
"test.full*",
"test.base*"
"test.base*",
"test.update*"
],

autoAliases: true,
Expand Down Expand Up @@ -3961,6 +3962,19 @@ describe("Test auto aliasing", () => {
expect(res.body).toBe("Full path");
});
});

it("should call PUT /update and PATCH /update", () => {
return Promise.all([
request(server).put("/api/update").query({ name: "John" }),
request(server).patch("/api/update").query({ name: "John" })
]).then((results) => {
results.forEach(result => {
expect(result.statusCode).toBe(200);
expect(result.headers["content-type"]).toBe("application/json; charset=utf-8");
expect(result.body).toBe("Hello John");
});
})
});
});

describe("Test ETag cache control", () => {
Expand Down Expand Up @@ -4549,4 +4563,19 @@ describe("Test multi REST interfaces in service settings", () => {
expect(res.body).toBe("Hello Custom Moleculer Root Path");
});
});

it("should call multiple PUT /update and PATCH /update on /route and /route/multi base path ", () => {
return Promise.all([
request(server).put("/route/update").query({ name: "John" }),
request(server).put("/route/multi/update").query({ name: "John" }),
request(server).patch("/route/update").query({ name: "John" }),
request(server).patch("/route/multi/update").query({ name: "John" })
]).then((results) => {
results.forEach(result => {
expect(result.statusCode).toBe(200);
expect(result.headers["content-type"]).toBe("application/json; charset=utf-8");
expect(result.body).toBe("Hello John");
});
})
});
});
10 changes: 10 additions & 0 deletions test/services/multiRoute.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,15 @@ module.exports = {
return "Hello Custom Moleculer Root Path";
}
},

update: {
rest: ["PUT /update", "PATCH /update"],
params: {
name: "string"
},
handler(ctx) {
return `Hello ${ctx.params.name}`;
}
},
}
}
28 changes: 19 additions & 9 deletions test/services/test.service.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"use strict";

const fs = require("fs");
const path = require("path");
const fs = require("fs");
const path = require("path");

const _ = require("lodash");
const _ = require("lodash");

const { MoleculerServerError } = require("moleculer").Errors;

Expand Down Expand Up @@ -85,15 +85,15 @@ module.exports = {
}
try {
let c = 0;
while(c != ctx.params.counter) {
while (c != ctx.params.counter) {
await sleep(ctx.params.sleeptime);
c++;
}
return {
status: 200,
msg: "apitimeout response"
};
} catch(e) {
} catch (e) {
return {
status: 500,
msg: "apitimeout response",
Expand Down Expand Up @@ -178,10 +178,10 @@ module.exports = {
},

function(ctx) {
return () => {};
return () => { };
},

nothing(ctx) {},
nothing(ctx) { },

null(ctx) {
return null;
Expand Down Expand Up @@ -259,14 +259,14 @@ module.exports = {
return stream;
},

freshness(ctx){
freshness(ctx) {
ctx.meta.$responseHeaders = {
"Last-Modified": "Mon, 06 Aug 2018 14:23:28 GMT"
};
return "fresh";
},

etag(ctx){
etag(ctx) {
ctx.meta.$responseHeaders = {
"ETag": "my custom etag"
};
Expand All @@ -285,5 +285,15 @@ module.exports = {

throw new MoleculerServerError("It is a wrong action! I always throw error!");
},

update: {
rest: ["PUT /update", "PATCH /update"],
params: {
name: "string"
},
handler(ctx) {
return `Hello ${ctx.params.name}`;
}
},
}
};

0 comments on commit ab2bb78

Please sign in to comment.