Skip to content
This repository has been archived by the owner on Dec 3, 2021. It is now read-only.

fix(converter): add support of the server's URL template #39

Merged
merged 1 commit into from
Jul 10, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 38 additions & 2 deletions src/converter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -154,15 +156,45 @@ 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)
const schemes = typeof swagger.schemes !== 'undefined' ? swagger.schemes : ['https']
return schemes.map((x) => x + '://' + removeTrailingSlash(host + '/' + basePath))
}

return swagger.servers.map((server) => removeTrailingSlash(server.url))
return []
}

/**
Expand All @@ -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) {
Expand Down