From 713c536be389cfecfc40d16adac97348a908f66c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tristan=20Spr=C3=B6=C3=9Fer?= Date: Tue, 22 Sep 2026 10:29:18 +0200 Subject: [PATCH 1/2] feat(typescript-angular): add opt-in form object dot notation Add useDotNotationForFormObjects with a false default so standard form serialization remains unchanged. Preserve parameter-prefixed property paths when enabled, document the server-specific convention, and add generator and runtime regression coverage with a generated sample. --- ...ript-angular-v20-query-param-form-dot.yaml | 9 + docs/generators/typescript-angular.md | 1 + .../TypeScriptAngularClientCodegen.java | 5 + .../typescript-angular/README.mustache | 14 ++ .../api.base.service.mustache | 2 +- ...ypeScriptAngularClientOptionsProvider.java | 1 + .../TypeScriptAngularClientCodegenTest.java | 23 ++ .../builds/query-param-form-dot/.gitignore | 4 + .../.openapi-generator-ignore | 23 ++ .../.openapi-generator/FILES | 21 ++ .../.openapi-generator/VERSION | 1 + .../builds/query-param-form-dot/README.md | 197 +++++++++++++++ .../query-param-form-dot/api.base.service.ts | 96 ++++++++ .../builds/query-param-form-dot/api.module.ts | 30 +++ .../builds/query-param-form-dot/api/api.ts | 3 + .../api/default.service.ts | 228 ++++++++++++++++++ .../query-param-form-dot/configuration.ts | 185 ++++++++++++++ .../builds/query-param-form-dot/encoder.ts | 35 +++ .../builds/query-param-form-dot/git_push.sh | 54 +++++ .../builds/query-param-form-dot/index.ts | 7 + .../query-param-form-dot/model/filter.ts | 23 ++ .../builds/query-param-form-dot/model/item.ts | 23 ++ .../query-param-form-dot/model/models.ts | 3 + .../query-param-form-dot/model/response.ts | 19 ++ .../query-param-form-dot/ng-package.json | 6 + .../builds/query-param-form-dot/package.json | 34 +++ .../builds/query-param-form-dot/param.ts | 69 ++++++ .../query-param-form-dot/provide-api.ts | 15 ++ .../query-param-form-dot/query.params.ts | 160 ++++++++++++ .../builds/query-param-form-dot/tsconfig.json | 29 +++ .../builds/query-param-form-dot/variables.ts | 9 + .../app/src/api.query_param_form_dot.spec.ts | 40 +++ 32 files changed, 1368 insertions(+), 1 deletion(-) create mode 100644 bin/configs/typescript-angular-v20-query-param-form-dot.yaml create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.gitignore create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.openapi-generator-ignore create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.openapi-generator/FILES create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.openapi-generator/VERSION create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/README.md create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api.base.service.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api.module.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api/api.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api/default.service.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/configuration.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/encoder.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/git_push.sh create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/index.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/filter.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/item.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/models.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/response.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/ng-package.json create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/package.json create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/param.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/provide-api.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/query.params.ts create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/tsconfig.json create mode 100644 samples/client/others/typescript-angular-v20/builds/query-param-form-dot/variables.ts create mode 100644 samples/client/others/typescript-angular-v20/projects/app/src/api.query_param_form_dot.spec.ts diff --git a/bin/configs/typescript-angular-v20-query-param-form-dot.yaml b/bin/configs/typescript-angular-v20-query-param-form-dot.yaml new file mode 100644 index 000000000000..ff7b3b8d9ada --- /dev/null +++ b/bin/configs/typescript-angular-v20-query-param-form-dot.yaml @@ -0,0 +1,9 @@ +generatorName: typescript-angular +outputDir: samples/client/others/typescript-angular-v20/builds/query-param-form-dot +inputSpec: modules/openapi-generator/src/test/resources/3_0/query-param-form.yaml +templateDir: modules/openapi-generator/src/main/resources/typescript-angular +additionalProperties: + ngVersion: 20.0.0 + npmName: sample-angular-20-0-0-query-param-form-dot + supportsES6: true + useDotNotationForFormObjects: true diff --git a/docs/generators/typescript-angular.md b/docs/generators/typescript-angular.md index e3a8ba54e386..7270a23e5e1f 100644 --- a/docs/generators/typescript-angular.md +++ b/docs/generators/typescript-angular.md @@ -53,6 +53,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |supportsES6|Generate code that conforms to ES6.| |false| |taggedUnions|Use discriminators to create tagged unions instead of extending interfaces.| |false| |tsVersion|The version of typescript compatible with Angular (see ngVersion option).| |null| +|useDotNotationForFormObjects|Use parameter-prefixed dot notation for exploded form query objects instead of the OpenAPI standard unprefixed property names. Enable only for servers requiring this convention.| |false| |useSingleRequestParameter|Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.| |false| |useSquareBracketsInArrayNames|Setting this property to true will add brackets to array attribute names, e.g. my_values[].| |false| |withInterfaces|Setting this property to true will generate interfaces next to the default class implementations.| |false| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java index 37825435176b..41e88007c077 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java @@ -80,6 +80,7 @@ public static enum PROVIDED_IN_LEVEL {none, root, any, platform} public static final String FILE_NAMING = "fileNaming"; public static final String STRING_ENUMS = "stringEnums"; public static final String STRING_ENUMS_DESC = "Generate string enums instead of objects for enum values."; + public static final String USE_DOT_NOTATION_FOR_FORM_OBJECTS = "useDotNotationForFormObjects"; public static final String QUERY_PARAM_OBJECT_FORMAT = "queryParamObjectFormat"; public static final String USE_SQUARE_BRACKETS_IN_ARRAY_NAMES = "useSquareBracketsInArrayNames"; public static final String TS_VERSION = "tsVersion"; @@ -152,6 +153,7 @@ public TypeScriptAngularClientCodegen() { this.cliOptions.add(new CliOption(MODEL_FILE_SUFFIX, "The suffix of the file of the generated model (model.ts).")); this.cliOptions.add(new CliOption(FILE_NAMING, "Naming convention for the output files: 'camelCase', 'kebab-case'.").defaultValue(this.fileNaming)); this.cliOptions.add(new CliOption(STRING_ENUMS, STRING_ENUMS_DESC).defaultValue(String.valueOf(this.stringEnums))); + this.cliOptions.add(CliOption.newBoolean(USE_DOT_NOTATION_FOR_FORM_OBJECTS, "Use parameter-prefixed dot notation for exploded form query objects instead of the OpenAPI standard unprefixed property names. Enable only for servers requiring this convention.", false)); this.cliOptions.add(new CliOption(QUERY_PARAM_OBJECT_FORMAT, "The format for query param objects: 'dot', 'json', 'key'.").defaultValue(this.queryParamObjectFormat.name())); this.cliOptions.add(CliOption.newBoolean(USE_SQUARE_BRACKETS_IN_ARRAY_NAMES, "Setting this property to true will add brackets to array attribute names, e.g. my_values[].", false)); this.cliOptions.add(new CliOption(TS_VERSION, "The version of typescript compatible with Angular (see ngVersion option).")); @@ -306,6 +308,9 @@ public void processOpts() { this.setFileNaming(additionalProperties.get(FILE_NAMING).toString()); } + additionalProperties.put(USE_DOT_NOTATION_FOR_FORM_OBJECTS, additionalProperties.containsKey(USE_DOT_NOTATION_FOR_FORM_OBJECTS) + && convertPropertyToBoolean(USE_DOT_NOTATION_FOR_FORM_OBJECTS)); + if (additionalProperties.containsKey(QUERY_PARAM_OBJECT_FORMAT)) { setQueryParamObjectFormat((String) additionalProperties.get(QUERY_PARAM_OBJECT_FORMAT)); } diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/README.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/README.mustache index afe430da51ce..89bd2b92c89e 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/README.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/README.mustache @@ -183,3 +183,17 @@ new Configuration({ [parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations [style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values [@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander +{{#useDotNotationForFormObjects}} + +## Form query object dot notation + +This client was generated with `useDotNotationForFormObjects=true`. For exploded +form query objects, property names include the parameter name and all parent +properties: `filter = { name: { contains: "Alice" } }` is serialized as +`filter.name.contains=Alice`. Primitive arrays and sets retain repeated keys, +for example `filter.ids=1&filter.ids=2`. + +This is a server-specific convention, not standard OpenAPI form serialization. +The option defaults to false and does not affect non-exploded form parameters, +JSON, deepObject, spaceDelimited or pipeDelimited parameters. +{{/useDotNotationForFormObjects}} diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/api.base.service.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/api.base.service.mustache index ed7a92be8bd2..7d619f606358 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/api.base.service.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/api.base.service.mustache @@ -70,7 +70,7 @@ export class BaseService { if (paramStyle === QueryParamStyle.Form) { if (explode) { Object.keys(value).forEach(k => { - httpParams = this.addToHttpParams(httpParams, k, value[k], paramStyle, explode); + httpParams = this.addToHttpParams(httpParams, {{#useDotNotationForFormObjects}}`${key}.${k}`{{/useDotNotationForFormObjects}}{{^useDotNotationForFormObjects}}k{{/useDotNotationForFormObjects}}, value[k], paramStyle, explode); }); return httpParams; } else { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularClientOptionsProvider.java index 334cb15200ab..d87bd3364651 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularClientOptionsProvider.java @@ -63,6 +63,7 @@ public Map createOptions() { .put(TypeScriptAngularClientCodegen.MODEL_SUFFIX, MODEL_SUFFIX) .put(TypeScriptAngularClientCodegen.MODEL_FILE_SUFFIX, MODEL_FILE_SUFFIX) .put(TypeScriptAngularClientCodegen.FILE_NAMING, FILE_NAMING_VALUE) + .put(TypeScriptAngularClientCodegen.USE_DOT_NOTATION_FOR_FORM_OBJECTS, Boolean.FALSE.toString()) .put(TypeScriptAngularClientCodegen.QUERY_PARAM_OBJECT_FORMAT, QUERY_PARAM_OBJECT_FORMAT_VALUE) .put(TypeScriptAngularClientCodegen.USE_SQUARE_BRACKETS_IN_ARRAY_NAMES, Boolean.FALSE.toString()) .put(TypeScriptAngularClientCodegen.TS_VERSION, TS_VERSION) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java index f7a88faf8346..184176e1c177 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java @@ -477,6 +477,29 @@ public void testEnumAsConst() throws IOException { assertThat(fileContents).doesNotContain(" as Type"); } + @Test + public void testFormObjectDotNotationOption() throws IOException { + for (Object option : new Object[]{null, false, "false", true, "true"}) { + File output = Files.createTempDirectory("angular-form-dot").toFile(); + output.deleteOnExit(); + CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("typescript-angular") + .setInputSpec("src/test/resources/3_0/query-param-form.yaml") + .setOutputDir(output.getAbsolutePath()); + if (option != null) { + configurator.addAdditionalProperty(TypeScriptAngularClientCodegen.USE_DOT_NOTATION_FOR_FORM_OBJECTS, option); + } + new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + String service = Files.readString(output.toPath().resolve("api.base.service.ts")); + if (Boolean.parseBoolean(String.valueOf(option))) { + assertThat(service).contains("this.addToHttpParams(httpParams, `${key}.${k}`, value[k], paramStyle, explode)"); + } else { + assertThat(service).contains("this.addToHttpParams(httpParams, k, value[k], paramStyle, explode)"); + assertThat(service).doesNotContain("`${key}.${k}`"); + } + } + } + @Test public void testDeepObject() throws IOException { // GIVEN diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.gitignore b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.gitignore new file mode 100644 index 000000000000..149b57654723 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.openapi-generator-ignore b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.openapi-generator/FILES b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.openapi-generator/FILES new file mode 100644 index 000000000000..c2509c9e9d2d --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.openapi-generator/FILES @@ -0,0 +1,21 @@ +.gitignore +README.md +api.base.service.ts +api.module.ts +api/api.ts +api/default.service.ts +configuration.ts +encoder.ts +git_push.sh +index.ts +model/filter.ts +model/item.ts +model/models.ts +model/response.ts +ng-package.json +package.json +param.ts +provide-api.ts +query.params.ts +tsconfig.json +variables.ts diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.openapi-generator/VERSION b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.openapi-generator/VERSION new file mode 100644 index 000000000000..32a8cfaceeb9 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.26.0-SNAPSHOT diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/README.md b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/README.md new file mode 100644 index 000000000000..cbcd1ff184d0 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/README.md @@ -0,0 +1,197 @@ +# sample-angular-20-0-0-query-param-form-dot@1.0.0 + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +The version of the OpenAPI document: 1.0.0 + +## Building + +To install the required dependencies and to build the typescript sources run: + +```console +npm install +npm run build +``` + +## Publishing + +First build the package then run `npm publish dist` (don't forget to specify the `dist` folder!) + +## Consuming + +Navigate to the folder of your consuming project and run one of next commands. + +_published:_ + +```console +npm install sample-angular-20-0-0-query-param-form-dot@1.0.0 --save +``` + +_without publishing (not recommended):_ + +```console +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save +``` + +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: + +```console +npm link +``` + +In your project: + +```console +npm link sample-angular-20-0-0-query-param-form-dot +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue for a solution / workaround. +Published packages are not effected by this issue. + +### General usage + +In your Angular project: + +```typescript + +import { ApplicationConfig } from '@angular/core'; +import { provideHttpClient } from '@angular/common/http'; +import { provideApi } from 'sample-angular-20-0-0-query-param-form-dot'; + +export const appConfig: ApplicationConfig = { + providers: [ + // ... + provideHttpClient(), + provideApi() + ], +}; +``` + +**NOTE** +If you're still using `AppModule` and haven't [migrated](https://angular.dev/reference/migrations/standalone) yet, you can still import an Angular module: +```typescript +import { ApiModule } from 'sample-angular-20-0-0-query-param-form-dot'; +``` + +If different from the generated base path, during app bootstrap, you can provide the base path to your service. + +```typescript +import { ApplicationConfig } from '@angular/core'; +import { provideHttpClient } from '@angular/common/http'; +import { provideApi } from 'sample-angular-20-0-0-query-param-form-dot'; + +export const appConfig: ApplicationConfig = { + providers: [ + // ... + provideHttpClient(), + provideApi('http://localhost:9999') + ], +}; +``` + +```typescript +// with a custom configuration +import { ApplicationConfig } from '@angular/core'; +import { provideHttpClient } from '@angular/common/http'; +import { provideApi } from 'sample-angular-20-0-0-query-param-form-dot'; + +export const appConfig: ApplicationConfig = { + providers: [ + // ... + provideHttpClient(), + provideApi({ + withCredentials: true, + username: 'user', + password: 'password' + }) + ], +}; +``` + +```typescript +// with factory building a custom configuration +import { ApplicationConfig } from '@angular/core'; +import { provideHttpClient } from '@angular/common/http'; +import { provideApi, Configuration } from 'sample-angular-20-0-0-query-param-form-dot'; + +export const appConfig: ApplicationConfig = { + providers: [ + // ... + provideHttpClient(), + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration({ + basePath: 'http://localhost:9999', + withCredentials: true, + username: authService.getUsername(), + password: authService.getPassword(), + }), + deps: [AuthService], + multi: false + } + ], +}; +``` + +### Using multiple OpenAPI files / APIs + +In order to use multiple APIs generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: + +```typescript +import { provideApi as provideUserApi } from 'my-user-api-path'; +import { provideApi as provideAdminApi } from 'my-admin-api-path'; +import { HttpClientModule } from '@angular/common/http'; +import { environment } from '../environments/environment'; + +export const appConfig: ApplicationConfig = { + providers: [ + // ... + provideHttpClient(), + provideUserApi(environment.basePath), + provideAdminApi(environment.basePath), + ], +}; +``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: + +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander + +## Form query object dot notation + +This client was generated with `useDotNotationForFormObjects=true`. For exploded +form query objects, property names include the parameter name and all parent +properties: `filter = { name: { contains: "Alice" } }` is serialized as +`filter.name.contains=Alice`. Primitive arrays and sets retain repeated keys, +for example `filter.ids=1&filter.ids=2`. + +This is a server-specific convention, not standard OpenAPI form serialization. +The option defaults to false and does not affect non-exploded form parameters, +JSON, deepObject, spaceDelimited or pipeDelimited parameters. diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api.base.service.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api.base.service.ts new file mode 100644 index 000000000000..d3a014917d12 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api.base.service.ts @@ -0,0 +1,96 @@ +/** + * query-param-form-with-array + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http'; +import { CustomHttpParameterCodec } from './encoder'; +import { Configuration } from './configuration'; +import { OpenApiHttpParams, QueryParamStyle, concatHttpParamsObject} from './query.params'; + +export class BaseService { + protected basePath = 'http://localhost'; + public defaultHeaders = new HttpHeaders(); + public configuration: Configuration; + public encoder: HttpParameterCodec; + + constructor(basePath?: string|string[], configuration?: Configuration) { + this.configuration = configuration || new Configuration(); + if (typeof this.configuration.basePath !== 'string') { + const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined; + if (firstBasePath != undefined) { + basePath = firstBasePath; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + protected canConsumeForm(consumes: string[]): boolean { + return consumes.indexOf('multipart/form-data') !== -1; + } + + protected addToHttpParams(httpParams: OpenApiHttpParams, key: string, value: any | null | undefined, paramStyle: QueryParamStyle, explode: boolean): OpenApiHttpParams { + if (value === null || value === undefined) { + return httpParams; + } + + if (paramStyle === QueryParamStyle.DeepObject) { + if (typeof value !== 'object') { + throw Error(`An object must be provided for key ${key} as it is a deep object`); + } + + return Object.keys(value as Record).reduce( + (hp, k) => hp.append(`${key}[${k}]`, value[k]), + httpParams, + ); + } else if (paramStyle === QueryParamStyle.Json) { + return httpParams.append(key, JSON.stringify(value)); + } else { + // Form-style, SpaceDelimited or PipeDelimited + + if (Object(value) !== value) { + // If it is a primitive type, add its string representation + return httpParams.append(key, value.toString()); + } else if (value instanceof Date) { + return httpParams.append(key, value.toISOString()); + } else if (Array.isArray(value) || value instanceof Set) { + // Otherwise, if it's an array or set, add each element. + const array = Array.isArray(value) ? value : Array.from(value); + if (paramStyle === QueryParamStyle.Form) { + return httpParams.set(key, array, {explode: explode, delimiter: ','}); + } else if (paramStyle === QueryParamStyle.SpaceDelimited) { + return httpParams.set(key, array, {explode: explode, delimiter: ' '}); + } else { + // PipeDelimited + return httpParams.set(key, array, {explode: explode, delimiter: '|'}); + } + } else { + // Otherwise, if it's an object, add each field. + if (paramStyle === QueryParamStyle.Form) { + if (explode) { + Object.keys(value).forEach(k => { + httpParams = this.addToHttpParams(httpParams, `${key}.${k}`, value[k], paramStyle, explode); + }); + return httpParams; + } else { + return concatHttpParamsObject(httpParams, key, value, ','); + } + } else if (paramStyle === QueryParamStyle.SpaceDelimited) { + return concatHttpParamsObject(httpParams, key, value, ' '); + } else { + // PipeDelimited + return concatHttpParamsObject(httpParams, key, value, '|'); + } + } + } + } +} diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api.module.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api.module.ts new file mode 100644 index 000000000000..58d341fbd2e5 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api.module.ts @@ -0,0 +1,30 @@ +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; +import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; + + +@NgModule({ + imports: [], + declarations: [], + exports: [], + providers: [] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } + } +} diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api/api.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api/api.ts new file mode 100644 index 000000000000..8e76619647f4 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api/api.ts @@ -0,0 +1,3 @@ +export * from './default.service'; +import { DefaultService } from './default.service'; +export const APIS = [DefaultService]; diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api/default.service.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api/default.service.ts new file mode 100644 index 000000000000..7359f92de421 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api/default.service.ts @@ -0,0 +1,228 @@ +/** + * query-param-form-with-array + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpContext + } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import { OpenApiHttpParams, QueryParamStyle } from '../query.params'; + +// @ts-ignore +import { Filter } from '../model/filter'; +// @ts-ignore +import { Response } from '../model/response'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + + + +@Injectable({ + providedIn: 'root' +}) +export class DefaultService extends BaseService { + + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); + } + + /** + * @endpoint get /search_explode + * @param ids Ids + * @param filter Filter + * @param country Filter + * @param tags Tags + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + * @param options additional options + */ + public searchExplode(ids?: Array, filter?: Filter, country?: string, tags?: Set, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchExplode(ids?: Array, filter?: Filter, country?: string, tags?: Set, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchExplode(ids?: Array, filter?: Filter, country?: string, tags?: Set, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchExplode(ids?: Array, filter?: Filter, country?: string, tags?: Set, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new OpenApiHttpParams(this.encoder); + + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + 'ids', + ids, + QueryParamStyle.Form, + true, + ); + + + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + 'filter', + filter, + QueryParamStyle.Form, + true, + ); + + + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + 'country', + country, + QueryParamStyle.Form, + true, + ); + + + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + 'tags', + tags, + QueryParamStyle.Form, + true, + ); + + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/search_explode`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters.toHttpParams(), + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * @endpoint get /search_not_explode + * @param ids Ids + * @param filter Filter + * @param country Filter + * @param tags Tags + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + * @param options additional options + */ + public searchNotExplode(ids?: Array, filter?: Filter, country?: string, tags?: Set, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchNotExplode(ids?: Array, filter?: Filter, country?: string, tags?: Set, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchNotExplode(ids?: Array, filter?: Filter, country?: string, tags?: Set, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchNotExplode(ids?: Array, filter?: Filter, country?: string, tags?: Set, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new OpenApiHttpParams(this.encoder); + + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + 'ids', + ids, + QueryParamStyle.Form, + false, + ); + + + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + 'filter', + filter, + QueryParamStyle.Form, + false, + ); + + + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + 'country', + country, + QueryParamStyle.Form, + false, + ); + + + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + 'tags', + tags, + QueryParamStyle.Form, + false, + ); + + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/search_not_explode`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters.toHttpParams(), + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/configuration.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/configuration.ts new file mode 100644 index 000000000000..eb876c1c672d --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/configuration.ts @@ -0,0 +1,185 @@ +import { HttpHeaders, HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; +import { OpenApiHttpParams } from './query.params'; + +export interface ConfigurationParameters { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

+ * See {@link README.md} for more details + *

+ */ + encodeParam?: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; +} + +export class Configuration { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

+ * See {@link README.md} for more details + *

+ */ + encodeParam: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + +constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder, password, username, withCredentials }: ConfigurationParameters = {}) { + if (apiKeys) { + this.apiKeys = apiKeys; + } + if (username !== undefined) { + this.username = username; + } + if (password !== undefined) { + this.password = password; + } + if (accessToken !== undefined) { + this.accessToken = accessToken; + } + if (basePath !== undefined) { + this.basePath = basePath; + } + if (withCredentials !== undefined) { + this.withCredentials = withCredentials; + } + if (encoder) { + this.encoder = encoder; + } + this.encodeParam = encodeParam ?? (param => this.defaultEncodeParam(param)); + this.credentials = credentials ?? {}; + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = /^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$/i; + return mime !== null && jsonMime.test(mime); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } + + public addCredentialToHeaders(credentialKey: string, headerName: string, headers: HttpHeaders, prefix?: string): HttpHeaders { + const value = this.lookupCredential(credentialKey); + return value + ? headers.set(headerName, (prefix ?? '') + value) + : headers; + } + + public addCredentialToQuery(credentialKey: string, paramName: string, query: OpenApiHttpParams): OpenApiHttpParams { + const value = this.lookupCredential(credentialKey); + return value + ? query.set(paramName, value) + : query; + } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' && param.value instanceof Date + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } +} diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/encoder.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/encoder.ts new file mode 100644 index 000000000000..af4523543e6c --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/encoder.ts @@ -0,0 +1,35 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} + +export class IdentityHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return k; + } + encodeValue(v: string): string { + return v; + } + decodeKey(k: string): string { + return k; + } + decodeValue(v: string): string { + return v; + } +} diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/git_push.sh b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/git_push.sh new file mode 100644 index 000000000000..a35991cd51a1 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/git_push.sh @@ -0,0 +1,54 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ -z "${git_host}" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \${git_host} to ${git_host}" +fi + +if [ -z "${git_user_id}" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \${git_user_id} to ${git_user_id}" +fi + +if [ -z "${git_repo_id}" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \${git_repo_id} to ${git_repo_id}" +fi + +if [ -z "${release_note}" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \${release_note} to ${release_note}" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "${release_note}" + +# Sets the new remote +if [ -z "$(git remote)" ]; then # git remote not defined + if [ -z "${GIT_TOKEN:-}" ]; then + echo "[INFO] \${GIT_TOKEN} (environment variable) is not set. Using the git credential in your environment." + git remote add origin "https://${git_host}/${git_user_id}/${git_repo_id}.git" + else + git remote add origin "https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git" + fi +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/index.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/index.ts new file mode 100644 index 000000000000..02cb7d437fbf --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/index.ts @@ -0,0 +1,7 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; +export * from './provide-api'; +export * from './param'; diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/filter.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/filter.ts new file mode 100644 index 000000000000..8d3e6c96fda2 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/filter.ts @@ -0,0 +1,23 @@ +/** + * query-param-form-with-array + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface Filter { + /** + * The name + */ + name?: string; + /** + * The age + */ + age?: number; + nicknames?: Array; +} + diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/item.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/item.ts new file mode 100644 index 000000000000..578edeb69783 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/item.ts @@ -0,0 +1,23 @@ +/** + * query-param-form-with-array + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface Item { + /** + * The name + */ + name: string; + /** + * The age + */ + age: number; + nicknames: Array; +} + diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/models.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/models.ts new file mode 100644 index 000000000000..b4f119f15d97 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/models.ts @@ -0,0 +1,3 @@ +export * from './filter'; +export * from './item'; +export * from './response'; diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/response.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/response.ts new file mode 100644 index 000000000000..02c41ae031dc --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/model/response.ts @@ -0,0 +1,19 @@ +/** + * query-param-form-with-array + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Item } from './item'; + + +export interface Response { + /** + * Array of items. + */ + items: Array; +} + diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/ng-package.json b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/ng-package.json new file mode 100644 index 000000000000..3b17900dc9c3 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/ng-package.json @@ -0,0 +1,6 @@ +{ + "$schema": "./node_modules/ng-packagr/ng-package.schema.json", + "lib": { + "entryFile": "index.ts" + } +} diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/package.json b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/package.json new file mode 100644 index 000000000000..a9b610ac20ab --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/package.json @@ -0,0 +1,34 @@ +{ + "name": "sample-angular-20-0-0-query-param-form-dot", + "version": "1.0.0", + "description": "OpenAPI client for sample-angular-20-0-0-query-param-form-dot", + "author": "OpenAPI-Generator Contributors", + "repository": { + "type": "git", + "url": "https://github.com/GIT_USER_ID/GIT_REPO_ID.git" + }, + "keywords": [ + "openapi-client", + "openapi-generator" + ], + "license": "Unlicense", + "scripts": { + "prepare": "npm run build", + "build": "ng-packagr -p ng-package.json" + }, + "peerDependencies": { + "@angular/core": "^20.0.0", + "rxjs": "^7.4.0" + }, + "devDependencies": { + "@angular/common": "^20.0.0", + "@angular/compiler": "^20.0.0", + "@angular/compiler-cli": "^20.0.0", + "@angular/core": "^20.0.0", + "@angular/platform-browser": "^20.0.0", + "ng-packagr": "^20.0.0", + "reflect-metadata": "^0.1.3", + "rxjs": "^7.4.0", + "typescript": ">=5.8.0 <5.9.0", + "zone.js": "^0.15.0" + }} diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/param.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/param.ts new file mode 100644 index 000000000000..78a2d20a6433 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/provide-api.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/provide-api.ts new file mode 100644 index 000000000000..19c762acdfe0 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/provide-api.ts @@ -0,0 +1,15 @@ +import { EnvironmentProviders, makeEnvironmentProviders } from "@angular/core"; +import { Configuration, ConfigurationParameters } from './configuration'; +import { BASE_PATH } from './variables'; + +// Returns the service class providers, to be used in the [ApplicationConfig](https://angular.dev/api/core/ApplicationConfig). +export function provideApi(configOrBasePath: string | ConfigurationParameters): EnvironmentProviders { + return makeEnvironmentProviders([ + typeof configOrBasePath === "string" + ? { provide: BASE_PATH, useValue: configOrBasePath } + : { + provide: Configuration, + useValue: new Configuration({ ...configOrBasePath }), + }, + ]); +} \ No newline at end of file diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/query.params.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/query.params.ts new file mode 100644 index 000000000000..4076c1140c83 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/query.params.ts @@ -0,0 +1,160 @@ +import { HttpParams, HttpParameterCodec } from '@angular/common/http'; +import { CustomHttpParameterCodec, IdentityHttpParameterCodec } from './encoder'; + +export enum QueryParamStyle { + Json, + Form, + DeepObject, + SpaceDelimited, + PipeDelimited, +} + +export type Delimiter = "," | " " | "|" | "\t"; + +export interface ParamOptions { + /** When true, serialized as multiple repeated key=value pairs. When false, serialized as a single key with joined values using `delimiter`. */ + explode?: boolean; + /** Delimiter used when explode=false. The delimiter itself is inserted unencoded between encoded values. */ + delimiter?: Delimiter; +} + +interface ParamEntry { + values: string[]; + options: Required; +} + +export class OpenApiHttpParams { + private params: Map = new Map(); + private defaults: Required; + private encoder: HttpParameterCodec; + + /** + * @param encoder Parameter serializer + * @param defaults Global defaults used when a specific parameter has no explicit options. + * By OpenAPI default, explode is true for query params with style=form. + */ + constructor(encoder?: HttpParameterCodec, defaults?: { explode?: boolean; delimiter?: Delimiter }) { + this.encoder = encoder || new CustomHttpParameterCodec(); + this.defaults = { + explode: defaults?.explode ?? true, + delimiter: defaults?.delimiter ?? ",", + }; + } + + private resolveOptions(local?: ParamOptions): Required { + return { + explode: local?.explode ?? this.defaults.explode, + delimiter: local?.delimiter ?? this.defaults.delimiter, + }; + } + + /** + * Replace the parameter's values and (optionally) its options. + * Options are stored per-parameter (not global). + */ + set(key: string, values: string[] | string, options?: ParamOptions): this { + const arr = Array.isArray(values) ? values.slice() : [values]; + const opts = this.resolveOptions(options); + this.params.set(key, {values: arr, options: opts}); + return this; + } + + /** + * Append a single value to the parameter. If the parameter didn't exist it will be created + * and use resolved options (global defaults merged with any provided options). + */ + append(key: string, value: string, options?: ParamOptions): this { + const entry = this.params.get(key); + if (entry) { + // If new options provided, override the stored options for subsequent serialization + if (options) { + entry.options = this.resolveOptions({...entry.options, ...options}); + } + entry.values.push(value); + } else { + this.set(key, [value], options); + } + return this; + } + + /** + * Serialize to a query string according to per-parameter OpenAPI options. + * - If explode=true for that parameter → repeated key=value pairs (each value encoded). + * - If explode=false for that parameter → single key=value where values are individually encoded + * and joined using the configured delimiter. The delimiter character is inserted AS-IS + * (not percent-encoded). + */ + toString(): string { + const records = this.toRecord(); + const parts: string[] = []; + + for (const key in records) { + parts.push(`${key}=${records[key]}`); + } + + return parts.join("&"); + } + + /** + * Return parameters as a plain record. + * - If a parameter has exactly one value, returns that value directly. + * - If a parameter has multiple values, returns a readonly array of values. + */ + toRecord(): Record> { + const parts: Record> = {}; + + for (const [key, entry] of this.params.entries()) { + const encodedKey = this.encoder.encodeKey(key); + + if (entry.options.explode) { + parts[encodedKey] = entry.values.map((v) => this.encoder.encodeValue(v)); + } else { + const encodedValues = entry.values.map((v) => this.encoder.encodeValue(v)); + + // join with the delimiter *unencoded* + parts[encodedKey] = encodedValues.join(entry.options.delimiter); + } + } + + return parts; + } + + /** + * Return an Angular's HttpParams with an identity parameter codec as the parameters are already encoded. + */ + toHttpParams(): HttpParams { + const records = this.toRecord(); + + let httpParams = new HttpParams({encoder: new IdentityHttpParameterCodec()}); + + return httpParams.appendAll(records); + } +} + +export function concatHttpParamsObject(httpParams: OpenApiHttpParams, key: string, item: { + [index: string]: any +}, delimiter: Delimiter): OpenApiHttpParams { + let keyAndValues: string[] = []; + + for (const k in item) { + keyAndValues.push(k); + + const value = item[k]; + + if (Array.isArray(value)) { + keyAndValues.push(...value.map(convertToString)); + } else { + keyAndValues.push(convertToString(value)); + } + } + + return httpParams.set(key, keyAndValues, {explode: false, delimiter: delimiter}); +} + +function convertToString(value: any): string { + if (value instanceof Date) { + return value.toISOString(); + } else { + return value.toString(); + } +} diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/tsconfig.json b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/tsconfig.json new file mode 100644 index 000000000000..b3049e9eee69 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "target": "es6", + "module": "es6", + "moduleResolution": "node", + "removeComments": true, + "strictNullChecks": true, + "exactOptionalPropertyTypes": true, + "sourceMap": true, + "outDir": "./dist", + "noLib": false, + "declaration": true, + "lib": [ "es6", "dom" ], + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "node_modules", + "dist" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts" + ] +} diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/variables.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/variables.ts new file mode 100644 index 000000000000..6fe58549f395 --- /dev/null +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/variables.ts @@ -0,0 +1,9 @@ +import { InjectionToken } from '@angular/core'; + +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/client/others/typescript-angular-v20/projects/app/src/api.query_param_form_dot.spec.ts b/samples/client/others/typescript-angular-v20/projects/app/src/api.query_param_form_dot.spec.ts new file mode 100644 index 000000000000..f99c3d3a917f --- /dev/null +++ b/samples/client/others/typescript-angular-v20/projects/app/src/api.query_param_form_dot.spec.ts @@ -0,0 +1,40 @@ +import {BaseService as DotBaseService} from '../../../builds/query-param-form-dot/api.base.service'; +import {OpenApiHttpParams, QueryParamStyle} from '../../../builds/query-param-form-dot/query.params'; + +class QuerySerializer extends DotBaseService { + serialize(value: unknown, style = QueryParamStyle.Form, explode = true): string { + return this.addToHttpParams(new OpenApiHttpParams(), 'filter', value, style, explode).toHttpParams().toString(); + } +} + +describe('Opt-in form query object dot notation', () => { + const serializer = new QuerySerializer(); + + it('preserves the parameter name and nested paths without collisions', () => { + expect(serializer.serialize({name: 'Alice', first: {id: 1}, second: {id: 2}})) + .toBe('filter.name=Alice&filter.first.id=1&filter.second.id=2'); + }); + + it('preserves repeated primitive arrays and sets', () => { + expect(serializer.serialize({ids: [1, 2], tags: new Set(['a', 'b'])})) + .toBe('filter.ids=1&filter.ids=2&filter.tags=a&filter.tags=b'); + }); + + it('preserves dates, escaping, false and zero and omits nullish values', () => { + expect(serializer.serialize({start: new Date('2026-01-02T03:04:05Z'), name: 'A & B', zero: 0, no: false, missing: null, absent: undefined})) + .toBe('filter.start=2026-01-02T03%3A04%3A05.000Z&filter.name=A%20%26%20B&filter.zero=0&filter.no=false'); + }); + + it('does not change top-level primitives or arrays', () => { + expect(serializer.serialize('Alice')).toBe('filter=Alice'); + expect(serializer.serialize([1, 2])).toBe('filter=1&filter=2'); + }); + + it('does not change non-exploded form objects or other styles', () => { + expect(serializer.serialize({name: 'Alice'}, QueryParamStyle.Form, false)).toBe('filter=name,Alice'); + expect(serializer.serialize({name: 'Alice'}, QueryParamStyle.DeepObject)).toBe('filter%5Bname%5D=Alice'); + expect(serializer.serialize({name: 'Alice'}, QueryParamStyle.Json)).toBe('filter=%7B%22name%22%3A%22Alice%22%7D'); + expect(serializer.serialize([1, 2], QueryParamStyle.SpaceDelimited, false)).toBe('filter=1 2'); + expect(serializer.serialize([1, 2], QueryParamStyle.PipeDelimited, false)).toBe('filter=1|2'); + }); +}); From e213a48ca123c4cd7f878cf1d1f5f22ecaf9e87d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tristan=20Spr=C3=B6=C3=9Fer?= Date: Thu, 1 Oct 2026 17:35:23 +0200 Subject: [PATCH 2/2] Regenerate Angular form dot notation sample after master merge --- .../builds/query-param-form-dot/README.md | 10 +++++++ .../query-param-form-dot/api.base.service.ts | 26 ++++++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/README.md b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/README.md index cbcd1ff184d0..b9c3756e6a17 100644 --- a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/README.md +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/README.md @@ -195,3 +195,13 @@ for example `filter.ids=1&filter.ids=2`. This is a server-specific convention, not standard OpenAPI form serialization. The option defaults to false and does not affect non-exploded form parameters, JSON, deepObject, spaceDelimited or pipeDelimited parameters. + +## Deep-object query parameters + +For `style: deepObject`, nested objects are serialized using bracket notation, for example +`filter[name][contains]=Alice`. Arrays and sets use zero-based indices, for example +`filter[sort][0][field]=name`. Dates are serialized as ISO strings; null and undefined +values and empty containers are omitted. + +OpenAPI only specifies deepObject serialization for flat objects. This recursive +encoding is a generator extension and requires a server that accepts bracket notation. diff --git a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api.base.service.ts b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api.base.service.ts index d3a014917d12..497c080d6fd7 100644 --- a/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api.base.service.ts +++ b/samples/client/others/typescript-angular-v20/builds/query-param-form-dot/api.base.service.ts @@ -49,7 +49,7 @@ export class BaseService { } return Object.keys(value as Record).reduce( - (hp, k) => hp.append(`${key}[${k}]`, value[k]), + (hp, k) => this.addToHttpParamsDeepObject(hp, `${key}[${k}]`, value[k]), httpParams, ); } else if (paramStyle === QueryParamStyle.Json) { @@ -93,4 +93,28 @@ export class BaseService { } } } + + /** + * Nested deepObject values are an extension to OpenAPI's flat-object serialization. + * Object properties use bracket notation; array and set elements use numeric indices. + */ + private addToHttpParamsDeepObject(httpParams: OpenApiHttpParams, key: string, value: any): OpenApiHttpParams { + if (value === null || value === undefined) { + return httpParams; + } else if (value instanceof Date) { + return httpParams.append(key, value.toISOString()); + } else if (Array.isArray(value) || value instanceof Set) { + const array = Array.isArray(value) ? value : Array.from(value); + return array.reduce( + (hp, item, index) => this.addToHttpParamsDeepObject(hp, `${key}[${index}]`, item), + httpParams, + ); + } else if (typeof value === 'object') { + return Object.keys(value).reduce( + (hp, k) => this.addToHttpParamsDeepObject(hp, `${key}[${k}]`, value[k]), + httpParams, + ); + } + return httpParams.append(key, value.toString()); + } }