Add oneof/anyof support to PowerShell client generator (#6361)

* add oneof/anyof support to powershell client gen

* fix tests
This commit is contained in:
William Cheng
2020-05-19 21:42:17 +08:00
committed by GitHub
parent 096b8f8828
commit 5fe34fbd74
18 changed files with 873 additions and 129 deletions

View File

@@ -575,7 +575,7 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
}
if (additionalProperties.containsKey("commonVerbs")) {
String[] entries = ((String)additionalProperties.get("commonVerbs")).split(":");
String[] entries = ((String) additionalProperties.get("commonVerbs")).split(":");
for (String entry : entries) {
String[] pair = entry.split("=");
if (pair.length == 2) {
@@ -617,7 +617,7 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
supportingFiles.add(new SupportingFile("Out-DebugParameter.mustache", infrastructureFolder + File.separator + "Private" + File.separator, "Out-DebugParameter.ps1"));
supportingFiles.add(new SupportingFile("http_signature_auth.mustache", infrastructureFolder + "Private", apiNamePrefix + "HttpSignatureAuth.ps1"));
supportingFiles.add(new SupportingFile("rsa_provider.mustache", infrastructureFolder + "Private", apiNamePrefix + "RSAEncryptionProvider.cs"));
// en-US
supportingFiles.add(new SupportingFile("about_Org.OpenAPITools.help.txt.mustache", infrastructureFolder + File.separator + "en-US" + File.separator + "about_" + packageName + ".help.txt"));
@@ -629,7 +629,7 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
@SuppressWarnings("static-method")
@Override
public String escapeText(String input) {
if (input == null) {
return input;
}
@@ -646,9 +646,9 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
.replaceAll("[\\t\\n\\r]", " ")
.replace("\\", "\\\\")
.replace("\"", "\"\""));
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("#>", "#_>").replace("<#", "<_#");
@@ -857,6 +857,26 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
}
}
// check if return type is oneOf/anyeOf model
for (CodegenOperation op : operationList) {
if (op.returnType != null) {
// look up the model to see if it's anyOf/oneOf
if (modelMaps.containsKey(op.returnType) && modelMaps.get(op.returnType) != null) {
CodegenModel cm = modelMaps.get(op.returnType);
if (cm.oneOf != null && !cm.oneOf.isEmpty()) {
op.vendorExtensions.put("x-ps-return-type-one-of", true);
}
if (cm.anyOf != null && !cm.anyOf.isEmpty()) {
op.vendorExtensions.put("x-ps-return-type-any-of", true);
}
} else {
//LOGGER.error("cannot lookup model " + op.returnType);
}
}
}
return objs;
}

View File

@@ -223,6 +223,16 @@ function {{{vendorExtensions.x-powershell-method-name}}} {
-CookieParameters $LocalVarCookieParameters `
-ReturnType "{{#returnType}}{{{.}}}{{/returnType}}"
{{#vendorExtensions.x-ps-return-type-one-of}}
# process oneOf response
$LocalVarResult["Response"] = ConvertFrom-{{apiNamePrefix}}JsonTo{{returnType}} (ConvertTo-Json $LocalVarResult["Response"])
{{/vendorExtensions.x-ps-return-type-one-of}}
{{#vendorExtensions.x-ps-return-type-any-of}}
# process anyOf response
$LocalVarResult["Response"] = ConvertFrom-{{apiNamePrefix}}JsonTo{{returnType}} (ConvertTo-Json $LocalVarResult["Response"])
{{/vendorExtensions.x-ps-return-type-any-of}}
if ($WithHttpInfo.IsPresent) {
return $LocalVarResult
} else {

View File

@@ -89,7 +89,8 @@ function Invoke-{{{apiNamePrefix}}}ApiClient {
$RequestBody = $Body
}
# http signature authentication
{{#hasHttpSignatureMethods}}
# http signature authentication
if ($null -ne $Configuration['ApiKey'] -and $Configuration['ApiKey'].Count -gt 0) {
$httpSignHeaderArgument = @{
Method = $Method
@@ -104,6 +105,7 @@ function Invoke-{{{apiNamePrefix}}}ApiClient {
}
}
{{/hasHttpSignatureMethods}}
if ($SkipCertificateCheck -eq $true) {
$Response = Invoke-WebRequest -Uri $UriBuilder.Uri `
-Method $Method `

View File

@@ -1,107 +1,6 @@
{{> partial_header}}
{{#models}}
{{#model}}
<#
.SYNOPSIS
{{#summary}}{{{.}}}{{/summary}}{{^summary}}No summary available.{{/summary}}
.DESCRIPTION
{{#description}}{{{description}}}{{/description}}{{^description}}No description available.{{/description}}
{{#allVars}}
.PARAMETER {{{name}}}
{{#description}}{{{description}}}{{/description}}{{^description}}No description available.{{/description}}
{{/allVars}}
.OUTPUTS
{{{classname}}}<PSCustomObject>
#>
function Initialize-{{{apiNamePrefix}}}{{{classname}}} {
[CmdletBinding()]
Param (
{{#allVars}}
[Parameter(Position = {{vendorExtensions.x-index}}, ValueFromPipelineByPropertyName = $true)]
{{#pattern}}
[ValidatePattern("{{{.}}}")]
{{/pattern}}
{{#isEnum}}
{{#allowableValues}}
[ValidateSet({{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}})]
{{/allowableValues}}
{{/isEnum}}
[{{vendorExtensions.x-powershell-data-type}}]
{{=<% %>=}}
${<%name%>}<%^-last%>,<%/-last%>
<%={{ }}=%>
{{/allVars}}
)
Process {
'Creating PSCustomObject: {{{packageName}}} => {{{apiNamePrefix}}}{{{classname}}}' | Write-Debug
$PSBoundParameters | Out-DebugParameter | Write-Debug
{{#vars}}
{{^isNullable}}
{{#required}}
if (!${{{name}}}) {
throw "invalid value for '{{{name}}}', '{{{name}}}' cannot be null."
}
{{/required}}
{{/isNullable}}
{{#hasValidation}}
{{#maxLength}}
if ({{^required}}!${{{name}}} -and {{/required}}${{{name}}}.length -gt {{{maxLength}}}) {
throw "invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}."
}
{{/maxLength}}
{{#minLength}}
if ({{^required}}!${{{name}}} -and {{/required}}${{{name}}}.length -lt {{{minLength}}}) {
throw "invalid value for '{{{name}}}', the character length must be great than or equal to {{{minLength}}}."
}
{{/minLength}}
{{#maximum}}
if ({{^required}}!${{{name}}} -and {{/required}}${{{name}}} {{#exclusiveMaximum}}-ge{{/exclusiveMaximum}}{{^exclusiveMaximum}}-gt{{/exclusiveMaximum}} {{{maximum}}}) {
throw "invalid value for '{{{name}}}', must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}."
}
{{/maximum}}
{{#minimum}}
if ({{^required}}!${{{name}}} -and {{/required}}${{{name}}} {{#exclusiveMinimum}}-le{{/exclusiveMinimum}}{{^exclusiveMinimum}}-lt{{/exclusiveMinimum}} {{{minimum}}}) {
throw "invalid value for '{{{name}}}', must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}."
}
{{/minimum}}
{{#maxItems}}
if ({{^required}}!${{{name}}} -and {{/required}}${{{name}}}.length -gt {{{maxItems}}}) {
throw "invalid value for '{{{name}}}', number of items must be less than or equal to {{{maxItems}}}."
}
{{/maxItems}}
{{#minItems}}
if ({{^required}}!${{{name}}} -and {{/required}}${{{name}}}.length -lt {{{minItems}}}) {
throw "invalid value for '{{{name}}}', number of items must be greater than or equal to {{{minItems}}}."
}
{{/minItems}}
{{/hasValidation}}
{{/vars}}
$PSO = [PSCustomObject]@{
{{=<< >>=}}
<<#allVars>>
"<<baseName>>" = ${<<name>>}
<</allVars>>
<<={{ }}=>>
}
return $PSO
}
}
{{#oneOf}}{{#-first}}{{>model_oneof}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>model_anyof}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>model_simple}}{{/anyOf}}{{/oneOf}}
{{/model}}
{{/models}}

View File

@@ -0,0 +1,60 @@
<#
.SYNOPSIS
{{#summary}}{{{.}}}{{/summary}}{{^summary}}No summary available.{{/summary}}
.DESCRIPTION
{{#description}}{{{description}}}{{/description}}{{^description}}No description available.{{/description}}
.PARAMETER Json
JSON object
.OUTPUTS
{{{classname}}}<PSCustomObject>
#>
function ConvertFrom-{{{apiNamePrefix}}}JsonTo{{{classname}}} {
[CmdletBinding()]
Param (
[AllowEmptyString()]
[string]$Json
)
Process {
$match = 0
$matchType = $null
$matchInstance = $null
{{#anyOf}}
if ($match -ne 0) { # no match yet
# try to match {{{.}}} defined in the anyOf schemas
try {
$matchInstance = ConvertFrom-{{{apiNamePrefix}}}JsonTo{{{.}}} $Json
foreach($property in $matchInstance.PsObject.Properties) {
if ($null -ne $property.Value) {
$matchType = "Dog"
$match++
break
}
}
} catch {
# fail to match the schema defined in anyOf, proceed to the next one
}
}
{{/anyOf}}
if ($match -eq 1) {
return [PSCustomObject]@{
"ActualType" = ${matchType}
"ActualInstance" = ${matchInstance}
"anyOfSchemas" = @({{#anyOf}}"{{{.}}}"{{^-last}}, {{/-last}}{{/anyOf}})
}
} else {
throw "Error! The JSON payload doesn't matches any type defined in anyOf schemas ({{{anyOf}}}). JSON Payload: $($Json)"
}
}
}

View File

@@ -0,0 +1,60 @@
<#
.SYNOPSIS
{{#summary}}{{{.}}}{{/summary}}{{^summary}}No summary available.{{/summary}}
.DESCRIPTION
{{#description}}{{{description}}}{{/description}}{{^description}}No description available.{{/description}}
.PARAMETER Json
JSON object
.OUTPUTS
{{{classname}}}<PSCustomObject>
#>
function ConvertFrom-{{{apiNamePrefix}}}JsonTo{{{classname}}} {
[CmdletBinding()]
Param (
[AllowEmptyString()]
[string]$Json
)
Process {
$match = 0
$matchType = $null
$matchInstance = $null
{{#oneOf}}
# try to match {{{.}}} defined in the oneOf schemas
try {
$matchInstance = ConvertFrom-{{{apiNamePrefix}}}JsonTo{{{.}}} $Json
foreach($property in $matchInstance.PsObject.Properties) {
if ($null -ne $property.Value) {
$matchType = "Dog"
$match++
break
}
}
} catch {
# fail to match the schema defined in oneOf, proceed to the next one
}
{{/oneOf}}
if ($match -gt 1) {
throw "Error! The JSON payload matches more than one type defined in oneOf schemas ({{{oneOf}}}). JSON Payload: $($Json)"
} elseif ($match -eq 1) {
return [PSCustomObject]@{
"ActualType" = ${matchType}
"ActualInstance" = ${matchInstance}
"OneOfSchemas" = @({{#oneOf}}"{{{.}}}"{{^-last}}, {{/-last}}{{/oneOf}})
}
} else {
throw "Error! The JSON payload doesn't matches any type defined in oneOf schemas ({{{oneOf}}}). JSON Payload: $($Json)"
}
}
}

View File

@@ -0,0 +1,166 @@
<#
.SYNOPSIS
{{#summary}}{{{.}}}{{/summary}}{{^summary}}No summary available.{{/summary}}
.DESCRIPTION
{{#description}}{{{description}}}{{/description}}{{^description}}No description available.{{/description}}
{{#allVars}}
.PARAMETER {{{name}}}
{{#description}}{{{description}}}{{/description}}{{^description}}No description available.{{/description}}
{{/allVars}}
.OUTPUTS
{{{classname}}}<PSCustomObject>
#>
function Initialize-{{{apiNamePrefix}}}{{{classname}}} {
[CmdletBinding()]
Param (
{{#allVars}}
[Parameter(Position = {{vendorExtensions.x-index}}, ValueFromPipelineByPropertyName = $true)]
{{#pattern}}
[ValidatePattern("{{{.}}}")]
{{/pattern}}
{{#isEnum}}
{{#allowableValues}}
[ValidateSet({{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}})]
{{/allowableValues}}
{{/isEnum}}
[{{vendorExtensions.x-powershell-data-type}}]
{{=<% %>=}}
${<%name%>}<%^-last%>,<%/-last%>
<%={{ }}=%>
{{/allVars}}
)
Process {
'Creating PSCustomObject: {{{packageName}}} => {{{apiNamePrefix}}}{{{classname}}}' | Write-Debug
$PSBoundParameters | Out-DebugParameter | Write-Debug
{{#vars}}
{{^isNullable}}
{{#required}}
if (!${{{name}}}) {
throw "invalid value for '{{{name}}}', '{{{name}}}' cannot be null."
}
{{/required}}
{{/isNullable}}
{{#hasValidation}}
{{#maxLength}}
if ({{^required}}!${{{name}}} -and {{/required}}${{{name}}}.length -gt {{{maxLength}}}) {
throw "invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}."
}
{{/maxLength}}
{{#minLength}}
if ({{^required}}!${{{name}}} -and {{/required}}${{{name}}}.length -lt {{{minLength}}}) {
throw "invalid value for '{{{name}}}', the character length must be great than or equal to {{{minLength}}}."
}
{{/minLength}}
{{#maximum}}
if ({{^required}}!${{{name}}} -and {{/required}}${{{name}}} {{#exclusiveMaximum}}-ge{{/exclusiveMaximum}}{{^exclusiveMaximum}}-gt{{/exclusiveMaximum}} {{{maximum}}}) {
throw "invalid value for '{{{name}}}', must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}."
}
{{/maximum}}
{{#minimum}}
if ({{^required}}!${{{name}}} -and {{/required}}${{{name}}} {{#exclusiveMinimum}}-le{{/exclusiveMinimum}}{{^exclusiveMinimum}}-lt{{/exclusiveMinimum}} {{{minimum}}}) {
throw "invalid value for '{{{name}}}', must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}."
}
{{/minimum}}
{{#maxItems}}
if ({{^required}}!${{{name}}} -and {{/required}}${{{name}}}.length -gt {{{maxItems}}}) {
throw "invalid value for '{{{name}}}', number of items must be less than or equal to {{{maxItems}}}."
}
{{/maxItems}}
{{#minItems}}
if ({{^required}}!${{{name}}} -and {{/required}}${{{name}}}.length -lt {{{minItems}}}) {
throw "invalid value for '{{{name}}}', number of items must be greater than or equal to {{{minItems}}}."
}
{{/minItems}}
{{/hasValidation}}
{{/vars}}
$PSO = [PSCustomObject]@{
{{=<< >>=}}
<<#allVars>>
"<<baseName>>" = ${<<name>>}
<</allVars>>
<<={{ }}=>>
}
return $PSO
}
}
<#
.SYNOPSIS
Convert from JSON to {{{classname}}}<PSCustomObject>
.DESCRIPTION
Convert from JSON to {{{classname}}}<PSCustomObject>
.PARAMETER Json
Json object
.OUTPUTS
{{{classname}}}<PSCustomObject>
#>
function ConvertFrom-{{{apiNamePrefix}}}JsonTo{{{classname}}} {
Param(
[AllowEmptyString()]
[string]$Json
)
Process {
'Converting JSON to PSCustomObject: {{{packageName}}} => {{{apiNamePrefix}}}{{{classname}}}' | Write-Debug
$PSBoundParameters | Out-DebugParameter | Write-Debug
$JsonParameters = ConvertFrom-Json -InputObject $Json
{{#requiredVars}}
{{#-first}}
If ([string]::IsNullOrEmpty($Json) -or $Json -eq "{}") { # empty json
throw "Error! Empty JSON cannot be serialized due to the required property `{{{baseName}}}` missing."
}
{{/-first}}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "{{{baseName}}}"))) {
throw "Error! JSON cannot be serialized due to the required property `{{{baseName}}}` missing."
} else {
${{name}} = $JsonParameters.PSobject.Properties["{{{baseName}}}"].value
}
{{/requiredVars}}
{{#optionalVars}}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "{{{baseName}}}"))) { #optional property not found
${{name}} = $null
} else {
${{name}} = $JsonParameters.PSobject.Properties["{{{baseName}}}"].value
}
{{/optionalVars}}
$PSO = [PSCustomObject]@{
{{=<< >>=}}
<<#allVars>>
"<<baseName>>" = ${<<name>>}
<</allVars>>
<<={{ }}=>>
}
return $PSO
}
}

View File

@@ -55,3 +55,62 @@ function Initialize-PSApiResponse {
return $PSO
}
}
<#
.SYNOPSIS
Convert from JSON to ApiResponse<PSCustomObject>
.DESCRIPTION
Convert from JSON to ApiResponse<PSCustomObject>
.PARAMETER Json
Json object
.OUTPUTS
ApiResponse<PSCustomObject>
#>
function ConvertFrom-PSJsonToApiResponse {
Param(
[AllowEmptyString()]
[string]$Json
)
Process {
'Converting JSON to PSCustomObject: PSPetstore => PSApiResponse' | Write-Debug
$PSBoundParameters | Out-DebugParameter | Write-Debug
$JsonParameters = ConvertFrom-Json -InputObject $Json
if (!([bool]($JsonParameters.PSobject.Properties.name -match "code"))) { #optional property not found
$Code = $null
} else {
$Code = $JsonParameters.PSobject.Properties["code"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "type"))) { #optional property not found
$Type = $null
} else {
$Type = $JsonParameters.PSobject.Properties["type"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "message"))) { #optional property not found
$Message = $null
} else {
$Message = $JsonParameters.PSobject.Properties["message"].value
}
$PSO = [PSCustomObject]@{
"code" = ${Code}
"type" = ${Type}
"message" = ${Message}
}
return $PSO
}
}

View File

@@ -49,3 +49,55 @@ function Initialize-PSCategory {
return $PSO
}
}
<#
.SYNOPSIS
Convert from JSON to Category<PSCustomObject>
.DESCRIPTION
Convert from JSON to Category<PSCustomObject>
.PARAMETER Json
Json object
.OUTPUTS
Category<PSCustomObject>
#>
function ConvertFrom-PSJsonToCategory {
Param(
[AllowEmptyString()]
[string]$Json
)
Process {
'Converting JSON to PSCustomObject: PSPetstore => PSCategory' | Write-Debug
$PSBoundParameters | Out-DebugParameter | Write-Debug
$JsonParameters = ConvertFrom-Json -InputObject $Json
if (!([bool]($JsonParameters.PSobject.Properties.name -match "id"))) { #optional property not found
$Id = $null
} else {
$Id = $JsonParameters.PSobject.Properties["id"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "name"))) { #optional property not found
$Name = $null
} else {
$Name = $JsonParameters.PSobject.Properties["name"].value
}
$PSO = [PSCustomObject]@{
"id" = ${Id}
"name" = ${Name}
}
return $PSO
}
}

View File

@@ -48,3 +48,55 @@ function Initialize-PSInlineObject {
return $PSO
}
}
<#
.SYNOPSIS
Convert from JSON to InlineObject<PSCustomObject>
.DESCRIPTION
Convert from JSON to InlineObject<PSCustomObject>
.PARAMETER Json
Json object
.OUTPUTS
InlineObject<PSCustomObject>
#>
function ConvertFrom-PSJsonToInlineObject {
Param(
[AllowEmptyString()]
[string]$Json
)
Process {
'Converting JSON to PSCustomObject: PSPetstore => PSInlineObject' | Write-Debug
$PSBoundParameters | Out-DebugParameter | Write-Debug
$JsonParameters = ConvertFrom-Json -InputObject $Json
if (!([bool]($JsonParameters.PSobject.Properties.name -match "name"))) { #optional property not found
$Name = $null
} else {
$Name = $JsonParameters.PSobject.Properties["name"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "status"))) { #optional property not found
$Status = $null
} else {
$Status = $JsonParameters.PSobject.Properties["status"].value
}
$PSO = [PSCustomObject]@{
"name" = ${Name}
"status" = ${Status}
}
return $PSO
}
}

View File

@@ -48,3 +48,55 @@ function Initialize-PSInlineObject1 {
return $PSO
}
}
<#
.SYNOPSIS
Convert from JSON to InlineObject1<PSCustomObject>
.DESCRIPTION
Convert from JSON to InlineObject1<PSCustomObject>
.PARAMETER Json
Json object
.OUTPUTS
InlineObject1<PSCustomObject>
#>
function ConvertFrom-PSJsonToInlineObject1 {
Param(
[AllowEmptyString()]
[string]$Json
)
Process {
'Converting JSON to PSCustomObject: PSPetstore => PSInlineObject1' | Write-Debug
$PSBoundParameters | Out-DebugParameter | Write-Debug
$JsonParameters = ConvertFrom-Json -InputObject $Json
if (!([bool]($JsonParameters.PSobject.Properties.name -match "additionalMetadata"))) { #optional property not found
$AdditionalMetadata = $null
} else {
$AdditionalMetadata = $JsonParameters.PSobject.Properties["additionalMetadata"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "file"))) { #optional property not found
$File = $null
} else {
$File = $JsonParameters.PSobject.Properties["file"].value
}
$PSO = [PSCustomObject]@{
"additionalMetadata" = ${AdditionalMetadata}
"file" = ${File}
}
return $PSO
}
}

View File

@@ -77,3 +77,83 @@ function Initialize-PSOrder {
return $PSO
}
}
<#
.SYNOPSIS
Convert from JSON to Order<PSCustomObject>
.DESCRIPTION
Convert from JSON to Order<PSCustomObject>
.PARAMETER Json
Json object
.OUTPUTS
Order<PSCustomObject>
#>
function ConvertFrom-PSJsonToOrder {
Param(
[AllowEmptyString()]
[string]$Json
)
Process {
'Converting JSON to PSCustomObject: PSPetstore => PSOrder' | Write-Debug
$PSBoundParameters | Out-DebugParameter | Write-Debug
$JsonParameters = ConvertFrom-Json -InputObject $Json
if (!([bool]($JsonParameters.PSobject.Properties.name -match "id"))) { #optional property not found
$Id = $null
} else {
$Id = $JsonParameters.PSobject.Properties["id"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "petId"))) { #optional property not found
$PetId = $null
} else {
$PetId = $JsonParameters.PSobject.Properties["petId"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "quantity"))) { #optional property not found
$Quantity = $null
} else {
$Quantity = $JsonParameters.PSobject.Properties["quantity"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "shipDate"))) { #optional property not found
$ShipDate = $null
} else {
$ShipDate = $JsonParameters.PSobject.Properties["shipDate"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "status"))) { #optional property not found
$Status = $null
} else {
$Status = $JsonParameters.PSobject.Properties["status"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "complete"))) { #optional property not found
$Complete = $null
} else {
$Complete = $JsonParameters.PSobject.Properties["complete"].value
}
$PSO = [PSCustomObject]@{
"id" = ${Id}
"petId" = ${PetId}
"quantity" = ${Quantity}
"shipDate" = ${ShipDate}
"status" = ${Status}
"complete" = ${Complete}
}
return $PSO
}
}

View File

@@ -85,3 +85,87 @@ function Initialize-PSPet {
return $PSO
}
}
<#
.SYNOPSIS
Convert from JSON to Pet<PSCustomObject>
.DESCRIPTION
Convert from JSON to Pet<PSCustomObject>
.PARAMETER Json
Json object
.OUTPUTS
Pet<PSCustomObject>
#>
function ConvertFrom-PSJsonToPet {
Param(
[AllowEmptyString()]
[string]$Json
)
Process {
'Converting JSON to PSCustomObject: PSPetstore => PSPet' | Write-Debug
$PSBoundParameters | Out-DebugParameter | Write-Debug
$JsonParameters = ConvertFrom-Json -InputObject $Json
If ([string]::IsNullOrEmpty($Json) -or $Json -eq "{}") { # empty json
throw "Error! Empty JSON cannot be serialized due to the required property `name` missing."
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "name"))) {
throw "Error! JSON cannot be serialized due to the required property `name` missing."
} else {
$Name = $JsonParameters.PSobject.Properties["name"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "photoUrls"))) {
throw "Error! JSON cannot be serialized due to the required property `photoUrls` missing."
} else {
$PhotoUrls = $JsonParameters.PSobject.Properties["photoUrls"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "id"))) { #optional property not found
$Id = $null
} else {
$Id = $JsonParameters.PSobject.Properties["id"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "category"))) { #optional property not found
$Category = $null
} else {
$Category = $JsonParameters.PSobject.Properties["category"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "tags"))) { #optional property not found
$Tags = $null
} else {
$Tags = $JsonParameters.PSobject.Properties["tags"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "status"))) { #optional property not found
$Status = $null
} else {
$Status = $JsonParameters.PSobject.Properties["status"].value
}
$PSO = [PSCustomObject]@{
"id" = ${Id}
"category" = ${Category}
"name" = ${Name}
"photoUrls" = ${PhotoUrls}
"tags" = ${Tags}
"status" = ${Status}
}
return $PSO
}
}

View File

@@ -48,3 +48,55 @@ function Initialize-PSTag {
return $PSO
}
}
<#
.SYNOPSIS
Convert from JSON to Tag<PSCustomObject>
.DESCRIPTION
Convert from JSON to Tag<PSCustomObject>
.PARAMETER Json
Json object
.OUTPUTS
Tag<PSCustomObject>
#>
function ConvertFrom-PSJsonToTag {
Param(
[AllowEmptyString()]
[string]$Json
)
Process {
'Converting JSON to PSCustomObject: PSPetstore => PSTag' | Write-Debug
$PSBoundParameters | Out-DebugParameter | Write-Debug
$JsonParameters = ConvertFrom-Json -InputObject $Json
if (!([bool]($JsonParameters.PSobject.Properties.name -match "id"))) { #optional property not found
$Id = $null
} else {
$Id = $JsonParameters.PSobject.Properties["id"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "name"))) { #optional property not found
$Name = $null
} else {
$Name = $JsonParameters.PSobject.Properties["name"].value
}
$PSO = [PSCustomObject]@{
"id" = ${Id}
"name" = ${Name}
}
return $PSO
}
}

View File

@@ -91,3 +91,97 @@ function Initialize-PSUser {
return $PSO
}
}
<#
.SYNOPSIS
Convert from JSON to User<PSCustomObject>
.DESCRIPTION
Convert from JSON to User<PSCustomObject>
.PARAMETER Json
Json object
.OUTPUTS
User<PSCustomObject>
#>
function ConvertFrom-PSJsonToUser {
Param(
[AllowEmptyString()]
[string]$Json
)
Process {
'Converting JSON to PSCustomObject: PSPetstore => PSUser' | Write-Debug
$PSBoundParameters | Out-DebugParameter | Write-Debug
$JsonParameters = ConvertFrom-Json -InputObject $Json
if (!([bool]($JsonParameters.PSobject.Properties.name -match "id"))) { #optional property not found
$Id = $null
} else {
$Id = $JsonParameters.PSobject.Properties["id"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "username"))) { #optional property not found
$Username = $null
} else {
$Username = $JsonParameters.PSobject.Properties["username"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "firstName"))) { #optional property not found
$FirstName = $null
} else {
$FirstName = $JsonParameters.PSobject.Properties["firstName"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "lastName"))) { #optional property not found
$LastName = $null
} else {
$LastName = $JsonParameters.PSobject.Properties["lastName"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "email"))) { #optional property not found
$Email = $null
} else {
$Email = $JsonParameters.PSobject.Properties["email"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "password"))) { #optional property not found
$Password = $null
} else {
$Password = $JsonParameters.PSobject.Properties["password"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "phone"))) { #optional property not found
$Phone = $null
} else {
$Phone = $JsonParameters.PSobject.Properties["phone"].value
}
if (!([bool]($JsonParameters.PSobject.Properties.name -match "userStatus"))) { #optional property not found
$UserStatus = $null
} else {
$UserStatus = $JsonParameters.PSobject.Properties["userStatus"].value
}
$PSO = [PSCustomObject]@{
"id" = ${Id}
"username" = ${Username}
"firstName" = ${FirstName}
"lastName" = ${LastName}
"email" = ${Email}
"password" = ${Password}
"phone" = ${Phone}
"userStatus" = ${UserStatus}
}
return $PSO
}
}

View File

@@ -3,7 +3,7 @@
#
# Generated by: OpenAPI Generator Team
#
# Generated on: 4/19/20
# Generated on: 5/19/20
#
@{
@@ -76,11 +76,16 @@ FunctionsToExport = 'Add-PSPet', 'Remove-Pet', 'Find-PSPetsByStatus', 'Find-PSPe
'New-PSUsersWithArrayInput', 'New-PSUsersWithListInput',
'Remove-PSUser', 'Get-PSUserByName', 'Invoke-PSLoginUser',
'Invoke-PSLogoutUser', 'Update-PSUser', 'Initialize-PSApiResponse',
'Initialize-PSCategory', 'Initialize-PSInlineObject',
'Initialize-PSInlineObject1', 'Initialize-PSOrder',
'Initialize-PSPet', 'Initialize-PSTag', 'Initialize-PSUser',
'Get-PSConfiguration', 'Set-PSConfiguration',
'Set-PSConfigurationApiKey', 'Set-PSConfigurationApiKeyPrefix',
'ConvertFrom-PSJsonToApiResponse', 'Initialize-PSCategory',
'ConvertFrom-PSJsonToCategory', 'Initialize-PSInlineObject',
'ConvertFrom-PSJsonToInlineObject', 'Initialize-PSInlineObject1',
'ConvertFrom-PSJsonToInlineObject1', 'Initialize-PSOrder',
'ConvertFrom-PSJsonToOrder', 'Initialize-PSPet',
'ConvertFrom-PSJsonToPet', 'Initialize-PSTag',
'ConvertFrom-PSJsonToTag', 'Initialize-PSUser',
'ConvertFrom-PSJsonToUser', 'Get-PSConfiguration',
'Set-PSConfiguration', 'Set-PSConfigurationApiKey',
'Set-PSConfigurationApiKeyPrefix',
'Set-PSConfigurationDefaultHeader', 'Get-PSHostSetting',
'Get-PSUrlFromHostSetting'

View File

@@ -95,21 +95,6 @@ function Invoke-PSApiClient {
$RequestBody = $Body
}
# http signature authentication
if ($null -ne $Configuration['ApiKey'] -and $Configuration['ApiKey'].Count -gt 0) {
$httpSignHeaderArgument = @{
Method = $Method
UriBuilder = $UriBuilder
Body = $Body
}
$signedHeader = Get-PSHttpSignedHeader @httpSignHeaderArgument
if($null -ne $signedHeader -and $signedHeader.Count -gt 0){
foreach($item in $signedHeader.GetEnumerator()){
$HeaderParameters[$item.Name] = $item.Value
}
}
}
if ($SkipCertificateCheck -eq $true) {
$Response = Invoke-WebRequest -Uri $UriBuilder.Uri `
-Method $Method `

View File

@@ -174,4 +174,16 @@ Describe -tag 'PSOpenAPITools' -name 'Integration Tests' {
$Conf = Set-PSConfiguration -BaseURL "https://localhost:8080/api"
}
}
Context 'PSObject' {
It "Create Object from JSON tests" {
$Result = ConvertFrom-PSJsonToPet '{"id": 345, "name": "json name test", "status": "available", "photoUrls": ["https://photo.test"]}'
$Result."id" | Should Be 345
$Result."name" | Should Be "json name test"
$Result."status" | Should Be "available"
$Result."photoUrls" | Should Be @("https://photo.test")
}
}
}