This repo shows you how to create OpenAPI Object (Swagger spec) with using a $ref references to external definitions and launch Swagger UI with Swagger UI Express.
Check the index.js file and copy and reuse multiFileSwagger function in your code.
If you want to launch the example - please, do next steps:
yarn install
- install dependenciesyarn run start
- run server (be sure that port 9000 is not busy on you local machine or change it :))- http://localhost:9000/api/doc/ - open link in browser
Q: I'm trying split my OpenAPI Object over multiple YAML files, but I get the erorr:
Resolver error. Could not resolve reference: Tried to resolve a relative URL, without having a basePath.
A: You have to resolve references in your YAML files first, and provide result to Swagger UI then. You can do it with json-refs and yamljs libraries.
Here is the code snippet below shows you how you can do it:
/**
* 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"))
);
};
If you want to know more about how it works, check the documenation of resolveRefs function.
MIT