diff --git a/src/converter.js b/src/converter.js index da0aad7..c7a8607 100644 --- a/src/converter.js +++ b/src/converter.js @@ -38,6 +38,8 @@ const { } = require('./utils') const { BOUNDARY, BASE64_PATTERN } = require('./common') +const REGEX_EXTRACT_VARS = /{([^{}]*?)}/g + /** * Create HAR Request object for path and method pair described in given swagger. * @@ -154,7 +156,37 @@ const getPayload = (swagger, path, method) => { * @returns {string[]} */ const parseUrls = (swagger) => { - if (!Array.isArray(swagger.servers)) { + if (Array.isArray(swagger.servers) && swagger.servers.length) { + return swagger.servers.map((server) => { + const variables = server.variables || {} + + let urlString = removeTrailingSlash(server.url) + let substitutions = 0 + let replacements = 0 + + do { + urlString = urlString.replace(REGEX_EXTRACT_VARS, (match, token) => { + replacements += 1 + + const variable = variables[token] + + if (!variable || !variable.default) { + return match + } + + return variable.default + }) + + if (replacements) { + substitutions += 1 + } + } while (replacements && substitutions < 30) + + return urlString + }) + } + + if (swagger.host) { const basePath = typeof swagger.basePath !== 'undefined' ? removeLeadingSlash(swagger.basePath) : '' const host = removeTrailingSlash(swagger.host) @@ -162,7 +194,7 @@ const parseUrls = (swagger) => { return schemes.map((x) => x + '://' + removeTrailingSlash(host + '/' + basePath)) } - return swagger.servers.map((server) => removeTrailingSlash(server.url)) + return [] } /** @@ -174,6 +206,10 @@ const parseUrls = (swagger) => { const getBaseUrl = (swagger) => { const urls = parseUrls(swagger) + if (!Array.isArray(urls) || !urls.length) { + throw new Error('None server or host is defined.') + } + let preferredUrls = urls.filter((x) => x.startsWith('https') || x.startsWith('wss')) if (!preferredUrls.length) {