0

如文档中所述,路由别名可以放在API服务中,但我想将别名放在单独的服务设置中,我该怎么做?

假设我有一个用户服务和API 网关

并且用户服务有一个角色操作,它只会发回 id作为示例

如果我向我发送获取请求,/users/role/1我将得到1结果

它像这样工作

api.service.js

"use strict";

const ApiGateway = require("moleculer-web");


module.exports = {
    name: "api",
    mixins: [ApiGateway],

    settings: {
        port: process.env.PORT || 3000,
        routes: [{
            path: "/api",
            whitelist: [
                // Access to any actions in all services under "/api" URL
                "**"
            ],
            aliases: {
                "GET users/role/:uid": "users.role"
            }
        }],

        // Serve assets from "public" folder
        assets: {
            folder: "public"
        },
    },
};

users.service.js

"use strict";

module.exports = {
    name: "users",

    /**
     * Service settings
     */
    settings: {},

    /**
     * Actions
     */
    actions: {
        role: {
            cache: {
                keys: ["uid"]
            },
            rest: "GET role/:uid",
            handler(ctx) {
                return ctx.params.uid
            }
        }
    },
};

想要这样的东西

api.service.js

"use strict";

const ApiGateway = require("moleculer-web");


module.exports = {
    name: "api",
    mixins: [ApiGateway],

    settings: {
        port: process.env.PORT || 3000,
        routes: [{
            path: "/api",
            whitelist: [
                // Access to any actions in all services under "/api" URL
                "**"
            ]
        }],

        // Serve assets from "public" folder
        assets: {
            folder: "public"
        },
    },
};

users.service.js

"use strict";

module.exports = {
    name: "users",

    /**
     * Service settings
     */
    settings: {
        routes: [{
            path: "/",
            aliases: {
                "GET role/:uid": "role"
            }
        }],

    },

    /**
     * Actions
     */
    actions: {
        role: {
            cache: {
                keys: ["uid"]
            },
            rest: "GET role/:uid",
            handler(ctx) {
                return ctx.params.uid
            }
        }
    },
};

目标是每个服务都在自己的项目中分离,任何服务的别名都可以放在其中而不是 API 服务中

4

1 回答 1

1
// api.service.js
module.exports = {
    mixins: [ApiGateway],
    settings: {
        port: process.env.PORT || 3000,
        routes: [
            {
                path: "/",    
                whitelist: [
                    "users.**"
                ],   
                autoAliases: true
            }
        ]
    }
};

// users.service.js
module.exports = {
    name: "users",

    settings: {
        // Base path
        rest: "users/"
    },

    actions: {
        role: {
            cache: {
                keys: ["uid"]
            },
            rest: "GET role/:uid",
            handler(ctx) {
                return ctx.params.uid
            }
        }
    }
};
于 2020-01-10T12:31:41.480 回答