Skip to content

Commit

Permalink
Merge branch 'master' into ensures
Browse files Browse the repository at this point in the history
* master:
  [Go][Experimental] Fix discriminator lookup (#6521)
  Typescript-rxjs: print param name (#6368)
  add oneof discrimistrator lookup to go experimental (#6517)
  [PowerShell] Add useOneOfDiscriminatorLookup option (#6516)
  add discriminator support to anyOf powershell client (#6512)
  [Go][Experimental] Add discriminator support to anyOf (#6511)
  • Loading branch information
jimschubert committed Jun 3, 2020
2 parents e2790ef + 4d68953 commit 9aa5675
Show file tree
Hide file tree
Showing 34 changed files with 841 additions and 395 deletions.
1 change: 1 addition & 0 deletions docs/generators/go-experimental.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ sidebar_label: go-experimental
|packageVersion|Go package version.| |1.0.0|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|structPrefix|whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts| |false|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.| |false|
|withAWSV4Signature|whether to include AWS v4 signature support| |false|
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default in GitHub PRs and diffs| |false|
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
Expand Down
1 change: 1 addition & 0 deletions docs/generators/powershell.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ sidebar_label: powershell
|packageName|Client package name (e.g. PSTwitter).| |PSOpenAPITools|
|packageVersion|Package version (e.g. 0.1.2).| |0.1.2|
|powershellGalleryUrl|URL to the module in PowerShell Gallery (e.g. https://www.powershellgallery.com/packages/PSTwitter/).| |null|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.| |null|

## IMPORT MAPPING

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -375,4 +375,6 @@ public static enum ENUM_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case,
" 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed." +
"Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.";

public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP = "useOneOfDiscriminatorLookup";
public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC = "Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.";
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public class GoClientExperimentalCodegen extends GoClientCodegen {

private static final Logger LOGGER = LoggerFactory.getLogger(GoClientExperimentalCodegen.class);
protected String goImportAlias = "openapiclient";
protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup

public GoClientExperimentalCodegen() {
super();
Expand All @@ -44,6 +45,8 @@ public GoClientExperimentalCodegen() {
usesOptionals = false;

generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.EXPERIMENTAL).build();

cliOptions.add(new CliOption(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC).defaultValue("false"));
}

/**
Expand Down Expand Up @@ -93,6 +96,20 @@ public void processOpts() {
additionalProperties.put("goImportAlias", goImportAlias);
}

if (additionalProperties.containsKey(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP)) {
setUseOneOfDiscriminatorLookup(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP));
} else {
additionalProperties.put(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, useOneOfDiscriminatorLookup);
}

}

public void setUseOneOfDiscriminatorLookup(boolean useOneOfDiscriminatorLookup) {
this.useOneOfDiscriminatorLookup = useOneOfDiscriminatorLookup;
}

public boolean getUseOneOfDiscriminatorLookup() {
return this.useOneOfDiscriminatorLookup;
}

public void setGoImportAlias(String goImportAlias) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
protected HashSet powershellVerbs;
protected Map<String, String> commonVerbs; // verbs not in the official ps verb list but can be mapped to one of the verbs
protected HashSet methodNames; // store a list of method names to detect duplicates
protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup

/**
* Constructs an instance of `PowerShellClientCodegen`.
Expand Down Expand Up @@ -498,7 +499,7 @@ public PowerShellClientCodegen() {
cliOptions.add(new CliOption(CodegenConstants.OPTIONAL_PROJECT_GUID, "GUID for PowerShell module (e.g. a27b908d-2a20-467f-bc32-af6f3a654ac5). A random GUID will be generated by default."));
cliOptions.add(new CliOption(CodegenConstants.API_NAME_PREFIX, "Prefix that will be appended to all PS objects. Default: empty string. e.g. Pet => PSPet."));
cliOptions.add(new CliOption("commonVerbs", "PS common verb mappings. e.g. Delete=Remove:Patch=Update to map Delete with Remove and Patch with Update accordingly."));

cliOptions.add(new CliOption(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC));
}

public CodegenType getTag() {
Expand Down Expand Up @@ -535,6 +536,14 @@ public void setPowershellGalleryUrl(String powershellGalleryUrl) {
this.powershellGalleryUrl = powershellGalleryUrl;
}

public void setUseOneOfDiscriminatorLookup(boolean useOneOfDiscriminatorLookup) {
this.useOneOfDiscriminatorLookup = useOneOfDiscriminatorLookup;
}

public boolean getUseOneOfDiscriminatorLookup() {
return this.useOneOfDiscriminatorLookup;
}

@Override
public void processOpts() {
super.processOpts();
Expand All @@ -550,6 +559,12 @@ public void processOpts() {
additionalProperties.put("powershellGalleryUrl", powershellGalleryUrl);
}

if (additionalProperties.containsKey(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP)) {
setUseOneOfDiscriminatorLookup(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP));
} else {
additionalProperties.put(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, useOneOfDiscriminatorLookup);
}

if (StringUtils.isNotBlank(powershellGalleryUrl)) {
// get the last segment of the URL
// e.g. https://www.powershellgallery.com/packages/PSTwitter => PSTwitter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,35 @@ func (dst *{{classname}}) UnmarshalJSON(data []byte) error {
}

{{/isNullable}}
{{#discriminator}}
{{#mappedModels}}
{{#-first}}
// use discriminator value to speed up the lookup
var jsonDict map[string]interface{}
err := json.Unmarshal(data, &jsonDict)
if err != nil {
return fmt.Errorf("Failed to unmarshal JSON into map for the discrimintor lookup.")
}

{{/-first}}
// check if the discriminator value is '{{{mappingName}}}'
if jsonDict["{{{propertyBaseName}}}"] == "{{{mappingName}}}" {
// try to unmarshal JSON data into {{{modelName}}}
err = json.Unmarshal(data, &dst.{{{modelName}}});
if err == nil {
json{{{modelName}}}, _ := json.Marshal(dst.{{{modelName}}})
if string(json{{{modelName}}}) == "{}" { // empty struct
dst.{{{modelName}}} = nil
} else {
return nil // data stored in dst.{{{modelName}}}, return on the first match
}
} else {
dst.{{{modelName}}} = nil
}
}

{{/mappedModels}}
{{/discriminator}}
{{#anyOf}}
// try to unmarshal JSON data into {{{.}}}
err = json.Unmarshal(data, &dst.{{{.}}});
Expand Down Expand Up @@ -44,4 +73,4 @@ func (src *{{classname}}) MarshalJSON() ([]byte, error) {
return nil, nil // no data in anyOf schemas
}

{{>nullable_model}}
{{>nullable_model}}
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,40 @@ func (dst *{{classname}}) UnmarshalJSON(data []byte) error {
}

{{/isNullable}}
{{#useOneOfDiscriminatorLookup}}
{{#discriminator}}
{{#mappedModels}}
{{#-first}}
// use discriminator value to speed up the lookup
var jsonDict map[string]interface{}
err = json.Unmarshal(data, &jsonDict)
if err != nil {
return fmt.Errorf("Failed to unmarshal JSON into map for the discrimintor lookup.")
}

{{/-first}}
// check if the discriminator value is '{{{mappingName}}}'
if jsonDict["{{{propertyBaseName}}}"] == "{{{mappingName}}}" {
// try to unmarshal JSON data into {{{modelName}}}
err = json.Unmarshal(data, &dst.{{{modelName}}})
if err == nil {
json{{{modelName}}}, _ := json.Marshal(dst.{{{modelName}}})
if string(json{{{modelName}}}) == "{}" { // empty struct
dst.{{{modelName}}} = nil
} else {
return nil // data stored in dst.{{{modelName}}}, return on the first match
}
} else {
dst.{{{modelName}}} = nil
}
}

{{/mappedModels}}
{{/discriminator}}
{{/useOneOfDiscriminatorLookup}}
{{#oneOf}}
// try to unmarshal data into {{{.}}}
err = json.Unmarshal(data, &dst.{{{.}}});
err = json.Unmarshal(data, &dst.{{{.}}})
if err == nil {
json{{{.}}}, _ := json.Marshal(dst.{{{.}}})
if string(json{{{.}}}) == "{}" { // empty struct
Expand Down Expand Up @@ -76,4 +107,4 @@ func (obj *{{classname}}) GetActualInstance() (interface{}) {
return nil
}

{{>nullable_model}}
{{>nullable_model}}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,35 @@ function ConvertFrom-{{{apiNamePrefix}}}JsonTo{{{classname}}} {
}

{{/isNullable}}
{{#discriminator}}
{{#mappedModels}}
{{#-first}}
$JsonData = ConvertFrom-Json -InputObject $Json
{{/-first}}
# check if the discriminator value is '{{{mappingName}}}'
if ($JsonData.PSobject.Properties["{{{propertyBaseName}}}"].value == "{{{mappingName}}}") {
# try to match {{{modelName}}} defined in the anyOf schemas
try {
$matchInstance = ConvertFrom-{{{apiNamePrefix}}}JsonTo{{{modelName}}} $Json

foreach($property in $matchInstance.PsObject.Properties) {
if ($null -ne $property.Value) {
$matchType = "{{{modelName}}}"
return [PSCustomObject]@{
"ActualType" = ${matchType}
"ActualInstance" = ${matchInstance}
"anyOfSchemas" = @({{#anyOf}}"{{{.}}}"{{^-last}}, {{/-last}}{{/anyOf}})
}
}
}
} catch {
# fail to match the schema defined in anyOf with the discriminator lookup, proceed to the next one
Write-Debug "Failed to match '{{{modelName}}}' defined in anyOf ({{{apiNamePrefix}}}{{{classname}}}) using the discriminator lookup ({{{mappingName}}}). Proceeding with the typical anyOf type matching."
}
}

{{/mappedModels}}
{{/discriminator}}
{{#anyOf}}
if ($match -ne 0) { # no match yet
# try to match {{{.}}} defined in the anyOf schemas
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,37 @@ function ConvertFrom-{{{apiNamePrefix}}}JsonTo{{{classname}}} {
}

{{/isNullable}}
{{#useOneOfDiscriminatorLookup}}
{{#discriminator}}
{{#mappedModels}}
{{#-first}}
$JsonData = ConvertFrom-Json -InputObject $Json
{{/-first}}
# check if the discriminator value is '{{{mappingName}}}'
if ($JsonData.PSobject.Properties["{{{propertyBaseName}}}"].value == "{{{mappingName}}}") {
# try to match {{{modelName}}} defined in the oneOf schemas
try {
$matchInstance = ConvertFrom-{{{apiNamePrefix}}}JsonTo{{{modelName}}} $Json

foreach($property in $matchInstance.PsObject.Properties) {
if ($null -ne $property.Value) {
$matchType = "{{{modelName}}}"
return [PSCustomObject]@{
"ActualType" = ${matchType}
"ActualInstance" = ${matchInstance}
"oneOfSchemas" = @({{#oneOf}}"{{{.}}}"{{^-last}}, {{/-last}}{{/oneOf}})
}
}
}
} catch {
# fail to match the schema defined in oneOf with the discriminator lookup, proceed to the next one
Write-Debug "Failed to match '{{{modelName}}}' defined in oneOf ({{{apiNamePrefix}}}{{{classname}}}) using the discriminator lookup ({{{mappingName}}}). Proceeding with the typical oneOf type matching."
}
}

{{/mappedModels}}
{{/discriminator}}
{{/useOneOfDiscriminatorLookup}}
{{#oneOf}}
# try to match {{{.}}} defined in the oneOf schemas
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export class {{classname}} extends BaseAPI {
{{#hasParams}}
{{#allParams}}
{{#required}}
throwIfNullOrUndefined({{> paramNamePartial}}, '{{nickname}}');
throwIfNullOrUndefined({{> paramNamePartial}}, '{{> paramNamePartial}}', '{{nickname}}');
{{/required}}
{{/allParams}}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,9 @@ export const throwIfRequired = (params: {[key: string]: any}, key: string, nickn
}
};

export const throwIfNullOrUndefined = (value: any, nickname?: string) => {
export const throwIfNullOrUndefined = (value: any, paramName: string, nickname: string) => {
if (value == null) {
throw new Error(`Parameter "${value}" was null or undefined when calling "${nickname}".`);
throw new Error(`Parameter "${paramName}" was null or undefined when calling "${nickname}".`);
}
};

Expand Down
Loading

0 comments on commit 9aa5675

Please sign in to comment.