【问题标题】:How to use $ref in swagger file properly while working with swagger-ui-express and swagger-jsdoc使用 swagger-ui-express 和 swagger-jsdoc 时如何在 swagger 文件中正确使用 $ref
【发布时间】:2018-12-29 10:37:51
【问题描述】:

我开始使用 swagger 和 swagger-ui-expressswagger-jsdoc 来自动记录我现有的 API,它是用 nodejs编写的> 并表达(如此处所述 - example)。

当我尝试将 $ref 添加到注释上的现有 JSON 架构 文件(与我的所有 js 文件位于我的项目中的同一目录中)时遇到了一个问题。

My directory looks like this

我尝试写本地路径(./schema.json)和绝对路径,尝试使用#,使用了很多语法但没有任何效果。

我的注释是这样的:

/**
 * @swagger
 * /testing:
 *    get:
 *      description: This should show the json schema
 *      responses:
 *          200:
 *              description: "successful operation"
 *              schema:
 *                 $ref: "./schema.json"
 */

我希望 swagger ui 在我的请求部分中向我显示 JSON 模式。我收到以下错误 -

Resolver error at paths./testing.get.responses.200.schema.$ref
Could not resolve reference: Tried to resolve a relative URL, without having a basePath. path: './schema.json' basePath: 'undefined'.

我在网上查了这个问题,找不到任何明确的答案。我看到了一个解决方案,建议我应该将架构放在服务器上并使用 URL 地址访问它,但我不想在这一点上这样做。

另外,在某个时候,我将方案保存在一个变量中,然后将其放入 $ref 中,它运行良好。唯一的问题是该方案在同一文件中包含了一些对元素的内部引用,而 Swagger 无法解决它们。

有没有办法在 swagger-ui-express 中使用 $ref 正常工作?

【问题讨论】:

标签: node.js json express swagger ref


【解决方案1】:

有没有办法在 swagger-ui-express 中使用 $ref 正常工作?

是的,您必须先自行解析 YAML 文件中的引用,然后将结果提供给 Swagger UI。您可以使用 json-refsyamljs 库来做到这一点。

下面的代码 sn-p 向您展示了如何做到这一点:

const yamljs = require('yamljs');
const { resolveRefs } = require('json-refs');

/**
 * Return JSON with resolved references
 * @param {array | object} root - The structure to find JSON References within (Swagger spec)
 * @returns {Promise.<JSON>}
 */
const multiFileSwagger = (root) => {
  const options = {
    filter: ["relative", "remote"],
    loaderOptions: {
      processContent: function (res, callback) {
        callback(null, yamljs.parse(res.text));
      },
    },
  };

  return resolveRefs(root, options).then(
    function (results) {
      return results.resolved;
    },
    function (err) {
      console.log(err.stack);
    }
  );
};


const swaggerDocument = await multiFileSwagger(
  yamljs.load(path.resolve(__dirname, "./openapi/v1.yaml"))
);

您还可以通过完整示例检查 repo,该解决方案如何与 swagger-ui-express 一起使用:https://github.com/chuve/swagger-multi-file-spec

【讨论】:

【解决方案2】:

在这里遇到同样的问题并找到您的问题。

我刚刚解决了我的问题,所以我想我可能会有所帮助。

首先,你试过了吗:

schema:
      $ref: "schema.json"

没有. 这是他们在文档中的教学方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-24
    • 2022-06-14
    • 1970-01-01
    • 2022-06-10
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多