[PS][Experimental] Add multiple server support (#5741)

* code comment

* add get host setting

* add multiple server support
This commit is contained in:
William Cheng 2020-03-29 21:44:18 +08:00 committed by GitHub
parent 94152c4d35
commit 01f02f6c57
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 280 additions and 16 deletions

View File

@ -309,7 +309,7 @@ public class PowerShellExperimentalClientCodegen extends DefaultCodegen implemen
typeMapping.put("long", "Int64"); typeMapping.put("long", "Int64");
typeMapping.put("double", "Double"); typeMapping.put("double", "Double");
typeMapping.put("number", "Decimal"); typeMapping.put("number", "Decimal");
typeMapping.put("object", "System.Hashtable"); typeMapping.put("object", "System.Collections.Hashtable");
typeMapping.put("file", "System.IO.FileInfo"); typeMapping.put("file", "System.IO.FileInfo");
typeMapping.put("ByteArray", "System.Byte[]"); typeMapping.put("ByteArray", "System.Byte[]");
typeMapping.put("binary", "System.IO.FileInfo"); typeMapping.put("binary", "System.IO.FileInfo");
@ -374,8 +374,9 @@ public class PowerShellExperimentalClientCodegen extends DefaultCodegen implemen
} }
if (StringUtils.isNotBlank(powershellGalleryUrl)) { if (StringUtils.isNotBlank(powershellGalleryUrl)) {
// get the last segment of the URL
// e.g. https://www.powershellgallery.com/packages/PSTwitter => PSTwitter
additionalProperties.put("powershellGalleryId", powershellGalleryUrl.replaceFirst(".*/([^/?]+).*", "$1")); additionalProperties.put("powershellGalleryId", powershellGalleryUrl.replaceFirst(".*/([^/?]+).*", "$1"));
//additionalProperties.put("powershellGalleryId", "something");
} }
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_GUID)) { if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_GUID)) {
@ -569,7 +570,7 @@ public class PowerShellExperimentalClientCodegen extends DefaultCodegen implemen
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getTypeDeclaration(inner) + "[]"; return getTypeDeclaration(inner) + "[]";
} else if (ModelUtils.isMapSchema(p)) { } else if (ModelUtils.isMapSchema(p)) {
return "Hashtable"; return "System.Collections.Hashtable";
} else if (!languageSpecificPrimitives.contains(getSchemaType(p))) { } else if (!languageSpecificPrimitives.contains(getSchemaType(p))) {
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);
} }

View File

@ -209,3 +209,106 @@ function Set-{{{apiNamePrefix}}}ConfigurationApiKeyPrefix {
$Script:Configuration["ApiKeyPrefix"][$Id] = $ApiKeyPrefix $Script:Configuration["ApiKeyPrefix"][$Id] = $ApiKeyPrefix
} }
} }
<#
.SYNOPSIS
Get the host setting.
.DESCRIPTION
Get the host setting in the form of array of hashtables.
.OUTPUTS
System.Collections.Hashtable[]
#>
function Get-{{apiNamePrefix}}HostSettings {
return @(
{{#servers}}
@{
"Url" = "{{{url}}}";
"Description" = "{{{description}}}{{^description}}No description provided{{/description}}";
{{#variables}}
{{#-first}}
"Variables" = @{
{{/-first}}
"{{{name}}}" = @{
"Description" = "{{{description}}}{{^description}}No description provided{{/description}}";
"DefaultValue" = "{{{defaultValue}}}";
{{#enumValues}}
{{#-first}}
"EnumValues" = @(
{{/-first}}
"{{{.}}}"{{^-last}},{{/-last}}
{{#-last}}
)
{{/-last}}
{{/enumValues}}
}{{^-last}};{{/-last}}
{{#-last}}
}
{{/-last}}
{{/variables}}
}{{^-last}},{{/-last}}
{{/servers}}
)
}
<#
.SYNOPSIS
Get the URL from the host settings.
.PARAMETER Index
Index of the host settings (array)
.PARAMETER Variables
Names and values of the variables (hashtable)
.DESCRIPTION
Get the URL from the host settings.
.OUTPUTS
String
#>
function Get-{{apiNamePrefix}}UrlFromHostSettings {
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline = $true)]
[Int]$Index,
[Hashtable]$Variables = @{}
)
Process {
$Hosts = Get-{{apiNamePrefix}}HostSettings
# check array index out of bound
if ($Index -lt 0 -or $Index -gt $Hosts.Length) {
throw "Invalid index $index when selecting the host. Must be less than $($Hosts.Length)"
}
$Host = $Hosts[$Index];
$Url = $Host["Url"];
# go through variable and assign a value
foreach ($h in $Host["Variables"].GetEnumerator()) {
if ($Variables.containsKey($h.Name)) { # check to see if it's in the variables provided by the user
if ($h.Value["EnumValues"] -Contains $Variables[$h.Name]) {
$Url = $Url.replace("{$($h.Name)}", $Variables[$h.Name])
} else {
throw "The variable '$($h.Name)' in the host URL has invalid value $($Variables[$h.Name]). Must be $($h.Value["EnumValues"] -join ",")"
}
} else {
$Url = $Url.replace("{$($h.Name)}", $h.Value["DefaultValue"])
}
}
return $Url;
}
}

View File

@ -1,6 +1,27 @@
openapi: 3.0.0 openapi: 3.0.0
servers: servers:
- url: 'http://petstore.swagger.io/v2' - url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server
variables:
server:
enum:
- 'petstore'
- 'qa-petstore'
- 'dev-petstore'
default: 'petstore'
port:
enum:
- 80
- 8080
default: 80
- url: https://localhost:8080/{version}
description: The local server
variables:
version:
enum:
- 'v1'
- 'v2'
default: 'v2'
info: info:
description: >- description: >-
This is a sample server Petstore server. For this sample, you can use the api key This is a sample server Petstore server. For this sample, you can use the api key

View File

@ -49,7 +49,7 @@ Invoker-Pester
## Documentation for API Endpoints ## Documentation for API Endpoints
All URIs are relative to *http://petstore.swagger.io/v2* All URIs are relative to *http://petstore.swagger.io:80/v2*
Class | Method | HTTP request | Description Class | Method | HTTP request | Description
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------

View File

@ -1,6 +1,6 @@
# PSPetstore.PSPetstore/Api.PSPetApi # PSPetstore.PSPetstore/Api.PSPetApi
All URIs are relative to *http://petstore.swagger.io/v2* All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description Method | HTTP request | Description
------------- | ------------- | ------------- ------------- | ------------- | -------------

View File

@ -1,6 +1,6 @@
# PSPetstore.PSPetstore/Api.PSStoreApi # PSPetstore.PSPetstore/Api.PSStoreApi
All URIs are relative to *http://petstore.swagger.io/v2* All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description Method | HTTP request | Description
------------- | ------------- | ------------- ------------- | ------------- | -------------
@ -57,7 +57,7 @@ No authorization required
<a name="Get-PSInventory"></a> <a name="Get-PSInventory"></a>
# **Get-PSInventory** # **Get-PSInventory**
> Hashtable Get-PSInventory<br> > System.Collections.Hashtable Get-PSInventory<br>
Returns pet inventories by status Returns pet inventories by status
@ -76,7 +76,7 @@ $Configuration["ApiKey"]["api_key"] = "YOUR_API_KEY"
# Returns pet inventories by status # Returns pet inventories by status
try { try {
Hashtable $Result = Get-PSInventory System.Collections.Hashtable $Result = Get-PSInventory
} catch { } catch {
Write-Host ($_.ErrorDetails | ConvertFrom-Json) Write-Host ($_.ErrorDetails | ConvertFrom-Json)
Write-Host ($_.Exception.Response.Headers | ConvertTo-Json) Write-Host ($_.Exception.Response.Headers | ConvertTo-Json)
@ -88,7 +88,7 @@ This endpoint does not need any parameter.
### Return type ### Return type
**Hashtable** **System.Collections.Hashtable**
### Authorization ### Authorization

View File

@ -1,6 +1,6 @@
# PSPetstore.PSPetstore/Api.PSUserApi # PSPetstore.PSPetstore/Api.PSUserApi
All URIs are relative to *http://petstore.swagger.io/v2* All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description Method | HTTP request | Description
------------- | ------------- | ------------- ------------- | ------------- | -------------

View File

@ -75,7 +75,7 @@ No description available.
.OUTPUTS .OUTPUTS
Hashtable System.Collections.Hashtable
#> #>
function Get-PSInventory { function Get-PSInventory {
[CmdletBinding()] [CmdletBinding()]
@ -114,7 +114,7 @@ function Get-PSInventory {
-QueryParameters $LocalVarQueryParameters ` -QueryParameters $LocalVarQueryParameters `
-FormParameters $LocalVarFormParameters ` -FormParameters $LocalVarFormParameters `
-CookieParameters $LocalVarCookieParameters ` -CookieParameters $LocalVarCookieParameters `
-ReturnType "Hashtable" -ReturnType "System.Collections.Hashtable"
return $LocalVarResult["Response"] return $LocalVarResult["Response"]
} }

View File

@ -23,7 +23,7 @@ function Get-PSConfiguration {
$Configuration = $Script:Configuration $Configuration = $Script:Configuration
if ([string]::IsNullOrEmpty($Configuration["BaseUrl"])) { if ([string]::IsNullOrEmpty($Configuration["BaseUrl"])) {
$Configuration["BaseUrl"] = "http://petstore.swagger.io/v2"; $Configuration["BaseUrl"] = "http://petstore.swagger.io:80/v2";
} }
if (!$Configuration.containsKey("Username")) { if (!$Configuration.containsKey("Username")) {
@ -215,3 +215,116 @@ function Set-PSConfigurationApiKeyPrefix {
$Script:Configuration["ApiKeyPrefix"][$Id] = $ApiKeyPrefix $Script:Configuration["ApiKeyPrefix"][$Id] = $ApiKeyPrefix
} }
} }
<#
.SYNOPSIS
Get the host setting.
.DESCRIPTION
Get the host setting in the form of array of hashtables.
.OUTPUTS
System.Collections.Hashtable[]
#>
function Get-PSHostSettings {
return @(
@{
"Url" = "http://{server}.swagger.io:{port}/v2";
"Description" = "petstore server";
"Variables" = @{
"server" = @{
"Description" = "No description provided";
"DefaultValue" = "petstore";
"EnumValues" = @(
"petstore",
"qa-petstore",
"dev-petstore"
)
};
"port" = @{
"Description" = "No description provided";
"DefaultValue" = "80";
"EnumValues" = @(
"80",
"8080"
)
}
}
},
@{
"Url" = "https://localhost:8080/{version}";
"Description" = "The local server";
"Variables" = @{
"version" = @{
"Description" = "No description provided";
"DefaultValue" = "v2";
"EnumValues" = @(
"v1",
"v2"
)
}
}
}
)
}
<#
.SYNOPSIS
Get the URL from the host settings.
.PARAMETER Index
Index of the host settings (array)
.PARAMETER Variables
Names and values of the variables (hashtable)
.DESCRIPTION
Get the URL from the host settings.
.OUTPUTS
String
#>
function Get-PSUrlFromHostSettings {
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline = $true)]
[Int]$Index,
[Hashtable]$Variables = @{}
)
Process {
$Hosts = Get-PSHostSettings
# check array index out of bound
if ($Index -lt 0 -or $Index -gt $Hosts.Length) {
throw "Invalid index $index when selecting the host. Must be less than $($Hosts.Length)"
}
$Host = $Hosts[$Index];
$Url = $Host["Url"];
# go through variable and assign a value
foreach ($h in $Host["Variables"].GetEnumerator()) {
if ($Variables.containsKey($h.Name)) { # check to see if it's in the variables provided by the user
if ($h.Value["EnumValues"] -Contains $Variables[$h.Name]) {
$Url = $Url.replace("{$($h.Name)}", $Variables[$h.Name])
} else {
throw "The variable '$($h.Name)' in the host URL has invalid value $($Variables[$h.Name]). Must be $($h.Value["EnumValues"] -join ",")"
}
} else {
$Url = $Url.replace("{$($h.Name)}", $h.Value["DefaultValue"])
}
}
return $Url;
}
}

View File

@ -3,7 +3,7 @@
# #
# Generated by: OpenAPI Generator Team # Generated by: OpenAPI Generator Team
# #
# Generated on: 3/19/20 # Generated on: 3/29/20
# #
@{ @{
@ -79,7 +79,8 @@ FunctionsToExport = 'Add-PSPet', 'Remove-Pet', 'Find-PSPetsByStatus', 'Find-PSPe
'Update-PSUser', 'New-PSApiResponse', 'New-PSCategory', 'Update-PSUser', 'New-PSApiResponse', 'New-PSCategory',
'New-PSInlineObject', 'New-PSInlineObject1', 'New-PSOrder', 'New-PSPet', 'New-PSInlineObject', 'New-PSInlineObject1', 'New-PSOrder', 'New-PSPet',
'New-PSTag', 'New-PSUser', 'Get-PSConfiguration', 'Set-PSConfiguration', 'New-PSTag', 'New-PSUser', 'Get-PSConfiguration', 'Set-PSConfiguration',
'Set-PSConfigurationApiKey', 'Set-PSConfigurationApiKeyPrefix' 'Set-PSConfigurationApiKey', 'Set-PSConfigurationApiKeyPrefix',
'Get-PSHostSettings', 'Get-PSUrlFromHostSettings'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @() CmdletsToExport = @()

View File

@ -60,4 +60,29 @@ Describe -tag 'PSOpenAPITools' -name 'Integration Tests' {
} }
} }
Context 'Configuration' {
It 'Get-PSHostSettings tests' {
$HS = Get-PSHostSettings
$HS[0]["Url"] | Should Be "http://{server}.swagger.io:{port}/v2"
$HS[0]["Description"] | Should Be "petstore server"
$HS[0]["Variables"]["server"]["Description"] | Should Be "No description provided"
$HS[0]["Variables"]["server"]["DefaultValue"] | Should Be "petstore"
$HS[0]["Variables"]["server"]["EnumValues"] | Should Be @("petstore",
"qa-petstore",
"dev-petstore")
}
It "Get-PSUrlFromHostSettings tests" {
Get-PSUrlFromHostSettings -Index 0 | Should Be "http://petstore.swagger.io:80/v2"
Get-PSUrlFromHostSettings -Index 0 -Variables @{ "port" = "8080" } | Should Be "http://petstore.swagger.io:8080/v2"
#Get-PSUrlFromHostSettings -Index 2 | Should -Throw -ExceptionType ([RuntimeException])
#Get-PSUrlFromHostSettings -Index 2 | Should -Throw # "Invalid index 2 when selecting the host. Must be less than 2"
#Get-PSUrlFromHostSettings -Index 0 -Variables @{ "port" = "1234" } | Should Throw "The variable 'port' in the host URL has invalid value 1234. Must be 80,8080"
}
}
} }