Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added fix for basic relative URLs and support variables in servers URLs #69

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Master

# 2.0.6 - 27 Mar, 2021
### Improvements
- Added support for relative URLs and variables in servers #59

# 2.0.5 - 08 Mar, 2021
### Improvements
- Update dependencies to fix security vulnerabilities
Expand Down
21 changes: 18 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,29 @@ function buildSchemaSync(pathOrSchema, options) {
return buildValidations(jsonSchema, dereferencedSchema, options);
}

function getBasePaths(dereferenced) {
return dereferenced.servers && dereferenced.servers.length
? dereferenced.servers.map(({ url, variables = {} }) => {
// replace variables with deafault values
Object.keys(variables).forEach((key) => {
udamir marked this conversation as resolved.
Show resolved Hide resolved
url = url.replace(new RegExp(`{${key}}`), variables[key].default);
});

// replace leading '//' with 'http://' (in cases such as //api.example.com)
url = url.replace(/^\/\//, 'http://');

// return base path
return (/\/\//.test(url)) ? new URL(url).pathname : url;
})
: [dereferenced.basePath || '/'];
}

function buildValidations(referenced, dereferenced, receivedOptions) {
const options = getOptions(receivedOptions);

const schemas = {};

const basePaths = dereferenced.servers && dereferenced.servers.length
? dereferenced.servers.map(({ url }) => new URL(url).pathname)
: [dereferenced.basePath || '/'];
const basePaths = getBasePaths(dereferenced);

Object.keys(dereferenced.paths).forEach(currentPath => {
const operationSchemas = {};
Expand Down
14 changes: 14 additions & 0 deletions test/openapi3/general/pets-general.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,20 @@ paths:
servers:
- url: http://petstore.swagger.io
- url: http://petstore.swagger.io/staging/
- url: /staging
- url: '{protocol}://petstore.swagger.io/{env}'
variables:
protocol:
enum:
- http
- https
default: http
env:
enum:
- staging
- ''
default: staging
- url: //petstore.swagger.io
udamir marked this conversation as resolved.
Show resolved Hide resolved
components:
schemas:
Error:
Expand Down