From 907df27458a73d60826588d6f0b40311be04ca32 Mon Sep 17 00:00:00 2001 From: Michael Welch Date: Mon, 24 Jun 2024 14:25:22 -0500 Subject: [PATCH] do variable substitutions in server urls OpenApi allows for servers to define one or more server objects, each of which has a `url` that supports server variables. A server variable looks like a symbol in braces. For example `{hostname}`. A server object can also define `variables` which can provide values for any variables. This commit honors any variables that have been defined which produces better looking code snippets. Otherwise server variables are escaped and produce snippets that look like: ``` var client = new RestClient("https:///%7Bhostname%7D/api/v5/login"); ``` --- openapi-to-har.js | 11 +++++++++++ test/form_data_example.json | 7 ++++++- test/test.js | 15 +++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/openapi-to-har.js b/openapi-to-har.js index 2d9daf2..3cf4185 100644 --- a/openapi-to-har.js +++ b/openapi-to-har.js @@ -410,6 +410,17 @@ const getBaseUrl = function (openApi, path, method) { if (openApi.paths[path][method].servers) return openApi.paths[path][method].servers[0].url; if (openApi.paths[path].servers) return openApi.paths[path].servers[0].url; + + if (openApi.servers && openApi.servers.length > 0) { + let firstServer = openApi.servers[0]; + let url = firstServer.url; + const variables = firstServer.variables || {}; + Object.keys(variables).forEach((variable) => { + url = url.replace(`{${variable}}`, variables[variable].default); + }); + return url; + } + if (openApi.servers) return openApi.servers[0].url; let baseUrl = ''; diff --git a/test/form_data_example.json b/test/form_data_example.json index 9bc6cec..8853b0c 100644 --- a/test/form_data_example.json +++ b/test/form_data_example.json @@ -17,7 +17,12 @@ }, "servers": [ { - "url": "http://petstore.swagger.io/api" + "url": "http://{hostname}/api", + "variables": { + "hostname": { + "default": "petstore.swagger.io" + } + } } ], "paths": { diff --git a/test/test.js b/test/test.js index cd59409..444a1c0 100644 --- a/test/test.js +++ b/test/test.js @@ -219,6 +219,21 @@ test('Generate snippet with multipart/form-data', function (t) { t.end(); }); +test('If a server has url with variables those should be substituted', function (t) { + const result = OpenAPISnippets.getEndpointSnippets( + FormDataExampleReferenceAPI, + '/pets', + 'patch', + ['csharp_restsharp'] + ); + const snippet = result.snippets[0].content; + t.true( + /new RestClient\("http:\/\/petstore.swagger.io\/api\/pets"/.test(snippet) + ); + t.false(/{hostname}/.test(snippet)); + t.end(); +}); + test('Generate snippet with multipart/form-data with array', function (t) { const result = OpenAPISnippets.getEndpointSnippets( FormDataExampleReferenceAPI,