[英]How to use $ref in swagger file properly while working with swagger-ui-express and swagger-jsdoc
我开始使用 swagger 和swagger-ui-express和swagger-jsdoc来自动记录我现有的 API,它是用nodejs和 express 编写的(就像这里描述的一样 - 示例)。
当我尝试将$ref
添加到我的注释上的现有JSON Schema文件(与我的所有 js 文件位于我的项目中的同一目录中)时,我遇到了一个问题。
我尝试编写本地路径( ./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
正常工作?
有没有办法在 swagger-ui-express 中使用 $ref 正常工作?
是的,有,您必须首先自己解析 YAML 文件中的引用,然后将结果提供给 Swagger UI。 您可以使用json-refs和yamljs库来实现。
下面的代码片段向您展示了如何做到这一点:
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"))
);
您还可以使用完整示例检查该解决方案如何与 swagger-ui-express 一起使用的存储库: https : //github.com/chuve/swagger-multi-file-spec
在这里遇到同样的问题并找到您的问题。
我刚刚解决了我的问题,所以我想我可能会有所帮助。
首先,您是否尝试过:
schema:
$ref: "schema.json"
没有.
这就是他们在文档中的教学方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.