diff --git a/CHANGELOG.md b/CHANGELOG.md index e0be0b4..8797d22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Master +# 2.0.6 - 27 May, 2021 +### Improvements +- Added support for relative URLs and variables in servers #59 + # 2.0.5 - 1 February, 2021 ### Improvements - Added basic support for relative URLs #59 diff --git a/src/index.js b/src/index.js index 9e55437..b54ed8a 100644 --- a/src/index.js +++ b/src/index.js @@ -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) => { + 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 }) => url.indexOf('://') > -1 ? new URL(url).pathname : url) - : [dereferenced.basePath || '/']; + const basePaths = getBasePaths(dereferenced); Object.keys(dereferenced.paths).forEach(currentPath => { const operationSchemas = {}; diff --git a/test/openapi3/general/pets-general.yaml b/test/openapi3/general/pets-general.yaml index 3337e82..75545e9 100644 --- a/test/openapi3/general/pets-general.yaml +++ b/test/openapi3/general/pets-general.yaml @@ -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 components: schemas: Error: