首页 > 解决方案 > Node.js | 将端点转换为通用路径以在 YAML 文件中匹配

问题描述

我正在开发一个模拟服务器,它将使用 Swagger-Parser 包来处理传入的请求并返回响应,其详细信息在 YAML 文件中指定。例如,如果服务器收到一个请求api/locations/assign,我将在 YAML 文件中查找确切api_path的内容,如果找到,我将进一步解析它以检查标头和请求正文。

getInfoFromUrl(req) {
    var paths = req['url'].split('/');
    return {
        host: req.get('host'),
        organization: paths[2],
        product: paths[3],
        api_path: `/${paths[4]}/${paths[5]}`,
        method: req.method.toLowerCase()
    };
},

// gets data related to the path from yaml file
// returns 404 Not Found when provided path does not exist in .yaml
getPathData(res, api, url) {
    var pathData = api['paths'][url.api_path][url.method]; // get all possible responses for that path

    if (pathData == null) {
        res.status(404)
            .send(`The path ${url.method.toUpperCase()} ${url.api_path} does not exist`);
    }

    return pathData;
}

当涉及到路径参数时,问题就出现了。例如,YAML 包含路径 GET api/locations/{location-id}。但是,我将收到的请求将是 GET api/locations/4

有没有办法知道key对应的(路径参数的名称)value?这样当我收到时api/locations/4,我可以将其转换为api/locations/{location-id}并在 YAML 文件中查找它?或者,如果您认为我可以采取任何其他方法,请随时告诉我!

标签: javascriptnode.jsexpressyamlswagger

解决方案


推荐阅读