From 71f3b5b1e270ea46fb6dd24e59185d581041d3b5 Mon Sep 17 00:00:00 2001 From: Artem Derevnjuk Date: Fri, 10 Jul 2020 18:37:44 +0300 Subject: [PATCH] fix(converter): add support of the server's URL template (#39) closes #37 and closes #36 --- src/converter.js | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) 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) {