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

Commit

Permalink
fix(converter): add support of the server's URL template
Browse files Browse the repository at this point in the history
closes #37
  • Loading branch information
derevnjuk committed Jul 10, 2020
1 parent 46eb0bc commit d2fe334
Showing 1 changed file with 38 additions and 2 deletions.
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

0 comments on commit d2fe334

Please sign in to comment.