From 84ed5fae57f239185af8d199d7b0561dbf52acb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9F=9A=80=20Jack?= Date: Wed, 30 Oct 2024 15:13:13 +1100 Subject: [PATCH 1/2] fix(type-safe-api): fix named composite models and composite model types Smithy uses the `title` field in OpenAPI to name composite models (all-of, one-of, any-of), which OpenAPI generator also used to produce more readable generated code. This change updates to use the title to name composite models if present for parity with OpenAPI generator. Additionally, nested composite model properties were typed as `any`. Since we know that we always hoist and generate a type for composite models, we use the model name as the type for these. --- .../type-safe-api/generators/generate-next.ts | 17 +- .../test/resources/specs/edge-cases.yaml | 41 +- .../__snapshots__/java.test.ts.snap | 4289 +++++++++++++---- .../__snapshots__/python.test.ts.snap | 2196 +++++++-- .../__snapshots__/typescript.test.ts.snap | 601 ++- 5 files changed, 5647 insertions(+), 1497 deletions(-) diff --git a/packages/type-safe-api/scripts/type-safe-api/generators/generate-next.ts b/packages/type-safe-api/scripts/type-safe-api/generators/generate-next.ts index b4fcba49b..b55d3282a 100755 --- a/packages/type-safe-api/scripts/type-safe-api/generators/generate-next.ts +++ b/packages/type-safe-api/scripts/type-safe-api/generators/generate-next.ts @@ -1,6 +1,7 @@ /*! Copyright [Amazon.com](http://amazon.com/), Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ import * as fs from "fs"; +import * as util from "util"; import SwaggerParser from "@apidevtools/swagger-parser"; import { parse } from "ts-command-line-args"; import * as ejs from "ejs"; @@ -359,6 +360,10 @@ const toTypeScriptType = (property: parseOpenapi.Model): string => { return `Array<${property.link && property.link.export !== "enum" ? toTypeScriptType(property.link) : property.type}>`; case "dictionary": return `{ [key: string]: ${property.link && property.link.export !== "enum" ? toTypeScriptType(property.link) : property.type}; }`; + case "one-of": + case "any-of": + case "all-of": + return property.name; default: return property.type; } @@ -412,6 +417,10 @@ const toJavaType = (property: parseOpenapi.Model): string => { return `${property.uniqueItems ? 'Set' : 'List'}<${property.link && property.link.export !== "enum" ? toJavaType(property.link) : property.type}>`; case "dictionary": return `Map`; + case "one-of": + case "any-of": + case "all-of": + return property.name; default: // "any" has export = interface if (PRIMITIVE_TYPES.has(property.type)) { @@ -461,6 +470,10 @@ const toPythonType = (property: parseOpenapi.Model): string => { return `List[${property.link && property.link.export !== "enum" ? toPythonType(property.link) : property.type}]`; case "dictionary": return `Dict[str, ${property.link && property.link.export !== "enum" ? toPythonType(property.link) : property.type}]`; + case "one-of": + case "any-of": + case "all-of": + return property.name; default: // "any" has export = interface if (PRIMITIVE_TYPES.has(property.type)) { @@ -649,7 +662,7 @@ const filterInlineCompositeSchemas = (schemas: (OpenAPIV3.SchemaObject | OpenAPI let inlineSchemaIndex = 0; return schemas.flatMap((s, i) => { if (hasSubSchemasToVisit(s)) { - const subSchema: SubSchema = { nameParts: [...nameParts, `${namePartPrefix}${inlineSchemaIndex === 0 ? '' : inlineSchemaIndex}`], schema: s, prop: `${prop}.[${i}]` }; + const subSchema: SubSchema = { nameParts: s.title ? [_upperFirst(_camelCase(s.title))] : [...nameParts, `${namePartPrefix}${inlineSchemaIndex === 0 ? '' : inlineSchemaIndex}`], schema: s, prop: `${prop}.[${i}]` }; inlineSchemaIndex++; return [subSchema]; } @@ -1034,7 +1047,7 @@ export default async (argv: string[], rootScriptDir: string) => { const data = await buildData(spec, JSON.parse(args.metadata ?? '{}')); if (args.printData) { - console.log(JSON.stringify(data, null, 2)); + console.log(util.inspect(data, { depth: 100 })); } // Read all .ejs files in each template directory diff --git a/packages/type-safe-api/test/resources/specs/edge-cases.yaml b/packages/type-safe-api/test/resources/specs/edge-cases.yaml index 0e430b00b..31aa20015 100644 --- a/packages/type-safe-api/test/resources/specs/edge-cases.yaml +++ b/packages/type-safe-api/test/resources/specs/edge-cases.yaml @@ -118,6 +118,26 @@ paths: string required: - someProperty + /named-one-of: + post: + operationId: namedOneOf + responses: + 200: + description: ok + content: + application/json: + schema: + $ref: "#/components/schemas/NamedOneOfUnion" + /array-of-one-ofs: + post: + operationId: arrayOfOneOfs + responses: + 200: + description: ok + content: + application/json: + schema: + $ref: "#/components/schemas/ArrayOfOneOfs" components: schemas: MyEnum: @@ -125,4 +145,23 @@ components: enum: - one - two - - three \ No newline at end of file + - three + NamedOneOfUnion: + oneOf: + - type: object + title: namedOneOf + properties: + foo: + type: string + - type: object + title: anotherNamedOneOf + properties: + bar: + type: string + ArrayOfOneOfs: + type: object + properties: + oneOfs: + type: array + items: + $ref: "#/components/schemas/NamedOneOfUnion" diff --git a/packages/type-safe-api/test/scripts/generators/__snapshots__/java.test.ts.snap b/packages/type-safe-api/test/scripts/generators/__snapshots__/java.test.ts.snap index 5d196168a..9b11037d2 100644 --- a/packages/type-safe-api/test/scripts/generators/__snapshots__/java.test.ts.snap +++ b/packages/type-safe-api/test/scripts/generators/__snapshots__/java.test.ts.snap @@ -30333,29 +30333,41 @@ src/main/java/test/test/runtime/api/handlers/RequestInput.java src/main/java/test/test/runtime/api/handlers/ChainedRequestInput.java src/main/java/test/test/runtime/api/handlers/InterceptorWarmupChainedRequestInput.java src/main/java/test/test/runtime/api/handlers/InterceptorWithWarmup.java +src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsResponse.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersResponse.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumResponse.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyResponse.java +src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfResponse.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsResponse.java +src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfs200Response.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParameters200Response.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnum200Response.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody204Response.java +src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOf200Response.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords200Response.java +src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsRequestParameters.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersRequestParameters.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestParameters.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestParameters.java +src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestParameters.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsRequestParameters.java +src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsInput.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersInput.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumInput.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyInput.java +src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfInput.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsInput.java +src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsRequestInput.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersRequestInput.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestInput.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestInput.java +src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestInput.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsRequestInput.java +src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfs.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParameters.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnum.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody.java +src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOf.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords.java src/main/java/test/test/runtime/api/handlers/HandlerRouter.java src/main/java/test/test/runtime/api/interceptors/TryCatchInterceptor.java @@ -30386,10 +30398,14 @@ src/main/java/test/test/runtime/ServerConfiguration.java src/main/java/test/test/runtime/ServerVariable.java src/main/java/test/test/runtime/StringUtil.java src/main/java/test/test/runtime/model/AbstractOpenApiSchema.java +src/main/java/test/test/runtime/model/AnotherNamedOneOf.java +src/main/java/test/test/runtime/model/ArrayOfOneOfs.java src/main/java/test/test/runtime/model/InlineEnum200Response.java src/main/java/test/test/runtime/model/InlineEnum200ResponseCategoryEnum.java src/main/java/test/test/runtime/model/InlineRequestBodyRequestContent.java -src/main/java/test/test/runtime/model/MyEnum.java", +src/main/java/test/test/runtime/model/MyEnum.java +src/main/java/test/test/runtime/model/NamedOneOf.java +src/main/java/test/test/runtime/model/NamedOneOfUnion.java", "src/main/java/test/test/runtime/ApiCallback.java": "/* * Edge Cases * @@ -32456,8 +32472,12 @@ public class JSON { gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AnotherNamedOneOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.ArrayOfOneOfs.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.InlineEnum200Response.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.InlineRequestBodyRequestContent.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.NamedOneOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.NamedOneOfUnion.CustomTypeAdapterFactory()); gson = gsonBuilder.create(); } @@ -33158,9 +33178,11 @@ import java.io.IOException; import java.math.BigDecimal; import java.io.File; +import test.test.runtime.model.ArrayOfOneOfs; import test.test.runtime.model.InlineEnum200Response; import test.test.runtime.model.InlineRequestBodyRequestContent; import test.test.runtime.model.MyEnum; +import test.test.runtime.model.NamedOneOfUnion; import java.lang.reflect.Type; import java.util.ArrayList; @@ -33206,6 +33228,151 @@ public class DefaultApi { this.localCustomBaseUrl = customBaseUrl; } + private okhttp3.Call arrayOfOneOfsCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/array-of-one-ofs"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + + @SuppressWarnings("rawtypes") + private okhttp3.Call arrayOfOneOfsValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return arrayOfOneOfsCall(_callback); + + } + + private ApiResponse arrayOfOneOfsWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = arrayOfOneOfsValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + + private okhttp3.Call arrayOfOneOfsAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = arrayOfOneOfsValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APIarrayOfOneOfsRequest { + + private APIarrayOfOneOfsRequest() { + } + + /** + * Build call for arrayOfOneOfs + * @param _callback ApiCallback API callback + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return arrayOfOneOfsCall(_callback); + } + + /** + * Execute arrayOfOneOfs request + * @return ArrayOfOneOfs + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public ArrayOfOneOfs execute() throws ApiException { + ApiResponse localVarResp = arrayOfOneOfsWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Execute arrayOfOneOfs request with HTTP info returned + * @return ApiResponse<ArrayOfOneOfs> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return arrayOfOneOfsWithHttpInfo(); + } + + /** + * Execute arrayOfOneOfs request (asynchronously) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return arrayOfOneOfsAsync(_callback); + } + } + + /** + * + * + * @return APIarrayOfOneOfsRequest + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + + public APIarrayOfOneOfsRequest arrayOfOneOfs() { + return new APIarrayOfOneOfsRequest(); + } private okhttp3.Call arrayRequestParametersCall(List myStringArrayRequestParams, List myEnumArrayRequestParams, List myIntegerArrayRequestParams, List myLongArrayRequestParams, List myInt32ArrayRequestParams, List myNumberArrayRequestParams, List myFloatArrayRequestParams, List myDoubleArrayRequestParams, MyEnum myEnumRequestParam, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers @@ -33778,6 +33945,151 @@ public class DefaultApi { public APIinlineRequestBodyRequest inlineRequestBody() { return new APIinlineRequestBodyRequest(); } + private okhttp3.Call namedOneOfCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/named-one-of"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + + @SuppressWarnings("rawtypes") + private okhttp3.Call namedOneOfValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return namedOneOfCall(_callback); + + } + + private ApiResponse namedOneOfWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = namedOneOfValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + + private okhttp3.Call namedOneOfAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = namedOneOfValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APInamedOneOfRequest { + + private APInamedOneOfRequest() { + } + + /** + * Build call for namedOneOf + * @param _callback ApiCallback API callback + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return namedOneOfCall(_callback); + } + + /** + * Execute namedOneOf request + * @return NamedOneOfUnion + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public NamedOneOfUnion execute() throws ApiException { + ApiResponse localVarResp = namedOneOfWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Execute namedOneOf request with HTTP info returned + * @return ApiResponse<NamedOneOfUnion> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return namedOneOfWithHttpInfo(); + } + + /** + * Execute namedOneOf request (asynchronously) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return namedOneOfAsync(_callback); + } + } + + /** + * + * + * @return APInamedOneOfRequest + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + + public APInamedOneOfRequest namedOneOf() { + return new APInamedOneOfRequest(); + } private okhttp3.Call reservedKeywordsCall(String with, String _if, String propertyClass, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers @@ -34011,9 +34323,11 @@ public interface HandlerChain { "src/main/java/test/test/runtime/api/handlers/HandlerRouter.java": " package test.test.runtime.api.handlers; +import test.test.runtime.api.handlers.array_of_one_ofs.*; import test.test.runtime.api.handlers.array_request_parameters.*; import test.test.runtime.api.handlers.inline_enum.*; import test.test.runtime.api.handlers.inline_request_body.*; +import test.test.runtime.api.handlers.named_one_of.*; import test.test.runtime.api.handlers.reserved_keywords.*; import test.test.runtime.api.handlers.Handlers; @@ -34032,16 +34346,24 @@ import java.util.Collections; public abstract class HandlerRouter implements RequestHandler { + private static final String arrayOfOneOfsMethodAndPath = Handlers.concatMethodAndPath("POST", "/array-of-one-ofs"); private static final String arrayRequestParametersMethodAndPath = Handlers.concatMethodAndPath("GET", "/array-request-parameters"); private static final String inlineEnumMethodAndPath = Handlers.concatMethodAndPath("GET", "/inline-enum"); private static final String inlineRequestBodyMethodAndPath = Handlers.concatMethodAndPath("POST", "/inline-request-body"); + private static final String namedOneOfMethodAndPath = Handlers.concatMethodAndPath("POST", "/named-one-of"); private static final String reservedKeywordsMethodAndPath = Handlers.concatMethodAndPath("GET", "/reserved-keywords"); + private final ArrayOfOneOfs constructedArrayOfOneOfs; private final ArrayRequestParameters constructedArrayRequestParameters; private final InlineEnum constructedInlineEnum; private final InlineRequestBody constructedInlineRequestBody; + private final NamedOneOf constructedNamedOneOf; private final ReservedKeywords constructedReservedKeywords; + /** + * This method must return your implementation of the ArrayOfOneOfs operation + */ + public abstract ArrayOfOneOfs arrayOfOneOfs(); /** * This method must return your implementation of the ArrayRequestParameters operation */ @@ -34054,15 +34376,21 @@ public abstract class HandlerRouter implements RequestHandler routes = new HashMap<>(); public HandlerRouter() { + this.routes.put(arrayOfOneOfsMethodAndPath, Route.arrayOfOneOfsRoute); this.routes.put(arrayRequestParametersMethodAndPath, Route.arrayRequestParametersRoute); this.routes.put(inlineEnumMethodAndPath, Route.inlineEnumRoute); this.routes.put(inlineRequestBodyMethodAndPath, Route.inlineRequestBodyRoute); + this.routes.put(namedOneOfMethodAndPath, Route.namedOneOfRoute); this.routes.put(reservedKeywordsMethodAndPath, Route.reservedKeywordsRoute); // Handlers are all constructed in the router's constructor such that lambda behaviour remains consistent; // ie resources created in the constructor remain in memory between invocations. // https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html + this.constructedArrayOfOneOfs = this.arrayOfOneOfs(); this.constructedArrayRequestParameters = this.arrayRequestParameters(); this.constructedInlineEnum = this.inlineEnum(); this.constructedInlineRequestBody = this.inlineRequestBody(); + this.constructedNamedOneOf = this.namedOneOf(); this.constructedReservedKeywords = this.reservedKeywords(); } @@ -34102,6 +34434,10 @@ public abstract class HandlerRouter implements RequestHandler> arrayOfOneOfsInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); + arrayOfOneOfsInterceptors.addAll(this.getInterceptors()); + return this.constructedArrayOfOneOfs.handleRequestWithAdditionalInterceptors(event, context, arrayOfOneOfsInterceptors); case arrayRequestParametersRoute: List> arrayRequestParametersInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); arrayRequestParametersInterceptors.addAll(this.getInterceptors()); @@ -34114,6 +34450,10 @@ public abstract class HandlerRouter implements RequestHandler> inlineRequestBodyInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); inlineRequestBodyInterceptors.addAll(this.getInterceptors()); return this.constructedInlineRequestBody.handleRequestWithAdditionalInterceptors(event, context, inlineRequestBodyInterceptors); + case namedOneOfRoute: + List> namedOneOfInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); + namedOneOfInterceptors.addAll(this.getInterceptors()); + return this.constructedNamedOneOf.handleRequestWithAdditionalInterceptors(event, context, namedOneOfInterceptors); case reservedKeywordsRoute: List> reservedKeywordsInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); reservedKeywordsInterceptors.addAll(this.getInterceptors()); @@ -34780,8 +35120,8 @@ public interface Response { Map> getMultiValueHeaders(); } ", - "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParameters.java": " -package test.test.runtime.api.handlers.array_request_parameters; + "src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfs.java": " +package test.test.runtime.api.handlers.array_of_one_ofs; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -34805,50 +35145,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the arrayRequestParameters operation + * Lambda handler wrapper for the arrayOfOneOfs operation */ -public abstract class ArrayRequestParameters implements RequestHandler, Resource { +public abstract class ArrayOfOneOfs implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the arrayRequestParameters operation + * Handle the request for the arrayOfOneOfs operation */ - public abstract ArrayRequestParametersResponse handle(final ArrayRequestParametersRequestInput request); + public abstract ArrayOfOneOfsResponse handle(final ArrayOfOneOfsRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(ArrayRequestParameters.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(ArrayOfOneOfs.class); /** * For more complex interceptors that require instantiation with parameters, you may override this method to * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, * prefer the @Interceptors annotation. */ - public List> getInterceptors() { + public List> getInterceptors() { return Collections.emptyList(); } - private List> getHandlerInterceptors() { - List> interceptors = new ArrayList<>(); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); interceptors.addAll(annotationInterceptors); interceptors.addAll(this.getInterceptors()); return interceptors; } - private HandlerChain buildChain(List> interceptors) { - return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { @Override - public Response next(ChainedRequestInput input) { - return handle(new ArrayRequestParametersRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new ArrayOfOneOfsRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final ArrayRequestParametersInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final ArrayOfOneOfsInput input, final Map interceptorContext) { + return new ChainedRequestInput() { @Override public HandlerChain getChain() { // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining @@ -34867,7 +35207,7 @@ public abstract class ArrayRequestParameters implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -34928,20 +35268,20 @@ public abstract class ArrayRequestParameters implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "arrayRequestParameters"); + interceptorContext.put("operationId", "arrayOfOneOfs"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - ArrayRequestParametersInput input; + ArrayOfOneOfsInput input; try { - input = new ArrayRequestParametersInput(event); + input = new ArrayOfOneOfsInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -34966,8 +35306,8 @@ public abstract class ArrayRequestParameters implements RequestHandler headers; private final Map> multiValueHeaders; - private ArrayRequestParameters200Response(final Map headers, final Map> multiValueHeaders) { - - this.body = ""; + private ArrayOfOneOfs200Response(final ArrayOfOneOfs body, final Map headers, final Map> multiValueHeaders) { + this.typedBody = body; + this.body = body.toJson(); this.headers = headers; this.multiValueHeaders = multiValueHeaders; } @@ -35009,6 +35349,9 @@ public class ArrayRequestParameters200Response extends RuntimeException implemen return this.body; } + public ArrayOfOneOfs getTypedBody() { + return this.typedBody; + } @Override public Map getHeaders() { @@ -35021,29 +35364,29 @@ public class ArrayRequestParameters200Response extends RuntimeException implemen } /** - * Create a ArrayRequestParameters200Response without a body + * Create a ArrayOfOneOfs200Response with a body */ - public static ArrayRequestParameters200Response of() { - return new ArrayRequestParameters200Response(new HashMap<>(), new HashMap<>()); + public static ArrayOfOneOfs200Response of(final ArrayOfOneOfs body) { + return new ArrayOfOneOfs200Response(body, new HashMap<>(), new HashMap<>()); } /** - * Create a ArrayRequestParameters200Response without a body and headers + * Create a ArrayOfOneOfs200Response with a body and headers */ - public static ArrayRequestParameters200Response of(final Map headers) { - return new ArrayRequestParameters200Response(headers, new HashMap<>()); + public static ArrayOfOneOfs200Response of(final ArrayOfOneOfs body, final Map headers) { + return new ArrayOfOneOfs200Response(body, headers, new HashMap<>()); } /** - * Create a ArrayRequestParameters200Response without a body, headers and multi-value headers + * Create a ArrayOfOneOfs200Response with a body, headers and multi-value headers */ - public static ArrayRequestParameters200Response of(final Map headers, final Map> multiValueHeaders) { - return new ArrayRequestParameters200Response(headers, multiValueHeaders); + public static ArrayOfOneOfs200Response of(final ArrayOfOneOfs body, final Map headers, final Map> multiValueHeaders) { + return new ArrayOfOneOfs200Response(body, headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersInput.java": " -package test.test.runtime.api.handlers.array_request_parameters; + "src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsInput.java": " +package test.test.runtime.api.handlers.array_of_one_ofs; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -35056,11 +35399,11 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import java.io.IOException; /** - * Input for the arrayRequestParameters operation + * Input for the arrayOfOneOfs operation */ @lombok.Builder @lombok.AllArgsConstructor -public class ArrayRequestParametersInput { +public class ArrayOfOneOfsInput { static { // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. // Create an instance here if required to ensure that the static Gson instance is always available. @@ -35069,20 +35412,20 @@ public class ArrayRequestParametersInput { } } - private final ArrayRequestParametersRequestParameters requestParameters; + private final ArrayOfOneOfsRequestParameters requestParameters; - public ArrayRequestParametersInput(final APIGatewayProxyRequestEvent event) { - this.requestParameters = new ArrayRequestParametersRequestParameters(event); + public ArrayOfOneOfsInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new ArrayOfOneOfsRequestParameters(event); } - public ArrayRequestParametersRequestParameters getRequestParameters() { + public ArrayOfOneOfsRequestParameters getRequestParameters() { return this.requestParameters; } } ", - "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersRequestInput.java": " -package test.test.runtime.api.handlers.array_request_parameters; + "src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsRequestInput.java": " +package test.test.runtime.api.handlers.array_of_one_ofs; import test.test.runtime.model.*; import test.test.runtime.api.handlers.RequestInput; @@ -35095,20 +35438,20 @@ import java.io.IOException; import com.amazonaws.services.lambda.runtime.Context; /** - * Full request input for the arrayRequestParameters operation, including the raw API Gateway event + * Full request input for the arrayOfOneOfs operation, including the raw API Gateway event */ @lombok.Builder @lombok.AllArgsConstructor -public class ArrayRequestParametersRequestInput implements RequestInput { +public class ArrayOfOneOfsRequestInput implements RequestInput { private final APIGatewayProxyRequestEvent event; private final Context context; private final Map interceptorContext; - private final ArrayRequestParametersInput input; + private final ArrayOfOneOfsInput input; /** * Returns the typed request input, with path, query and body parameters */ - public ArrayRequestParametersInput getInput() { + public ArrayOfOneOfsInput getInput() { return this.input; } @@ -35134,8 +35477,8 @@ public class ArrayRequestParametersRequestInput implements RequestInput> myStringArrayRequestParams; - private final Optional> myEnumArrayRequestParams; - private final Optional> myIntegerArrayRequestParams; - private final Optional> myLongArrayRequestParams; - private final Optional> myInt32ArrayRequestParams; - private final Optional> myNumberArrayRequestParams; - private final Optional> myFloatArrayRequestParams; - private final Optional> myDoubleArrayRequestParams; - private final Optional myEnumRequestParam; +public class ArrayOfOneOfsRequestParameters { - public ArrayRequestParametersRequestParameters(final APIGatewayProxyRequestEvent event) { + public ArrayOfOneOfsRequestParameters(final APIGatewayProxyRequestEvent event) { Map rawStringParameters = new HashMap<>(); Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); @@ -35179,58 +35513,22 @@ public class ArrayRequestParametersRequestParameters { Handlers.putAllFromNullableMap(event.getMultiValueHeaders(), rawStringArrayParameters); Map> decodedStringArrayParameters = Handlers.decodeRequestArrayParameters(rawStringArrayParameters); - this.myStringArrayRequestParams = Optional.ofNullable(Handlers.coerceStringArrayParameter("my-string-array-request-params", false, decodedStringArrayParameters)); - this.myEnumArrayRequestParams = Optional.ofNullable(Handlers.coerceStringArrayParameter("my-enum-array-request-params", false, decodedStringArrayParameters).stream().map(MyEnum::fromValue).collect(Collectors.toList())); - this.myIntegerArrayRequestParams = Optional.ofNullable(Handlers.coerceIntegerArrayParameter("my-integer-array-request-params", false, decodedStringArrayParameters)); - this.myLongArrayRequestParams = Optional.ofNullable(Handlers.coerceLongArrayParameter("my-long-array-request-params", false, decodedStringArrayParameters)); - this.myInt32ArrayRequestParams = Optional.ofNullable(Handlers.coerceIntegerArrayParameter("my-int32-array-request-params", false, decodedStringArrayParameters)); - this.myNumberArrayRequestParams = Optional.ofNullable(Handlers.coerceBigDecimalArrayParameter("my-number-array-request-params", false, decodedStringArrayParameters)); - this.myFloatArrayRequestParams = Optional.ofNullable(Handlers.coerceFloatArrayParameter("my-float-array-request-params", false, decodedStringArrayParameters)); - this.myDoubleArrayRequestParams = Optional.ofNullable(Handlers.coerceDoubleArrayParameter("my-double-array-request-params", false, decodedStringArrayParameters)); - this.myEnumRequestParam = Optional.ofNullable(MyEnum.fromValue(Handlers.coerceStringParameter("my-enum-request-param", false, decodedStringParameters))); } - public Optional> getMyStringArrayRequestParams() { - return this.myStringArrayRequestParams; - } - public Optional> getMyEnumArrayRequestParams() { - return this.myEnumArrayRequestParams; - } - public Optional> getMyIntegerArrayRequestParams() { - return this.myIntegerArrayRequestParams; - } - public Optional> getMyLongArrayRequestParams() { - return this.myLongArrayRequestParams; - } - public Optional> getMyInt32ArrayRequestParams() { - return this.myInt32ArrayRequestParams; - } - public Optional> getMyNumberArrayRequestParams() { - return this.myNumberArrayRequestParams; - } - public Optional> getMyFloatArrayRequestParams() { - return this.myFloatArrayRequestParams; - } - public Optional> getMyDoubleArrayRequestParams() { - return this.myDoubleArrayRequestParams; - } - public Optional getMyEnumRequestParam() { - return this.myEnumRequestParam; - } } ", - "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersResponse.java": " -package test.test.runtime.api.handlers.array_request_parameters; + "src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsResponse.java": " +package test.test.runtime.api.handlers.array_of_one_ofs; import test.test.runtime.api.handlers.Response; /** - * Response for the arrayRequestParameters operation + * Response for the arrayOfOneOfs operation */ -public interface ArrayRequestParametersResponse extends Response {} +public interface ArrayOfOneOfsResponse extends Response {} ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnum.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParameters.java": " +package test.test.runtime.api.handlers.array_request_parameters; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -35254,50 +35552,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the inlineEnum operation + * Lambda handler wrapper for the arrayRequestParameters operation */ -public abstract class InlineEnum implements RequestHandler, Resource { +public abstract class ArrayRequestParameters implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the inlineEnum operation + * Handle the request for the arrayRequestParameters operation */ - public abstract InlineEnumResponse handle(final InlineEnumRequestInput request); + public abstract ArrayRequestParametersResponse handle(final ArrayRequestParametersRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(InlineEnum.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(ArrayRequestParameters.class); /** * For more complex interceptors that require instantiation with parameters, you may override this method to * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, * prefer the @Interceptors annotation. */ - public List> getInterceptors() { + public List> getInterceptors() { return Collections.emptyList(); } - private List> getHandlerInterceptors() { - List> interceptors = new ArrayList<>(); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); interceptors.addAll(annotationInterceptors); interceptors.addAll(this.getInterceptors()); return interceptors; } - private HandlerChain buildChain(List> interceptors) { - return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { @Override - public Response next(ChainedRequestInput input) { - return handle(new InlineEnumRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new ArrayRequestParametersRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final InlineEnumInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final ArrayRequestParametersInput input, final Map interceptorContext) { + return new ChainedRequestInput() { @Override public HandlerChain getChain() { // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining @@ -35316,7 +35614,7 @@ public abstract class InlineEnum implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -35377,20 +35675,20 @@ public abstract class InlineEnum implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "inlineEnum"); + interceptorContext.put("operationId", "arrayRequestParameters"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - InlineEnumInput input; + ArrayRequestParametersInput input; try { - input = new InlineEnumInput(event); + input = new ArrayRequestParametersInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -35415,8 +35713,8 @@ public abstract class InlineEnum implements RequestHandler headers; private final Map> multiValueHeaders; - private InlineEnum200Response(final InlineEnum200Response body, final Map headers, final Map> multiValueHeaders) { - this.typedBody = body; - this.body = body.toJson(); + private ArrayRequestParameters200Response(final Map headers, final Map> multiValueHeaders) { + + this.body = ""; this.headers = headers; this.multiValueHeaders = multiValueHeaders; } @@ -35458,9 +35756,6 @@ public class InlineEnum200Response extends RuntimeException implements InlineEnu return this.body; } - public InlineEnum200Response getTypedBody() { - return this.typedBody; - } @Override public Map getHeaders() { @@ -35473,29 +35768,29 @@ public class InlineEnum200Response extends RuntimeException implements InlineEnu } /** - * Create a InlineEnum200Response with a body + * Create a ArrayRequestParameters200Response without a body */ - public static InlineEnum200Response of(final InlineEnum200Response body) { - return new InlineEnum200Response(body, new HashMap<>(), new HashMap<>()); + public static ArrayRequestParameters200Response of() { + return new ArrayRequestParameters200Response(new HashMap<>(), new HashMap<>()); } /** - * Create a InlineEnum200Response with a body and headers + * Create a ArrayRequestParameters200Response without a body and headers */ - public static InlineEnum200Response of(final InlineEnum200Response body, final Map headers) { - return new InlineEnum200Response(body, headers, new HashMap<>()); + public static ArrayRequestParameters200Response of(final Map headers) { + return new ArrayRequestParameters200Response(headers, new HashMap<>()); } /** - * Create a InlineEnum200Response with a body, headers and multi-value headers + * Create a ArrayRequestParameters200Response without a body, headers and multi-value headers */ - public static InlineEnum200Response of(final InlineEnum200Response body, final Map headers, final Map> multiValueHeaders) { - return new InlineEnum200Response(body, headers, multiValueHeaders); + public static ArrayRequestParameters200Response of(final Map headers, final Map> multiValueHeaders) { + return new ArrayRequestParameters200Response(headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumInput.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersInput.java": " +package test.test.runtime.api.handlers.array_request_parameters; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -35508,11 +35803,11 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import java.io.IOException; /** - * Input for the inlineEnum operation + * Input for the arrayRequestParameters operation */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineEnumInput { +public class ArrayRequestParametersInput { static { // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. // Create an instance here if required to ensure that the static Gson instance is always available. @@ -35521,20 +35816,20 @@ public class InlineEnumInput { } } - private final InlineEnumRequestParameters requestParameters; + private final ArrayRequestParametersRequestParameters requestParameters; - public InlineEnumInput(final APIGatewayProxyRequestEvent event) { - this.requestParameters = new InlineEnumRequestParameters(event); + public ArrayRequestParametersInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new ArrayRequestParametersRequestParameters(event); } - public InlineEnumRequestParameters getRequestParameters() { + public ArrayRequestParametersRequestParameters getRequestParameters() { return this.requestParameters; } } ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestInput.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersRequestInput.java": " +package test.test.runtime.api.handlers.array_request_parameters; import test.test.runtime.model.*; import test.test.runtime.api.handlers.RequestInput; @@ -35547,20 +35842,20 @@ import java.io.IOException; import com.amazonaws.services.lambda.runtime.Context; /** - * Full request input for the inlineEnum operation, including the raw API Gateway event + * Full request input for the arrayRequestParameters operation, including the raw API Gateway event */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineEnumRequestInput implements RequestInput { +public class ArrayRequestParametersRequestInput implements RequestInput { private final APIGatewayProxyRequestEvent event; private final Context context; private final Map interceptorContext; - private final InlineEnumInput input; + private final ArrayRequestParametersInput input; /** * Returns the typed request input, with path, query and body parameters */ - public InlineEnumInput getInput() { + public ArrayRequestParametersInput getInput() { return this.input; } @@ -35586,8 +35881,8 @@ public class InlineEnumRequestInput implements RequestInput { } } ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestParameters.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersRequestParameters.java": " +package test.test.runtime.api.handlers.array_request_parameters; import test.test.runtime.api.handlers.Handlers; import java.util.Optional; @@ -35604,13 +35899,22 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import test.test.runtime.model.*; /** - * Query, path and header parameters for the InlineEnum operation + * Query, path and header parameters for the ArrayRequestParameters operation */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineEnumRequestParameters { +public class ArrayRequestParametersRequestParameters { + private final Optional> myStringArrayRequestParams; + private final Optional> myEnumArrayRequestParams; + private final Optional> myIntegerArrayRequestParams; + private final Optional> myLongArrayRequestParams; + private final Optional> myInt32ArrayRequestParams; + private final Optional> myNumberArrayRequestParams; + private final Optional> myFloatArrayRequestParams; + private final Optional> myDoubleArrayRequestParams; + private final Optional myEnumRequestParam; - public InlineEnumRequestParameters(final APIGatewayProxyRequestEvent event) { + public ArrayRequestParametersRequestParameters(final APIGatewayProxyRequestEvent event) { Map rawStringParameters = new HashMap<>(); Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); @@ -35622,31 +35926,67 @@ public class InlineEnumRequestParameters { Handlers.putAllFromNullableMap(event.getMultiValueHeaders(), rawStringArrayParameters); Map> decodedStringArrayParameters = Handlers.decodeRequestArrayParameters(rawStringArrayParameters); + this.myStringArrayRequestParams = Optional.ofNullable(Handlers.coerceStringArrayParameter("my-string-array-request-params", false, decodedStringArrayParameters)); + this.myEnumArrayRequestParams = Optional.ofNullable(Handlers.coerceStringArrayParameter("my-enum-array-request-params", false, decodedStringArrayParameters).stream().map(MyEnum::fromValue).collect(Collectors.toList())); + this.myIntegerArrayRequestParams = Optional.ofNullable(Handlers.coerceIntegerArrayParameter("my-integer-array-request-params", false, decodedStringArrayParameters)); + this.myLongArrayRequestParams = Optional.ofNullable(Handlers.coerceLongArrayParameter("my-long-array-request-params", false, decodedStringArrayParameters)); + this.myInt32ArrayRequestParams = Optional.ofNullable(Handlers.coerceIntegerArrayParameter("my-int32-array-request-params", false, decodedStringArrayParameters)); + this.myNumberArrayRequestParams = Optional.ofNullable(Handlers.coerceBigDecimalArrayParameter("my-number-array-request-params", false, decodedStringArrayParameters)); + this.myFloatArrayRequestParams = Optional.ofNullable(Handlers.coerceFloatArrayParameter("my-float-array-request-params", false, decodedStringArrayParameters)); + this.myDoubleArrayRequestParams = Optional.ofNullable(Handlers.coerceDoubleArrayParameter("my-double-array-request-params", false, decodedStringArrayParameters)); + this.myEnumRequestParam = Optional.ofNullable(MyEnum.fromValue(Handlers.coerceStringParameter("my-enum-request-param", false, decodedStringParameters))); } -} -", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumResponse.java": " -package test.test.runtime.api.handlers.inline_enum; - -import test.test.runtime.api.handlers.Response; - -/** - * Response for the inlineEnum operation - */ -public interface InlineEnumResponse extends Response {} -", - "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody.java": " -package test.test.runtime.api.handlers.inline_request_body; - -import test.test.runtime.model.*; -import test.test.runtime.JSON; -import test.test.runtime.api.handlers.Interceptor; -import test.test.runtime.api.handlers.Handlers; -import test.test.runtime.api.handlers.*; - -import java.util.List; -import java.util.ArrayList; + public Optional> getMyStringArrayRequestParams() { + return this.myStringArrayRequestParams; + } + public Optional> getMyEnumArrayRequestParams() { + return this.myEnumArrayRequestParams; + } + public Optional> getMyIntegerArrayRequestParams() { + return this.myIntegerArrayRequestParams; + } + public Optional> getMyLongArrayRequestParams() { + return this.myLongArrayRequestParams; + } + public Optional> getMyInt32ArrayRequestParams() { + return this.myInt32ArrayRequestParams; + } + public Optional> getMyNumberArrayRequestParams() { + return this.myNumberArrayRequestParams; + } + public Optional> getMyFloatArrayRequestParams() { + return this.myFloatArrayRequestParams; + } + public Optional> getMyDoubleArrayRequestParams() { + return this.myDoubleArrayRequestParams; + } + public Optional getMyEnumRequestParam() { + return this.myEnumRequestParam; + } +} +", + "src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersResponse.java": " +package test.test.runtime.api.handlers.array_request_parameters; + +import test.test.runtime.api.handlers.Response; + +/** + * Response for the arrayRequestParameters operation + */ +public interface ArrayRequestParametersResponse extends Response {} +", + "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnum.java": " +package test.test.runtime.api.handlers.inline_enum; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.Handlers; +import test.test.runtime.api.handlers.*; + +import java.util.List; +import java.util.ArrayList; import java.util.Optional; import java.util.Map; import java.util.HashMap; @@ -35661,50 +36001,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the inlineRequestBody operation + * Lambda handler wrapper for the inlineEnum operation */ -public abstract class InlineRequestBody implements RequestHandler, Resource { +public abstract class InlineEnum implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the inlineRequestBody operation + * Handle the request for the inlineEnum operation */ - public abstract InlineRequestBodyResponse handle(final InlineRequestBodyRequestInput request); + public abstract InlineEnumResponse handle(final InlineEnumRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(InlineRequestBody.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(InlineEnum.class); /** * For more complex interceptors that require instantiation with parameters, you may override this method to * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, * prefer the @Interceptors annotation. */ - public List> getInterceptors() { + public List> getInterceptors() { return Collections.emptyList(); } - private List> getHandlerInterceptors() { - List> interceptors = new ArrayList<>(); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); interceptors.addAll(annotationInterceptors); interceptors.addAll(this.getInterceptors()); return interceptors; } - private HandlerChain buildChain(List> interceptors) { - return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { @Override - public Response next(ChainedRequestInput input) { - return handle(new InlineRequestBodyRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new InlineEnumRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final InlineRequestBodyInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final InlineEnumInput input, final Map interceptorContext) { + return new ChainedRequestInput() { @Override public HandlerChain getChain() { // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining @@ -35723,7 +36063,7 @@ public abstract class InlineRequestBody implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -35784,20 +36124,20 @@ public abstract class InlineRequestBody implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "inlineRequestBody"); + interceptorContext.put("operationId", "inlineEnum"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - InlineRequestBodyInput input; + InlineEnumInput input; try { - input = new InlineRequestBodyInput(event); + input = new InlineEnumInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -35822,8 +36162,8 @@ public abstract class InlineRequestBody implements RequestHandler headers; private final Map> multiValueHeaders; - private InlineRequestBody204Response(final Map headers, final Map> multiValueHeaders) { - - this.body = ""; + private InlineEnum200Response(final InlineEnum200Response body, final Map headers, final Map> multiValueHeaders) { + this.typedBody = body; + this.body = body.toJson(); this.headers = headers; this.multiValueHeaders = multiValueHeaders; } @Override public int getStatusCode() { - return 204; + return 200; } @Override @@ -35865,6 +36205,9 @@ public class InlineRequestBody204Response extends RuntimeException implements In return this.body; } + public InlineEnum200Response getTypedBody() { + return this.typedBody; + } @Override public Map getHeaders() { @@ -35877,29 +36220,29 @@ public class InlineRequestBody204Response extends RuntimeException implements In } /** - * Create a InlineRequestBody204Response without a body + * Create a InlineEnum200Response with a body */ - public static InlineRequestBody204Response of() { - return new InlineRequestBody204Response(new HashMap<>(), new HashMap<>()); + public static InlineEnum200Response of(final InlineEnum200Response body) { + return new InlineEnum200Response(body, new HashMap<>(), new HashMap<>()); } /** - * Create a InlineRequestBody204Response without a body and headers + * Create a InlineEnum200Response with a body and headers */ - public static InlineRequestBody204Response of(final Map headers) { - return new InlineRequestBody204Response(headers, new HashMap<>()); + public static InlineEnum200Response of(final InlineEnum200Response body, final Map headers) { + return new InlineEnum200Response(body, headers, new HashMap<>()); } /** - * Create a InlineRequestBody204Response without a body, headers and multi-value headers + * Create a InlineEnum200Response with a body, headers and multi-value headers */ - public static InlineRequestBody204Response of(final Map headers, final Map> multiValueHeaders) { - return new InlineRequestBody204Response(headers, multiValueHeaders); + public static InlineEnum200Response of(final InlineEnum200Response body, final Map headers, final Map> multiValueHeaders) { + return new InlineEnum200Response(body, headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyInput.java": " -package test.test.runtime.api.handlers.inline_request_body; + "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumInput.java": " +package test.test.runtime.api.handlers.inline_enum; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -35912,11 +36255,11 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import java.io.IOException; /** - * Input for the inlineRequestBody operation + * Input for the inlineEnum operation */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineRequestBodyInput { +public class InlineEnumInput { static { // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. // Create an instance here if required to ensure that the static Gson instance is always available. @@ -35925,29 +36268,20 @@ public class InlineRequestBodyInput { } } - private final InlineRequestBodyRequestParameters requestParameters; - private final InlineRequestBodyRequestContent body; + private final InlineEnumRequestParameters requestParameters; - public InlineRequestBodyInput(final APIGatewayProxyRequestEvent event) { - this.requestParameters = new InlineRequestBodyRequestParameters(event); - try { - this.body = InlineRequestBodyRequestContent.fromJson(event.getBody()); - } catch (IOException e) { - throw new RuntimeException(e); - }; + public InlineEnumInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new InlineEnumRequestParameters(event); } - public InlineRequestBodyRequestParameters getRequestParameters() { + public InlineEnumRequestParameters getRequestParameters() { return this.requestParameters; } - public InlineRequestBodyRequestContent getBody() { - return this.body; - } } ", - "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestInput.java": " -package test.test.runtime.api.handlers.inline_request_body; + "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestInput.java": " +package test.test.runtime.api.handlers.inline_enum; import test.test.runtime.model.*; import test.test.runtime.api.handlers.RequestInput; @@ -35960,20 +36294,20 @@ import java.io.IOException; import com.amazonaws.services.lambda.runtime.Context; /** - * Full request input for the inlineRequestBody operation, including the raw API Gateway event + * Full request input for the inlineEnum operation, including the raw API Gateway event */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineRequestBodyRequestInput implements RequestInput { +public class InlineEnumRequestInput implements RequestInput { private final APIGatewayProxyRequestEvent event; private final Context context; private final Map interceptorContext; - private final InlineRequestBodyInput input; + private final InlineEnumInput input; /** * Returns the typed request input, with path, query and body parameters */ - public InlineRequestBodyInput getInput() { + public InlineEnumInput getInput() { return this.input; } @@ -35999,8 +36333,8 @@ public class InlineRequestBodyRequestInput implements RequestInput rawStringParameters = new HashMap<>(); Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); @@ -36039,18 +36373,18 @@ public class InlineRequestBodyRequestParameters { } ", - "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyResponse.java": " -package test.test.runtime.api.handlers.inline_request_body; + "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumResponse.java": " +package test.test.runtime.api.handlers.inline_enum; import test.test.runtime.api.handlers.Response; /** - * Response for the inlineRequestBody operation + * Response for the inlineEnum operation */ -public interface InlineRequestBodyResponse extends Response {} +public interface InlineEnumResponse extends Response {} ", - "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords.java": " -package test.test.runtime.api.handlers.reserved_keywords; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody.java": " +package test.test.runtime.api.handlers.inline_request_body; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -36074,50 +36408,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the reservedKeywords operation + * Lambda handler wrapper for the inlineRequestBody operation */ -public abstract class ReservedKeywords implements RequestHandler, Resource { +public abstract class InlineRequestBody implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the reservedKeywords operation + * Handle the request for the inlineRequestBody operation */ - public abstract ReservedKeywordsResponse handle(final ReservedKeywordsRequestInput request); + public abstract InlineRequestBodyResponse handle(final InlineRequestBodyRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(ReservedKeywords.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(InlineRequestBody.class); /** * For more complex interceptors that require instantiation with parameters, you may override this method to * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, * prefer the @Interceptors annotation. */ - public List> getInterceptors() { + public List> getInterceptors() { return Collections.emptyList(); } - private List> getHandlerInterceptors() { - List> interceptors = new ArrayList<>(); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); interceptors.addAll(annotationInterceptors); interceptors.addAll(this.getInterceptors()); return interceptors; } - private HandlerChain buildChain(List> interceptors) { - return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { @Override - public Response next(ChainedRequestInput input) { - return handle(new ReservedKeywordsRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new InlineRequestBodyRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final ReservedKeywordsInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final InlineRequestBodyInput input, final Map interceptorContext) { + return new ChainedRequestInput() { @Override public HandlerChain getChain() { // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining @@ -36136,7 +36470,7 @@ public abstract class ReservedKeywords implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -36197,20 +36531,20 @@ public abstract class ReservedKeywords implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "reservedKeywords"); + interceptorContext.put("operationId", "inlineRequestBody"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - ReservedKeywordsInput input; + InlineRequestBodyInput input; try { - input = new ReservedKeywordsInput(event); + input = new InlineRequestBodyInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -36235,8 +36569,8 @@ public abstract class ReservedKeywords implements RequestHandler headers; private final Map> multiValueHeaders; - private ReservedKeywords200Response(final Map headers, final Map> multiValueHeaders) { + private InlineRequestBody204Response(final Map headers, final Map> multiValueHeaders) { this.body = ""; this.headers = headers; @@ -36270,7 +36604,7 @@ public class ReservedKeywords200Response extends RuntimeException implements Res @Override public int getStatusCode() { - return 200; + return 204; } @Override @@ -36290,29 +36624,29 @@ public class ReservedKeywords200Response extends RuntimeException implements Res } /** - * Create a ReservedKeywords200Response without a body + * Create a InlineRequestBody204Response without a body */ - public static ReservedKeywords200Response of() { - return new ReservedKeywords200Response(new HashMap<>(), new HashMap<>()); + public static InlineRequestBody204Response of() { + return new InlineRequestBody204Response(new HashMap<>(), new HashMap<>()); } /** - * Create a ReservedKeywords200Response without a body and headers + * Create a InlineRequestBody204Response without a body and headers */ - public static ReservedKeywords200Response of(final Map headers) { - return new ReservedKeywords200Response(headers, new HashMap<>()); + public static InlineRequestBody204Response of(final Map headers) { + return new InlineRequestBody204Response(headers, new HashMap<>()); } /** - * Create a ReservedKeywords200Response without a body, headers and multi-value headers + * Create a InlineRequestBody204Response without a body, headers and multi-value headers */ - public static ReservedKeywords200Response of(final Map headers, final Map> multiValueHeaders) { - return new ReservedKeywords200Response(headers, multiValueHeaders); + public static InlineRequestBody204Response of(final Map headers, final Map> multiValueHeaders) { + return new InlineRequestBody204Response(headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsInput.java": " -package test.test.runtime.api.handlers.reserved_keywords; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyInput.java": " +package test.test.runtime.api.handlers.inline_request_body; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -36325,11 +36659,11 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import java.io.IOException; /** - * Input for the reservedKeywords operation + * Input for the inlineRequestBody operation */ @lombok.Builder @lombok.AllArgsConstructor -public class ReservedKeywordsInput { +public class InlineRequestBodyInput { static { // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. // Create an instance here if required to ensure that the static Gson instance is always available. @@ -36338,20 +36672,29 @@ public class ReservedKeywordsInput { } } - private final ReservedKeywordsRequestParameters requestParameters; + private final InlineRequestBodyRequestParameters requestParameters; + private final InlineRequestBodyRequestContent body; - public ReservedKeywordsInput(final APIGatewayProxyRequestEvent event) { - this.requestParameters = new ReservedKeywordsRequestParameters(event); + public InlineRequestBodyInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new InlineRequestBodyRequestParameters(event); + try { + this.body = InlineRequestBodyRequestContent.fromJson(event.getBody()); + } catch (IOException e) { + throw new RuntimeException(e); + }; } - public ReservedKeywordsRequestParameters getRequestParameters() { + public InlineRequestBodyRequestParameters getRequestParameters() { return this.requestParameters; } + public InlineRequestBodyRequestContent getBody() { + return this.body; + } } ", - "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsRequestInput.java": " -package test.test.runtime.api.handlers.reserved_keywords; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestInput.java": " +package test.test.runtime.api.handlers.inline_request_body; import test.test.runtime.model.*; import test.test.runtime.api.handlers.RequestInput; @@ -36364,20 +36707,20 @@ import java.io.IOException; import com.amazonaws.services.lambda.runtime.Context; /** - * Full request input for the reservedKeywords operation, including the raw API Gateway event + * Full request input for the inlineRequestBody operation, including the raw API Gateway event */ @lombok.Builder @lombok.AllArgsConstructor -public class ReservedKeywordsRequestInput implements RequestInput { +public class InlineRequestBodyRequestInput implements RequestInput { private final APIGatewayProxyRequestEvent event; private final Context context; private final Map interceptorContext; - private final ReservedKeywordsInput input; + private final InlineRequestBodyInput input; /** * Returns the typed request input, with path, query and body parameters */ - public ReservedKeywordsInput getInput() { + public InlineRequestBodyInput getInput() { return this.input; } @@ -36403,8 +36746,8 @@ public class ReservedKeywordsRequestInput implements RequestInput with; - private final Optional _if; - private final Optional propertyClass; +public class InlineRequestBodyRequestParameters { - public ReservedKeywordsRequestParameters(final APIGatewayProxyRequestEvent event) { + public InlineRequestBodyRequestParameters(final APIGatewayProxyRequestEvent event) { Map rawStringParameters = new HashMap<>(); Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); @@ -36442,467 +36782,1905 @@ public class ReservedKeywordsRequestParameters { Handlers.putAllFromNullableMap(event.getMultiValueHeaders(), rawStringArrayParameters); Map> decodedStringArrayParameters = Handlers.decodeRequestArrayParameters(rawStringArrayParameters); - this.with = Optional.ofNullable(Handlers.coerceStringParameter("with", false, decodedStringParameters)); - this._if = Optional.ofNullable(Handlers.coerceStringParameter("if", false, decodedStringParameters)); - this.propertyClass = Optional.ofNullable(Handlers.coerceStringParameter("class", false, decodedStringParameters)); } - public Optional getWith() { - return this.with; - } - public Optional getIf() { - return this._if; - } - public Optional getPropertyClass() { - return this.propertyClass; - } } ", - "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsResponse.java": " -package test.test.runtime.api.handlers.reserved_keywords; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyResponse.java": " +package test.test.runtime.api.handlers.inline_request_body; import test.test.runtime.api.handlers.Response; /** - * Response for the reservedKeywords operation + * Response for the inlineRequestBody operation */ -public interface ReservedKeywordsResponse extends Response {} +public interface InlineRequestBodyResponse extends Response {} ", - "src/main/java/test/test/runtime/api/interceptors/DefaultInterceptors.java": "package test.test.runtime.api.interceptors; + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOf.java": " +package test.test.runtime.api.handlers.named_one_of; -import test.test.runtime.api.interceptors.powertools.LoggingInterceptor; -import test.test.runtime.api.interceptors.powertools.MetricsInterceptor; -import test.test.runtime.api.interceptors.powertools.TracingInterceptor; +import test.test.runtime.model.*; +import test.test.runtime.JSON; import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.Handlers; +import test.test.runtime.api.handlers.*; -import java.util.Arrays; import java.util.List; - -public class DefaultInterceptors { - public static List> all() { - return Arrays.asList( - new ResponseHeadersInterceptor<>(), - new LoggingInterceptor<>(), - new TryCatchInterceptor<>(), - new TracingInterceptor<>(), - new MetricsInterceptor<>() - ); - } -}", - "src/main/java/test/test/runtime/api/interceptors/ResponseHeadersInterceptor.java": "package test.test.runtime.api.interceptors; - -import test.test.runtime.api.handlers.ChainedRequestInput; -import test.test.runtime.api.handlers.Response; -import test.test.runtime.api.handlers.Interceptor; -import test.test.runtime.api.handlers.InterceptorWithWarmup; +import java.util.ArrayList; +import java.util.Optional; import java.util.Map; import java.util.HashMap; +import java.util.Collections; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; +import java.io.IOException; +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import org.crac.Core; +import org.crac.Resource; + /** - * An interceptor for adding cross-origin resource sharing (CORS) headers to the response. - * Allows all origins and headers. + * Lambda handler wrapper for the namedOneOf operation */ -public class ResponseHeadersInterceptor extends InterceptorWithWarmup { - private final Map additionalHeaders; - - public ResponseHeadersInterceptor() { - this.additionalHeaders = new HashMap<>(); - this.additionalHeaders.put("Access-Control-Allow-Origin", "*"); - this.additionalHeaders.put("Access-Control-Allow-Headers", "*"); +public abstract class NamedOneOf implements RequestHandler, Resource { + { + Core.getGlobalContext().register(this); } - public ResponseHeadersInterceptor(final Map headers) { - this.additionalHeaders = headers; + /** + * Handle the request for the namedOneOf operation + */ + public abstract NamedOneOfResponse handle(final NamedOneOfRequestInput request); + + /** + * Interceptors that the handler class has been decorated with + */ + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(NamedOneOf.class); + + /** + * For more complex interceptors that require instantiation with parameters, you may override this method to + * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, + * prefer the @Interceptors annotation. + */ + public List> getInterceptors() { + return Collections.emptyList(); } - @Override - public Response handle(ChainedRequestInput input) { - Response res = input.getChain().next(input); - res.getHeaders().putAll(this.additionalHeaders); - return res; + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); + interceptors.addAll(annotationInterceptors); + interceptors.addAll(this.getInterceptors()); + return interceptors; } - public Map getAdditionalHeaders() { - return this.additionalHeaders; + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + @Override + public Response next(ChainedRequestInput input) { + return handle(new NamedOneOfRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + } + }); } -} -", - "src/main/java/test/test/runtime/api/interceptors/TryCatchInterceptor.java": "package test.test.runtime.api.interceptors; -import test.test.runtime.api.handlers.ApiResponse; -import test.test.runtime.api.handlers.ChainedRequestInput; -import test.test.runtime.api.handlers.Response; -import test.test.runtime.api.handlers.Interceptor; -import test.test.runtime.api.handlers.InterceptorWithWarmup; -import org.apache.logging.log4j.Logger; + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final NamedOneOfInput input, final Map interceptorContext) { + return new ChainedRequestInput() { + @Override + public HandlerChain getChain() { + // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining + // chain. + return null; + } -/** - * Interceptor for handling uncaught exceptions and responding with a default error response - */ -public class TryCatchInterceptor extends InterceptorWithWarmup { - private final int statusCode; - private final String errorResponseBody; + @Override + public APIGatewayProxyRequestEvent getEvent() { + return event; + } - public TryCatchInterceptor() { - this(500, "{\\"message\\": \\"Internal Error\\"}"); - } + @Override + public Context getContext() { + return context; + } - public TryCatchInterceptor(final int statusCode, final String errorResponseBody) { - this.statusCode = statusCode; - this.errorResponseBody = errorResponseBody; + @Override + public NamedOneOfInput getInput() { + return input; + } + + @Override + public Map getInterceptorContext() { + return interceptorContext; + } + }; } @Override - public Response handle(final ChainedRequestInput input) { - try { - return input.getChain().next(input); - } catch (Throwable e) { - if (e instanceof Response) { - return (Response) e; - } + public void beforeCheckpoint(org.crac.Context context) { + // Prime building the handler chain which can take a few 100ms to JIT. + this.buildChain(this.getHandlerInterceptors()); + this.buildChainedRequestInput(null, null, null, null); - Object logger = input.getInterceptorContext().get("logger"); - if (logger instanceof Logger) { - ((Logger) logger).error("Interceptor caught exception", e); - } else { - System.err.println("Interceptor caught exception"); - e.printStackTrace(); - } + // Initialise instance of Gson and prime serialisation and deserialisation + new JSON(); + JSON.getGson().fromJson(JSON.getGson().toJson(new ApiResponse("", 0, new HashMap<>(), new HashMap<>())), ApiResponse.class); + + try { + // Prime input validation - this will likely fail for the fake event but ensures the code path is optimised + // ready for a real invocation + new NamedOneOfInput(new APIGatewayProxyRequestEvent() + .withBody("{}") + .withPathParameters(new HashMap<>()) + .withQueryStringParameters(new HashMap<>()) + .withMultiValueQueryStringParameters(new HashMap<>()) + .withHeaders(new HashMap<>()) + .withMultiValueHeaders(new HashMap<>()) + ); + } catch (Exception e) { - return ApiResponse.builder() - .statusCode(this.statusCode) - .body(this.errorResponseBody) - .build(); } + + this.warmUp(); } -} -", - "src/main/java/test/test/runtime/api/interceptors/powertools/LoggingInterceptor.java": "package test.test.runtime.api.interceptors.powertools; -import test.test.runtime.api.handlers.ChainedRequestInput; -import test.test.runtime.api.handlers.RequestInput; -import test.test.runtime.api.handlers.Response; -import test.test.runtime.api.handlers.Interceptor; -import test.test.runtime.api.handlers.InterceptorWithWarmup; -import com.amazonaws.services.lambda.runtime.Context; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.ThreadContext; -import software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor; -import software.amazon.lambda.powertools.logging.LoggingUtils; + @Override + public void afterRestore(org.crac.Context context) { -/** - * An interceptor which adds an aws lambda powertools logger to the interceptor context, - * and adds the lambda context. - * See https://docs.powertools.aws.dev/lambda/java/latest/core/logging/ - */ -public class LoggingInterceptor extends InterceptorWithWarmup { - private Logger logger = LogManager.getLogger(LoggingInterceptor.class); - - @Override - public void warmUp() { - super.warmUp(); - logger.info("LoggingInterceptor: init"); } /** - * Return the instance of the logger from the interceptor context + * Override this method to perform any warmup activities which will be executed prior to the snap-start snapshot. */ - public static Logger getLogger(final RequestInput request) { - Object logger = request.getInterceptorContext().get("logger"); - if (logger == null) { - throw new RuntimeException("No logger found. Did you configure the LoggingInterceptor?"); - } - return (Logger) logger; - } + public void warmUp() { - private void addContext(final Context context) { - LoggingUtils.appendKey("functionName", context.getFunctionName()); - LoggingUtils.appendKey("functionVersion", context.getFunctionVersion()); - LoggingUtils.appendKey("functionArn", context.getInvokedFunctionArn()); - LoggingUtils.appendKey("functionMemorySize", String.valueOf(context.getMemoryLimitInMB())); - // Same casing as powertools aspect implementation - LoggingUtils.appendKey("function_request_id", String.valueOf(context.getAwsRequestId())); } @Override - public Response handle(final ChainedRequestInput input) { - // Add lambda context fields - this.addContext(input.getContext()); - - // Add service, cold start and tracing - LoggingUtils.appendKey("service", LambdaHandlerProcessor.serviceName()); - LoggingUtils.appendKey("coldStart", LambdaHandlerProcessor.isColdStart() ? "true" : "false"); - LambdaHandlerProcessor.getXrayTraceId().ifPresent((xRayTraceId) -> { - LoggingUtils.appendKey("xray_trace_id", xRayTraceId); - }); - - // Add the operation id - String operationId = (String) input.getInterceptorContext().get("operationId"); - LoggingUtils.appendKey("operationId", operationId); - - // Add the logger to the interceptor context - input.getInterceptorContext().put("logger", logger); - - Response response = input.getChain().next(input); - - // Mark cold start done - LambdaHandlerProcessor.coldStartDone(); - - // Clear the logger keys - ThreadContext.clearMap(); - - return response; + public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent event, final Context context) { + return this.handleRequestWithAdditionalInterceptors(event, context, new ArrayList<>()); } -} -", - "src/main/java/test/test/runtime/api/interceptors/powertools/MetricsInterceptor.java": "package test.test.runtime.api.interceptors.powertools; - -import test.test.runtime.api.handlers.ChainedRequestInput; -import test.test.runtime.api.handlers.RequestInput; -import test.test.runtime.api.handlers.Response; -import test.test.runtime.api.handlers.Interceptor; -import test.test.runtime.api.handlers.InterceptorWithWarmup; -import software.amazon.cloudwatchlogs.emf.logger.MetricsLogger; -import software.amazon.cloudwatchlogs.emf.model.DimensionSet; -import software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor; -import software.amazon.lambda.powertools.metrics.MetricsUtils; - -/** - * Interceptor which adds an instance of aws lambda powertools metrics to the interceptor context (under the key "metrics"), - * and ensures metrics are flushed prior to finishing the lambda execution - * See: https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics - */ -public class MetricsInterceptor extends InterceptorWithWarmup { - private MetricsLogger metrics = MetricsUtils.metricsLogger(); - /** - * Return the instance of the metrics logger from the interceptor context - */ - public static MetricsLogger getMetrics(final RequestInput request) { - Object metrics = request.getInterceptorContext().get("metrics"); - if (metrics == null) { - throw new RuntimeException("No metrics logger found. Did you configure the MetricsInterceptor?"); - } - return (MetricsLogger) metrics; + private Map getErrorResponseHeaders(final int statusCode) { + Map headers = new HashMap<>(); + return headers; } - @Override - public Response handle(final ChainedRequestInput input) { - metrics.putDimensions(DimensionSet.of("operationId", (String) input.getInterceptorContext().get("operationId"))); + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { + final Map interceptorContext = new HashMap<>(); + interceptorContext.put("operationId", "namedOneOf"); - input.getInterceptorContext().put("metrics", metrics); + List> interceptors = new ArrayList<>(); + interceptors.addAll(additionalInterceptors); + interceptors.addAll(this.getHandlerInterceptors()); - metrics.putProperty("function_request_id", input.getContext().getAwsRequestId()); - LambdaHandlerProcessor.getXrayTraceId().ifPresent((traceId) -> { - metrics.putProperty("xray_trace_id", traceId); - }); + final HandlerChain chain = this.buildChain(interceptors); + + NamedOneOfInput input; try { - Response response = input.getChain().next(input); + input = new NamedOneOfInput(event); + } catch (RuntimeException e) { + Map headers = new HashMap<>(); + headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); + headers.putAll(this.getErrorResponseHeaders(400)); + return new APIGatewayProxyResponseEvent() + .withStatusCode(400) + .withHeaders(headers) + .withBody("{\\"message\\": \\"" + e.getMessage() + "\\"}"); + } - // Mark cold start done - LambdaHandlerProcessor.coldStartDone(); + final Response response = chain.next(this.buildChainedRequestInput(event, context, input, interceptorContext)); - return response; - } finally { - metrics.flush(); - } + Map responseHeaders = new HashMap<>(); + responseHeaders.putAll(this.getErrorResponseHeaders(response.getStatusCode())); + responseHeaders.putAll(response.getHeaders()); + + return new APIGatewayProxyResponseEvent() + .withStatusCode(response.getStatusCode()) + .withHeaders(responseHeaders) + .withMultiValueHeaders(response.getMultiValueHeaders()) + .withBody(response.getBody()); } } ", - "src/main/java/test/test/runtime/api/interceptors/powertools/TracingInterceptor.java": "package test.test.runtime.api.interceptors.powertools; + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOf200Response.java": " +package test.test.runtime.api.handlers.named_one_of; -import test.test.runtime.api.handlers.ChainedRequestInput; -import test.test.runtime.api.handlers.Response; -import test.test.runtime.api.handlers.Interceptor; -import test.test.runtime.api.handlers.InterceptorWithWarmup; -import com.amazonaws.xray.AWSXRay; -import com.amazonaws.xray.AWSXRayRecorderBuilder; -import com.amazonaws.xray.entities.Subsegment; -import com.fasterxml.jackson.core.JsonProcessingException; -import org.apache.logging.log4j.Logger; -import software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor; -import software.amazon.lambda.powertools.tracing.TracingUtils; +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import java.util.Map; +import java.util.HashMap; +import java.util.List; /** - * Interceptor which adds an aws lambda powertools tracer to the interceptor context, - * creating the appropriate segment for the handler execution and annotating with recommended - * details. - * See: https://docs.powertools.aws.dev/lambda/java/latest/core/tracing/ + * Response with status code 200 for the namedOneOf operation */ -public class TracingInterceptor extends InterceptorWithWarmup { - +public class NamedOneOf200Response extends RuntimeException implements NamedOneOfResponse { static { - AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard(); - AWSXRay.setGlobalRecorder(builder.build()); + // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. + // Create an instance here if required to ensure that the static Gson instance is always available. + if (JSON.getGson() == null) { + new JSON(); + } } - private final boolean captureResponse; + private final String body; + private final NamedOneOfUnion typedBody; + private final Map headers; + private final Map> multiValueHeaders; - public TracingInterceptor(final boolean captureResponse) { - this.captureResponse = captureResponse; + private NamedOneOf200Response(final NamedOneOfUnion body, final Map headers, final Map> multiValueHeaders) { + this.typedBody = body; + this.body = body.toJson(); + this.headers = headers; + this.multiValueHeaders = multiValueHeaders; } - public TracingInterceptor() { - this(false); + @Override + public int getStatusCode() { + return 200; } @Override - public void warmUp() { - try { - // Set a dummy trace header to ensure the regular subsegment code path is followed and warmed. - // The segment is not actually recorded by xray. - System.setProperty("com.amazonaws.xray.traceHeader", "Root=1-xxx;Parent=yyy;Sampled=1"); - super.warmUp(); - } finally { - System.clearProperty("com.amazonaws.xray.traceHeader"); - } + public String getBody() { + return this.body; } - private void logError(final String message, final ChainedRequestInput input, final Throwable e) { - Object logger = input.getInterceptorContext().get("logger"); - if (logger instanceof Logger) { - ((Logger) logger).error(message, e); - } else { - System.err.println(message); - e.printStackTrace(); - } + public NamedOneOfUnion getTypedBody() { + return this.typedBody; } @Override - public Response handle(final ChainedRequestInput input) { - String operationId = (String) input.getInterceptorContext().get("operationId"); - Subsegment segment = AWSXRay.beginSubsegment("## " + operationId); - - segment.setNamespace(operationId); - segment.putAnnotation("ColdStart", LambdaHandlerProcessor.isColdStart()); - segment.putAnnotation("Service", LambdaHandlerProcessor.serviceName()); + public Map getHeaders() { + return this.headers; + } - try { - Response response = input.getChain().next(input); + @Override + public Map> getMultiValueHeaders() { + return this.multiValueHeaders; + } - try { - if (this.captureResponse) { - segment.putMetadata(operationId + " response", TracingUtils.objectMapper() != null ? TracingUtils.objectMapper().writeValueAsString(response) : response); - } - } catch (JsonProcessingException e) { - this.logError("Failed to add response to trace", input, e); - } + /** + * Create a NamedOneOf200Response with a body + */ + public static NamedOneOf200Response of(final NamedOneOfUnion body) { + return new NamedOneOf200Response(body, new HashMap<>(), new HashMap<>()); + } - // Mark cold start done - LambdaHandlerProcessor.coldStartDone(); + /** + * Create a NamedOneOf200Response with a body and headers + */ + public static NamedOneOf200Response of(final NamedOneOfUnion body, final Map headers) { + return new NamedOneOf200Response(body, headers, new HashMap<>()); + } - return response; - } catch (Throwable e) { - try { - segment.putMetadata(operationId + " error", TracingUtils.objectMapper() != null ? TracingUtils.objectMapper().writeValueAsString(e) : e); - } catch (JsonProcessingException ex) { - this.logError("Failed to add error to trace", input, e); - } - throw e; - } finally { - if (!LambdaHandlerProcessor.isSamLocal()) { - AWSXRay.endSubsegment(); - } - } + /** + * Create a NamedOneOf200Response with a body, headers and multi-value headers + */ + public static NamedOneOf200Response of(final NamedOneOfUnion body, final Map headers, final Map> multiValueHeaders) { + return new NamedOneOf200Response(body, headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/operation_config/OperationConfig.java": "package test.test.runtime.api.operation_config; + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfInput.java": " +package test.test.runtime.api.handlers.named_one_of; import test.test.runtime.model.*; - -import java.util.HashMap; +import test.test.runtime.JSON; +import java.util.List; +import java.util.ArrayList; +import java.util.Optional; import java.util.Map; +import java.util.HashMap; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import java.io.IOException; -// Generic type for object "keyed" by operation names -@lombok.Builder @lombok.Getter -public class OperationConfig { - private T arrayRequestParameters; - private T inlineEnum; - private T inlineRequestBody; - private T reservedKeywords; - - public Map asMap() { +/** + * Input for the namedOneOf operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class NamedOneOfInput { + static { + // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. + // Create an instance here if required to ensure that the static Gson instance is always available. + if (JSON.getGson() == null) { + new JSON(); + } + } + + private final NamedOneOfRequestParameters requestParameters; + + public NamedOneOfInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new NamedOneOfRequestParameters(event); + } + + public NamedOneOfRequestParameters getRequestParameters() { + return this.requestParameters; + } + +} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestInput.java": " +package test.test.runtime.api.handlers.named_one_of; + +import test.test.runtime.model.*; +import test.test.runtime.api.handlers.RequestInput; +import java.util.List; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import java.io.IOException; +import com.amazonaws.services.lambda.runtime.Context; + +/** + * Full request input for the namedOneOf operation, including the raw API Gateway event + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class NamedOneOfRequestInput implements RequestInput { + private final APIGatewayProxyRequestEvent event; + private final Context context; + private final Map interceptorContext; + private final NamedOneOfInput input; + + /** + * Returns the typed request input, with path, query and body parameters + */ + public NamedOneOfInput getInput() { + return this.input; + } + + /** + * Returns the raw API Gateway event + */ + public APIGatewayProxyRequestEvent getEvent() { + return this.event; + } + + /** + * Returns the lambda context + */ + public Context getContext() { + return this.context; + } + + /** + * Returns the interceptor context, which may contain values set by request interceptors + */ + public Map getInterceptorContext() { + return this.interceptorContext; + } +} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestParameters.java": " +package test.test.runtime.api.handlers.named_one_of; + +import test.test.runtime.api.handlers.Handlers; +import java.util.Optional; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.time.OffsetDateTime; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.stream.Collectors; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; + +import test.test.runtime.model.*; + +/** + * Query, path and header parameters for the NamedOneOf operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class NamedOneOfRequestParameters { + + public NamedOneOfRequestParameters(final APIGatewayProxyRequestEvent event) { + Map rawStringParameters = new HashMap<>(); + Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); + Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); + Handlers.putAllFromNullableMap(event.getHeaders(), rawStringParameters); + Map decodedStringParameters = Handlers.decodeRequestParameters(rawStringParameters); + + Map> rawStringArrayParameters = new HashMap<>(); + Handlers.putAllFromNullableMap(event.getMultiValueQueryStringParameters(), rawStringArrayParameters); + Handlers.putAllFromNullableMap(event.getMultiValueHeaders(), rawStringArrayParameters); + Map> decodedStringArrayParameters = Handlers.decodeRequestArrayParameters(rawStringArrayParameters); + + } + +} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfResponse.java": " +package test.test.runtime.api.handlers.named_one_of; + +import test.test.runtime.api.handlers.Response; + +/** + * Response for the namedOneOf operation + */ +public interface NamedOneOfResponse extends Response {} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.Handlers; +import test.test.runtime.api.handlers.*; + +import java.util.List; +import java.util.ArrayList; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import java.util.Collections; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; +import java.io.IOException; +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import org.crac.Core; +import org.crac.Resource; + + +/** + * Lambda handler wrapper for the reservedKeywords operation + */ +public abstract class ReservedKeywords implements RequestHandler, Resource { + { + Core.getGlobalContext().register(this); + } + + /** + * Handle the request for the reservedKeywords operation + */ + public abstract ReservedKeywordsResponse handle(final ReservedKeywordsRequestInput request); + + /** + * Interceptors that the handler class has been decorated with + */ + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(ReservedKeywords.class); + + /** + * For more complex interceptors that require instantiation with parameters, you may override this method to + * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, + * prefer the @Interceptors annotation. + */ + public List> getInterceptors() { + return Collections.emptyList(); + } + + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); + interceptors.addAll(annotationInterceptors); + interceptors.addAll(this.getInterceptors()); + return interceptors; + } + + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + @Override + public Response next(ChainedRequestInput input) { + return handle(new ReservedKeywordsRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + } + }); + } + + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final ReservedKeywordsInput input, final Map interceptorContext) { + return new ChainedRequestInput() { + @Override + public HandlerChain getChain() { + // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining + // chain. + return null; + } + + @Override + public APIGatewayProxyRequestEvent getEvent() { + return event; + } + + @Override + public Context getContext() { + return context; + } + + @Override + public ReservedKeywordsInput getInput() { + return input; + } + + @Override + public Map getInterceptorContext() { + return interceptorContext; + } + }; + } + + @Override + public void beforeCheckpoint(org.crac.Context context) { + // Prime building the handler chain which can take a few 100ms to JIT. + this.buildChain(this.getHandlerInterceptors()); + this.buildChainedRequestInput(null, null, null, null); + + // Initialise instance of Gson and prime serialisation and deserialisation + new JSON(); + JSON.getGson().fromJson(JSON.getGson().toJson(new ApiResponse("", 0, new HashMap<>(), new HashMap<>())), ApiResponse.class); + + try { + // Prime input validation - this will likely fail for the fake event but ensures the code path is optimised + // ready for a real invocation + new ReservedKeywordsInput(new APIGatewayProxyRequestEvent() + .withBody("{}") + .withPathParameters(new HashMap<>()) + .withQueryStringParameters(new HashMap<>()) + .withMultiValueQueryStringParameters(new HashMap<>()) + .withHeaders(new HashMap<>()) + .withMultiValueHeaders(new HashMap<>()) + ); + } catch (Exception e) { + + } + + this.warmUp(); + } + + @Override + public void afterRestore(org.crac.Context context) { + + } + + /** + * Override this method to perform any warmup activities which will be executed prior to the snap-start snapshot. + */ + public void warmUp() { + + } + + @Override + public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent event, final Context context) { + return this.handleRequestWithAdditionalInterceptors(event, context, new ArrayList<>()); + } + + private Map getErrorResponseHeaders(final int statusCode) { + Map headers = new HashMap<>(); + return headers; + } + + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { + final Map interceptorContext = new HashMap<>(); + interceptorContext.put("operationId", "reservedKeywords"); + + List> interceptors = new ArrayList<>(); + interceptors.addAll(additionalInterceptors); + interceptors.addAll(this.getHandlerInterceptors()); + + final HandlerChain chain = this.buildChain(interceptors); + + ReservedKeywordsInput input; + + try { + input = new ReservedKeywordsInput(event); + } catch (RuntimeException e) { + Map headers = new HashMap<>(); + headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); + headers.putAll(this.getErrorResponseHeaders(400)); + return new APIGatewayProxyResponseEvent() + .withStatusCode(400) + .withHeaders(headers) + .withBody("{\\"message\\": \\"" + e.getMessage() + "\\"}"); + } + + final Response response = chain.next(this.buildChainedRequestInput(event, context, input, interceptorContext)); + + Map responseHeaders = new HashMap<>(); + responseHeaders.putAll(this.getErrorResponseHeaders(response.getStatusCode())); + responseHeaders.putAll(response.getHeaders()); + + return new APIGatewayProxyResponseEvent() + .withStatusCode(response.getStatusCode()) + .withHeaders(responseHeaders) + .withMultiValueHeaders(response.getMultiValueHeaders()) + .withBody(response.getBody()); + } +} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords200Response.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import java.util.Map; +import java.util.HashMap; +import java.util.List; + +/** + * Response with status code 200 for the reservedKeywords operation + */ +public class ReservedKeywords200Response extends RuntimeException implements ReservedKeywordsResponse { + static { + // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. + // Create an instance here if required to ensure that the static Gson instance is always available. + if (JSON.getGson() == null) { + new JSON(); + } + } + + private final String body; + + private final Map headers; + private final Map> multiValueHeaders; + + private ReservedKeywords200Response(final Map headers, final Map> multiValueHeaders) { + + this.body = ""; + this.headers = headers; + this.multiValueHeaders = multiValueHeaders; + } + + @Override + public int getStatusCode() { + return 200; + } + + @Override + public String getBody() { + return this.body; + } + + + @Override + public Map getHeaders() { + return this.headers; + } + + @Override + public Map> getMultiValueHeaders() { + return this.multiValueHeaders; + } + + /** + * Create a ReservedKeywords200Response without a body + */ + public static ReservedKeywords200Response of() { + return new ReservedKeywords200Response(new HashMap<>(), new HashMap<>()); + } + + /** + * Create a ReservedKeywords200Response without a body and headers + */ + public static ReservedKeywords200Response of(final Map headers) { + return new ReservedKeywords200Response(headers, new HashMap<>()); + } + + /** + * Create a ReservedKeywords200Response without a body, headers and multi-value headers + */ + public static ReservedKeywords200Response of(final Map headers, final Map> multiValueHeaders) { + return new ReservedKeywords200Response(headers, multiValueHeaders); + } +} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsInput.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import java.util.List; +import java.util.ArrayList; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import java.io.IOException; + +/** + * Input for the reservedKeywords operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class ReservedKeywordsInput { + static { + // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. + // Create an instance here if required to ensure that the static Gson instance is always available. + if (JSON.getGson() == null) { + new JSON(); + } + } + + private final ReservedKeywordsRequestParameters requestParameters; + + public ReservedKeywordsInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new ReservedKeywordsRequestParameters(event); + } + + public ReservedKeywordsRequestParameters getRequestParameters() { + return this.requestParameters; + } + +} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsRequestInput.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.model.*; +import test.test.runtime.api.handlers.RequestInput; +import java.util.List; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import java.io.IOException; +import com.amazonaws.services.lambda.runtime.Context; + +/** + * Full request input for the reservedKeywords operation, including the raw API Gateway event + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class ReservedKeywordsRequestInput implements RequestInput { + private final APIGatewayProxyRequestEvent event; + private final Context context; + private final Map interceptorContext; + private final ReservedKeywordsInput input; + + /** + * Returns the typed request input, with path, query and body parameters + */ + public ReservedKeywordsInput getInput() { + return this.input; + } + + /** + * Returns the raw API Gateway event + */ + public APIGatewayProxyRequestEvent getEvent() { + return this.event; + } + + /** + * Returns the lambda context + */ + public Context getContext() { + return this.context; + } + + /** + * Returns the interceptor context, which may contain values set by request interceptors + */ + public Map getInterceptorContext() { + return this.interceptorContext; + } +} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsRequestParameters.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.api.handlers.Handlers; +import java.util.Optional; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.time.OffsetDateTime; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.stream.Collectors; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; + +import test.test.runtime.model.*; + +/** + * Query, path and header parameters for the ReservedKeywords operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class ReservedKeywordsRequestParameters { + private final Optional with; + private final Optional _if; + private final Optional propertyClass; + + public ReservedKeywordsRequestParameters(final APIGatewayProxyRequestEvent event) { + Map rawStringParameters = new HashMap<>(); + Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); + Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); + Handlers.putAllFromNullableMap(event.getHeaders(), rawStringParameters); + Map decodedStringParameters = Handlers.decodeRequestParameters(rawStringParameters); + + Map> rawStringArrayParameters = new HashMap<>(); + Handlers.putAllFromNullableMap(event.getMultiValueQueryStringParameters(), rawStringArrayParameters); + Handlers.putAllFromNullableMap(event.getMultiValueHeaders(), rawStringArrayParameters); + Map> decodedStringArrayParameters = Handlers.decodeRequestArrayParameters(rawStringArrayParameters); + + this.with = Optional.ofNullable(Handlers.coerceStringParameter("with", false, decodedStringParameters)); + this._if = Optional.ofNullable(Handlers.coerceStringParameter("if", false, decodedStringParameters)); + this.propertyClass = Optional.ofNullable(Handlers.coerceStringParameter("class", false, decodedStringParameters)); + } + + public Optional getWith() { + return this.with; + } + public Optional getIf() { + return this._if; + } + public Optional getPropertyClass() { + return this.propertyClass; + } +} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsResponse.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.api.handlers.Response; + +/** + * Response for the reservedKeywords operation + */ +public interface ReservedKeywordsResponse extends Response {} +", + "src/main/java/test/test/runtime/api/interceptors/DefaultInterceptors.java": "package test.test.runtime.api.interceptors; + +import test.test.runtime.api.interceptors.powertools.LoggingInterceptor; +import test.test.runtime.api.interceptors.powertools.MetricsInterceptor; +import test.test.runtime.api.interceptors.powertools.TracingInterceptor; +import test.test.runtime.api.handlers.Interceptor; + +import java.util.Arrays; +import java.util.List; + +public class DefaultInterceptors { + public static List> all() { + return Arrays.asList( + new ResponseHeadersInterceptor<>(), + new LoggingInterceptor<>(), + new TryCatchInterceptor<>(), + new TracingInterceptor<>(), + new MetricsInterceptor<>() + ); + } +}", + "src/main/java/test/test/runtime/api/interceptors/ResponseHeadersInterceptor.java": "package test.test.runtime.api.interceptors; + +import test.test.runtime.api.handlers.ChainedRequestInput; +import test.test.runtime.api.handlers.Response; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.InterceptorWithWarmup; +import java.util.Map; +import java.util.HashMap; + +/** + * An interceptor for adding cross-origin resource sharing (CORS) headers to the response. + * Allows all origins and headers. + */ +public class ResponseHeadersInterceptor extends InterceptorWithWarmup { + private final Map additionalHeaders; + + public ResponseHeadersInterceptor() { + this.additionalHeaders = new HashMap<>(); + this.additionalHeaders.put("Access-Control-Allow-Origin", "*"); + this.additionalHeaders.put("Access-Control-Allow-Headers", "*"); + } + + public ResponseHeadersInterceptor(final Map headers) { + this.additionalHeaders = headers; + } + + @Override + public Response handle(ChainedRequestInput input) { + Response res = input.getChain().next(input); + res.getHeaders().putAll(this.additionalHeaders); + return res; + } + + public Map getAdditionalHeaders() { + return this.additionalHeaders; + } +} +", + "src/main/java/test/test/runtime/api/interceptors/TryCatchInterceptor.java": "package test.test.runtime.api.interceptors; + +import test.test.runtime.api.handlers.ApiResponse; +import test.test.runtime.api.handlers.ChainedRequestInput; +import test.test.runtime.api.handlers.Response; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.InterceptorWithWarmup; +import org.apache.logging.log4j.Logger; + +/** + * Interceptor for handling uncaught exceptions and responding with a default error response + */ +public class TryCatchInterceptor extends InterceptorWithWarmup { + private final int statusCode; + private final String errorResponseBody; + + public TryCatchInterceptor() { + this(500, "{\\"message\\": \\"Internal Error\\"}"); + } + + public TryCatchInterceptor(final int statusCode, final String errorResponseBody) { + this.statusCode = statusCode; + this.errorResponseBody = errorResponseBody; + } + + @Override + public Response handle(final ChainedRequestInput input) { + try { + return input.getChain().next(input); + } catch (Throwable e) { + if (e instanceof Response) { + return (Response) e; + } + + Object logger = input.getInterceptorContext().get("logger"); + if (logger instanceof Logger) { + ((Logger) logger).error("Interceptor caught exception", e); + } else { + System.err.println("Interceptor caught exception"); + e.printStackTrace(); + } + + return ApiResponse.builder() + .statusCode(this.statusCode) + .body(this.errorResponseBody) + .build(); + } + } +} +", + "src/main/java/test/test/runtime/api/interceptors/powertools/LoggingInterceptor.java": "package test.test.runtime.api.interceptors.powertools; + +import test.test.runtime.api.handlers.ChainedRequestInput; +import test.test.runtime.api.handlers.RequestInput; +import test.test.runtime.api.handlers.Response; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.InterceptorWithWarmup; +import com.amazonaws.services.lambda.runtime.Context; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.ThreadContext; +import software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor; +import software.amazon.lambda.powertools.logging.LoggingUtils; + +/** + * An interceptor which adds an aws lambda powertools logger to the interceptor context, + * and adds the lambda context. + * See https://docs.powertools.aws.dev/lambda/java/latest/core/logging/ + */ +public class LoggingInterceptor extends InterceptorWithWarmup { + private Logger logger = LogManager.getLogger(LoggingInterceptor.class); + + @Override + public void warmUp() { + super.warmUp(); + logger.info("LoggingInterceptor: init"); + } + + /** + * Return the instance of the logger from the interceptor context + */ + public static Logger getLogger(final RequestInput request) { + Object logger = request.getInterceptorContext().get("logger"); + if (logger == null) { + throw new RuntimeException("No logger found. Did you configure the LoggingInterceptor?"); + } + return (Logger) logger; + } + + private void addContext(final Context context) { + LoggingUtils.appendKey("functionName", context.getFunctionName()); + LoggingUtils.appendKey("functionVersion", context.getFunctionVersion()); + LoggingUtils.appendKey("functionArn", context.getInvokedFunctionArn()); + LoggingUtils.appendKey("functionMemorySize", String.valueOf(context.getMemoryLimitInMB())); + // Same casing as powertools aspect implementation + LoggingUtils.appendKey("function_request_id", String.valueOf(context.getAwsRequestId())); + } + + @Override + public Response handle(final ChainedRequestInput input) { + // Add lambda context fields + this.addContext(input.getContext()); + + // Add service, cold start and tracing + LoggingUtils.appendKey("service", LambdaHandlerProcessor.serviceName()); + LoggingUtils.appendKey("coldStart", LambdaHandlerProcessor.isColdStart() ? "true" : "false"); + LambdaHandlerProcessor.getXrayTraceId().ifPresent((xRayTraceId) -> { + LoggingUtils.appendKey("xray_trace_id", xRayTraceId); + }); + + // Add the operation id + String operationId = (String) input.getInterceptorContext().get("operationId"); + LoggingUtils.appendKey("operationId", operationId); + + // Add the logger to the interceptor context + input.getInterceptorContext().put("logger", logger); + + Response response = input.getChain().next(input); + + // Mark cold start done + LambdaHandlerProcessor.coldStartDone(); + + // Clear the logger keys + ThreadContext.clearMap(); + + return response; + } +} +", + "src/main/java/test/test/runtime/api/interceptors/powertools/MetricsInterceptor.java": "package test.test.runtime.api.interceptors.powertools; + +import test.test.runtime.api.handlers.ChainedRequestInput; +import test.test.runtime.api.handlers.RequestInput; +import test.test.runtime.api.handlers.Response; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.InterceptorWithWarmup; +import software.amazon.cloudwatchlogs.emf.logger.MetricsLogger; +import software.amazon.cloudwatchlogs.emf.model.DimensionSet; +import software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor; +import software.amazon.lambda.powertools.metrics.MetricsUtils; + +/** + * Interceptor which adds an instance of aws lambda powertools metrics to the interceptor context (under the key "metrics"), + * and ensures metrics are flushed prior to finishing the lambda execution + * See: https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics + */ +public class MetricsInterceptor extends InterceptorWithWarmup { + private MetricsLogger metrics = MetricsUtils.metricsLogger(); + + /** + * Return the instance of the metrics logger from the interceptor context + */ + public static MetricsLogger getMetrics(final RequestInput request) { + Object metrics = request.getInterceptorContext().get("metrics"); + if (metrics == null) { + throw new RuntimeException("No metrics logger found. Did you configure the MetricsInterceptor?"); + } + return (MetricsLogger) metrics; + } + + @Override + public Response handle(final ChainedRequestInput input) { + metrics.putDimensions(DimensionSet.of("operationId", (String) input.getInterceptorContext().get("operationId"))); + + input.getInterceptorContext().put("metrics", metrics); + + metrics.putProperty("function_request_id", input.getContext().getAwsRequestId()); + LambdaHandlerProcessor.getXrayTraceId().ifPresent((traceId) -> { + metrics.putProperty("xray_trace_id", traceId); + }); + + try { + Response response = input.getChain().next(input); + + // Mark cold start done + LambdaHandlerProcessor.coldStartDone(); + + return response; + } finally { + metrics.flush(); + } + } +} +", + "src/main/java/test/test/runtime/api/interceptors/powertools/TracingInterceptor.java": "package test.test.runtime.api.interceptors.powertools; + +import test.test.runtime.api.handlers.ChainedRequestInput; +import test.test.runtime.api.handlers.Response; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.InterceptorWithWarmup; +import com.amazonaws.xray.AWSXRay; +import com.amazonaws.xray.AWSXRayRecorderBuilder; +import com.amazonaws.xray.entities.Subsegment; +import com.fasterxml.jackson.core.JsonProcessingException; +import org.apache.logging.log4j.Logger; +import software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor; +import software.amazon.lambda.powertools.tracing.TracingUtils; + +/** + * Interceptor which adds an aws lambda powertools tracer to the interceptor context, + * creating the appropriate segment for the handler execution and annotating with recommended + * details. + * See: https://docs.powertools.aws.dev/lambda/java/latest/core/tracing/ + */ +public class TracingInterceptor extends InterceptorWithWarmup { + + static { + AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard(); + AWSXRay.setGlobalRecorder(builder.build()); + } + + private final boolean captureResponse; + + public TracingInterceptor(final boolean captureResponse) { + this.captureResponse = captureResponse; + } + + public TracingInterceptor() { + this(false); + } + + @Override + public void warmUp() { + try { + // Set a dummy trace header to ensure the regular subsegment code path is followed and warmed. + // The segment is not actually recorded by xray. + System.setProperty("com.amazonaws.xray.traceHeader", "Root=1-xxx;Parent=yyy;Sampled=1"); + super.warmUp(); + } finally { + System.clearProperty("com.amazonaws.xray.traceHeader"); + } + } + + private void logError(final String message, final ChainedRequestInput input, final Throwable e) { + Object logger = input.getInterceptorContext().get("logger"); + if (logger instanceof Logger) { + ((Logger) logger).error(message, e); + } else { + System.err.println(message); + e.printStackTrace(); + } + } + + @Override + public Response handle(final ChainedRequestInput input) { + String operationId = (String) input.getInterceptorContext().get("operationId"); + Subsegment segment = AWSXRay.beginSubsegment("## " + operationId); + + segment.setNamespace(operationId); + segment.putAnnotation("ColdStart", LambdaHandlerProcessor.isColdStart()); + segment.putAnnotation("Service", LambdaHandlerProcessor.serviceName()); + + try { + Response response = input.getChain().next(input); + + try { + if (this.captureResponse) { + segment.putMetadata(operationId + " response", TracingUtils.objectMapper() != null ? TracingUtils.objectMapper().writeValueAsString(response) : response); + } + } catch (JsonProcessingException e) { + this.logError("Failed to add response to trace", input, e); + } + + // Mark cold start done + LambdaHandlerProcessor.coldStartDone(); + + return response; + } catch (Throwable e) { + try { + segment.putMetadata(operationId + " error", TracingUtils.objectMapper() != null ? TracingUtils.objectMapper().writeValueAsString(e) : e); + } catch (JsonProcessingException ex) { + this.logError("Failed to add error to trace", input, e); + } + throw e; + } finally { + if (!LambdaHandlerProcessor.isSamLocal()) { + AWSXRay.endSubsegment(); + } + } + } +} +", + "src/main/java/test/test/runtime/api/operation_config/OperationConfig.java": "package test.test.runtime.api.operation_config; + +import test.test.runtime.model.*; + +import java.util.HashMap; +import java.util.Map; + +// Generic type for object "keyed" by operation names +@lombok.Builder @lombok.Getter +public class OperationConfig { + private T arrayOfOneOfs; + private T arrayRequestParameters; + private T inlineEnum; + private T inlineRequestBody; + private T namedOneOf; + private T reservedKeywords; + + public Map asMap() { Map map = new HashMap<>(); + map.put("arrayOfOneOfs", this.arrayOfOneOfs); map.put("arrayRequestParameters", this.arrayRequestParameters); map.put("inlineEnum", this.inlineEnum); map.put("inlineRequestBody", this.inlineRequestBody); + map.put("namedOneOf", this.namedOneOf); map.put("reservedKeywords", this.reservedKeywords); return map; } } ", - "src/main/java/test/test/runtime/api/operation_config/OperationLookup.java": "package test.test.runtime.api.operation_config; + "src/main/java/test/test/runtime/api/operation_config/OperationLookup.java": "package test.test.runtime.api.operation_config; + +import test.test.runtime.model.*; + +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.Arrays; + + +// Look up path and http method for a given operation name +public class OperationLookup { + @lombok.Builder @lombok.Getter + public static class OperationLookupEntry { + private String method; + private String path; + private List contentTypes; + } + + /** + * Returns the operation lookup information for the TypeSafeRestApi construct + */ + public static Map getOperationLookup() { + final Map config = new HashMap<>(); + + config.put("arrayOfOneOfs", OperationLookupEntry.builder() + .path("/array-of-one-ofs") + .method("POST") + .contentTypes(Arrays.asList("application/json")) + .build()); + config.put("arrayRequestParameters", OperationLookupEntry.builder() + .path("/array-request-parameters") + .method("GET") + .contentTypes(Arrays.asList("application/json")) + .build()); + config.put("inlineEnum", OperationLookupEntry.builder() + .path("/inline-enum") + .method("GET") + .contentTypes(Arrays.asList("application/json")) + .build()); + config.put("inlineRequestBody", OperationLookupEntry.builder() + .path("/inline-request-body") + .method("POST") + .contentTypes(Arrays.asList("application/json")) + .build()); + config.put("namedOneOf", OperationLookupEntry.builder() + .path("/named-one-of") + .method("POST") + .contentTypes(Arrays.asList("application/json")) + .build()); + config.put("reservedKeywords", OperationLookupEntry.builder() + .path("/reserved-keywords") + .method("GET") + .contentTypes(Arrays.asList("application/json")) + .build()); + + return config; + } +} +", + "src/main/java/test/test/runtime/api/operation_config/Operations.java": "package test.test.runtime.api.operation_config; + +public class Operations { + /** + * Returns an OperationConfig Builder with all values populated with the given value. + * You can override specific values on the builder if you like. + * Make sure you call \`.build()\` at the end to construct the OperationConfig. + */ + public static OperationConfig.OperationConfigBuilder all(final T value) { + return OperationConfig.builder() + .arrayOfOneOfs(value) + .arrayRequestParameters(value) + .inlineEnum(value) + .inlineRequestBody(value) + .namedOneOf(value) + .reservedKeywords(value) + ; + } +} +", + "src/main/java/test/test/runtime/auth/ApiKeyAuth.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.auth; + +import test.test.runtime.ApiException; +import test.test.runtime.Pair; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } else if ("cookie".equals(location)) { + cookieParams.put(paramName, value); + } + } +} +", + "src/main/java/test/test/runtime/auth/Authentication.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.auth; + +import test.test.runtime.Pair; +import test.test.runtime.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + * @param cookieParams Map of cookie parameters + * @param payload HTTP request body + * @param method HTTP method + * @param uri URI + * @throws ApiException if failed to update the parameters + */ + void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException; +} +", + "src/main/java/test/test/runtime/auth/HttpBasicAuth.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.auth; + +import test.test.runtime.Pair; +import test.test.runtime.ApiException; + +import okhttp3.Credentials; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); + } +} +", + "src/main/java/test/test/runtime/auth/HttpBearerAuth.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.auth; + +import test.test.runtime.ApiException; +import test.test.runtime.Pair; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +public class HttpBearerAuth implements Authentication { + private final String scheme; + private String bearerToken; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return bearerToken; + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ + public void setBearerToken(String bearerToken) { + this.bearerToken = bearerToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + if (bearerToken == null) { + return; + } + + headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} +", + "src/main/java/test/test/runtime/model/AbstractOpenApiSchema.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.model; + +import test.test.runtime.ApiException; +import java.util.Objects; +import java.lang.reflect.Type; +import java.util.Map; +import javax.ws.rs.core.GenericType; + +//import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public abstract class AbstractOpenApiSchema { + + // store the actual instance of the schema/object + private Object instance; + + // is nullable + private Boolean isNullable; + + // schema type (e.g. oneOf, anyOf) + private final String schemaType; + + public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { + this.schemaType = schemaType; + this.isNullable = isNullable; + } + + /** + * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object + * + * @return an instance of the actual schema/object + */ + public abstract Map getSchemas(); + + /** + * Get the actual instance + * + * @return an instance of the actual schema/object + */ + //@JsonValue + public Object getActualInstance() {return instance;} + + /** + * Set the actual instance + * + * @param instance the actual instance of the schema/object + */ + public void setActualInstance(Object instance) {this.instance = instance;} + + /** + * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well + * + * @return an instance of the actual schema/object + */ + public Object getActualInstanceRecursively() { + return getActualInstanceRecursively(this); + } + + private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { + if (object.getActualInstance() == null) { + return null; + } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { + return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); + } else { + return object.getActualInstance(); + } + } + + /** + * Get the schema type (e.g. anyOf, oneOf) + * + * @return the schema type + */ + public String getSchemaType() { + return schemaType; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ").append(getClass()).append(" {\\n"); + sb.append(" instance: ").append(toIndentedString(instance)).append("\\n"); + sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\\n"); + sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\\n", "\\n "); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; + return Objects.equals(this.instance, a.instance) && + Objects.equals(this.isNullable, a.isNullable) && + Objects.equals(this.schemaType, a.schemaType); + } + + @Override + public int hashCode() { + return Objects.hash(instance, isNullable, schemaType); + } + + /** + * Is nullable + * + * @return true if it's nullable + */ + public Boolean isNullable() { + if (Boolean.TRUE.equals(isNullable)) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + + +} +", + "src/main/java/test/test/runtime/model/AnotherNamedOneOf.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ -import test.test.runtime.model.*; +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; +import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import java.util.List; -import java.util.Arrays; +import java.util.Set; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; -// Look up path and http method for a given operation name -public class OperationLookup { - @lombok.Builder @lombok.Getter - public static class OperationLookupEntry { - private String method; - private String path; - private List contentTypes; +import test.test.runtime.JSON; + +/** + * AnotherNamedOneOf + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public class AnotherNamedOneOf { + public static final String SERIALIZED_NAME_BAR = "bar"; + @SerializedName(SERIALIZED_NAME_BAR) + private String bar; + + public AnotherNamedOneOf() { + } + + public AnotherNamedOneOf bar(String bar) { + + this.bar = bar; + return this; + } + + /** + * Get bar + * @return bar + **/ + @javax.annotation.Nullable + public String getBar() { + return bar; + } + + + public void setBar(String bar) { + this.bar = bar; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; } + AnotherNamedOneOf anotherNamedOneOf = (AnotherNamedOneOf) o; + return Objects.equals(this.bar, anotherNamedOneOf.bar); + + } - /** - * Returns the operation lookup information for the TypeSafeRestApi construct - */ - public static Map getOperationLookup() { - final Map config = new HashMap<>(); + @Override + public int hashCode() { + return Objects.hash(bar); + } - config.put("arrayRequestParameters", OperationLookupEntry.builder() - .path("/array-request-parameters") - .method("GET") - .contentTypes(Arrays.asList("application/json")) - .build()); - config.put("inlineEnum", OperationLookupEntry.builder() - .path("/inline-enum") - .method("GET") - .contentTypes(Arrays.asList("application/json")) - .build()); - config.put("inlineRequestBody", OperationLookupEntry.builder() - .path("/inline-request-body") - .method("POST") - .contentTypes(Arrays.asList("application/json")) - .build()); - config.put("reservedKeywords", OperationLookupEntry.builder() - .path("/reserved-keywords") - .method("GET") - .contentTypes(Arrays.asList("application/json")) - .build()); + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnotherNamedOneOf {\\n"); + sb.append(" bar: ").append(toIndentedString(bar)).append("\\n"); + sb.append("}"); + return sb.toString(); + } - return config; + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; } -} -", - "src/main/java/test/test/runtime/api/operation_config/Operations.java": "package test.test.runtime.api.operation_config; + return o.toString().replace("\\n", "\\n "); + } -public class Operations { - /** - * Returns an OperationConfig Builder with all values populated with the given value. - * You can override specific values on the builder if you like. - * Make sure you call \`.build()\` at the end to construct the OperationConfig. - */ - public static OperationConfig.OperationConfigBuilder all(final T value) { - return OperationConfig.builder() - .arrayRequestParameters(value) - .inlineEnum(value) - .inlineRequestBody(value) - .reservedKeywords(value) - ; + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("bar"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to AnotherNamedOneOf + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!AnotherNamedOneOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AnotherNamedOneOf is not found in the empty JSON string", AnotherNamedOneOf.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!AnotherNamedOneOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`AnotherNamedOneOf\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`bar\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("bar").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AnotherNamedOneOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AnotherNamedOneOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AnotherNamedOneOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AnotherNamedOneOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public AnotherNamedOneOf read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); } + } + + /** + * Create an instance of AnotherNamedOneOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of AnotherNamedOneOf + * @throws IOException if the JSON string is invalid with respect to AnotherNamedOneOf + */ + public static AnotherNamedOneOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AnotherNamedOneOf.class); + } + + /** + * Convert an instance of AnotherNamedOneOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } } ", - "src/main/java/test/test/runtime/auth/ApiKeyAuth.java": "/* + "src/main/java/test/test/runtime/model/ArrayOfOneOfs.java": "/* * Edge Cases * * @@ -36914,74 +38692,230 @@ public class Operations { */ -package test.test.runtime.auth; +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; +import test.test.runtime.model.NamedOneOfUnion; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; -import test.test.runtime.ApiException; -import test.test.runtime.Pair; +import javax.ws.rs.core.GenericType; +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import java.util.List; +import java.util.Set; -public class ApiKeyAuth implements Authentication { - private final String location; - private final String paramName; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; - private String apiKey; - private String apiKeyPrefix; +import test.test.runtime.JSON; - public ApiKeyAuth(String location, String paramName) { - this.location = location; - this.paramName = paramName; +/** + * ArrayOfOneOfs + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public class ArrayOfOneOfs { + public static final String SERIALIZED_NAME_ONE_OFS = "oneOfs"; + @SerializedName(SERIALIZED_NAME_ONE_OFS) + private List oneOfs = null; + + public ArrayOfOneOfs() { } - public String getLocation() { - return location; + public ArrayOfOneOfs oneOfs(List oneOfs) { + + this.oneOfs = oneOfs; + return this; } - public String getParamName() { - return paramName; + public ArrayOfOneOfs addOneOfsItem(NamedOneOfUnion oneOfsItem) { + if (this.oneOfs == null) { + this.oneOfs = new ArrayList<>(); + } + this.oneOfs.add(oneOfsItem); + return this; } - public String getApiKey() { - return apiKey; + /** + * Get oneOfs + * @return oneOfs + **/ + @javax.annotation.Nullable + public List getOneOfs() { + return oneOfs; } - public void setApiKey(String apiKey) { - this.apiKey = apiKey; + + public void setOneOfs(List oneOfs) { + this.oneOfs = oneOfs; } - public String getApiKeyPrefix() { - return apiKeyPrefix; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfOneOfs arrayOfOneOfs = (ArrayOfOneOfs) o; + return Objects.equals(this.oneOfs, arrayOfOneOfs.oneOfs); + } - public void setApiKeyPrefix(String apiKeyPrefix) { - this.apiKeyPrefix = apiKeyPrefix; + @Override + public int hashCode() { + return Objects.hash(oneOfs); } @Override - public void applyToParams(List queryParams, Map headerParams, Map cookieParams, - String payload, String method, URI uri) throws ApiException { - if (apiKey == null) { - return; - } - String value; - if (apiKeyPrefix != null) { - value = apiKeyPrefix + " " + apiKey; - } else { - value = apiKey; + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfOneOfs {\\n"); + sb.append(" oneOfs: ").append(toIndentedString(oneOfs)).append("\\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; } - if ("query".equals(location)) { - queryParams.add(new Pair(paramName, value)); - } else if ("header".equals(location)) { - headerParams.put(paramName, value); - } else if ("cookie".equals(location)) { - cookieParams.put(paramName, value); + return o.toString().replace("\\n", "\\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("oneOfs"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to ArrayOfOneOfs + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!ArrayOfOneOfs.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfOneOfs is not found in the empty JSON string", ArrayOfOneOfs.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!ArrayOfOneOfs.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`ArrayOfOneOfs\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + // ensure the optional json data is an array if present + if (jsonObj.get("oneOfs") != null && !jsonObj.get("oneOfs").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field \`oneOfs\` to be an array in the JSON string but got \`%s\`", jsonObj.get("oneOfs").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayOfOneOfs.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayOfOneOfs' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayOfOneOfs.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayOfOneOfs value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ArrayOfOneOfs read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); } } + + /** + * Create an instance of ArrayOfOneOfs given an JSON string + * + * @param jsonString JSON string + * @return An instance of ArrayOfOneOfs + * @throws IOException if the JSON string is invalid with respect to ArrayOfOneOfs + */ + public static ArrayOfOneOfs fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ArrayOfOneOfs.class); + } + + /** + * Convert an instance of ArrayOfOneOfs to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } } ", - "src/main/java/test/test/runtime/auth/Authentication.java": "/* + "src/main/java/test/test/runtime/model/InlineEnum200Response.java": "/* * Edge Cases * * @@ -36993,150 +38927,222 @@ public class ApiKeyAuth implements Authentication { */ -package test.test.runtime.auth; +package test.test.runtime.model; -import test.test.runtime.Pair; -import test.test.runtime.ApiException; +import java.util.Objects; +import java.util.Arrays; +import test.test.runtime.model.InlineEnum200ResponseCategoryEnum; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import java.util.List; +import java.util.Set; -public interface Authentication { - /** - * Apply authentication settings to header and query params. - * - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - * @param cookieParams Map of cookie parameters - * @param payload HTTP request body - * @param method HTTP method - * @param uri URI - * @throws ApiException if failed to update the parameters - */ - void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException; -} -", - "src/main/java/test/test/runtime/auth/HttpBasicAuth.java": "/* - * Edge Cases - * - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated. - * Do not edit the class manually. +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import test.test.runtime.JSON; + +/** + * InlineEnum200Response */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public class InlineEnum200Response { + public static final String SERIALIZED_NAME_CATEGORY = "category"; + @SerializedName(SERIALIZED_NAME_CATEGORY) + private InlineEnum200ResponseCategoryEnum category; + public InlineEnum200Response() { + } -package test.test.runtime.auth; + public InlineEnum200Response category(InlineEnum200ResponseCategoryEnum category) { -import test.test.runtime.Pair; -import test.test.runtime.ApiException; + this.category = category; + return this; + } -import okhttp3.Credentials; + /** + * Get category + * @return category + **/ + @javax.annotation.Nullable + public InlineEnum200ResponseCategoryEnum getCategory() { + return category; + } -import java.net.URI; -import java.util.Map; -import java.util.List; -import java.io.UnsupportedEncodingException; + public void setCategory(InlineEnum200ResponseCategoryEnum category) { + this.category = category; + } -public class HttpBasicAuth implements Authentication { - private String username; - private String password; - public String getUsername() { - return username; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - public void setUsername(String username) { - this.username = username; + if (o == null || getClass() != o.getClass()) { + return false; } + InlineEnum200Response inlineEnum200Response = (InlineEnum200Response) o; + return Objects.equals(this.category, inlineEnum200Response.category); + + } - public String getPassword() { - return password; - } + @Override + public int hashCode() { + return Objects.hash(category); + } - public void setPassword(String password) { - this.password = password; - } + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class InlineEnum200Response {\\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\\n"); + sb.append("}"); + return sb.toString(); + } - @Override - public void applyToParams(List queryParams, Map headerParams, Map cookieParams, - String payload, String method, URI uri) throws ApiException { - if (username == null && password == null) { - return; - } - headerParams.put("Authorization", Credentials.basic( - username == null ? "" : username, - password == null ? "" : password)); + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; } -} -", - "src/main/java/test/test/runtime/auth/HttpBearerAuth.java": "/* - * Edge Cases - * - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated. - * Do not edit the class manually. - */ + return o.toString().replace("\\n", "\\n "); + } -package test.test.runtime.auth; + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; -import test.test.runtime.ApiException; -import test.test.runtime.Pair; + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("category"); -import java.net.URI; -import java.util.Map; -import java.util.List; + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } -public class HttpBearerAuth implements Authentication { - private final String scheme; - private String bearerToken; + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to InlineEnum200Response + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!InlineEnum200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in InlineEnum200Response is not found in the empty JSON string", InlineEnum200Response.openapiRequiredFields.toString())); + } + } - public HttpBearerAuth(String scheme) { - this.scheme = scheme; + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!InlineEnum200Response.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`InlineEnum200Response\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + // validate the optional field \`category\` + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { + InlineEnum200ResponseCategoryEnum.validateJsonObject(jsonObj.getAsJsonObject("category")); + } } - /** - * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. - * - * @return The bearer token - */ - public String getBearerToken() { - return bearerToken; - } + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!InlineEnum200Response.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'InlineEnum200Response' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(InlineEnum200Response.class)); - /** - * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. - * - * @param bearerToken The bearer token to send in the Authorization header - */ - public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; - } + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, InlineEnum200Response value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } - @Override - public void applyToParams(List queryParams, Map headerParams, Map cookieParams, - String payload, String method, URI uri) throws ApiException { - if (bearerToken == null) { - return; + @Override + public InlineEnum200Response read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); } + } - headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + /** + * Create an instance of InlineEnum200Response given an JSON string + * + * @param jsonString JSON string + * @return An instance of InlineEnum200Response + * @throws IOException if the JSON string is invalid with respect to InlineEnum200Response + */ + public static InlineEnum200Response fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, InlineEnum200Response.class); } - private static String upperCaseBearer(String scheme) { - return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + /** + * Convert an instance of InlineEnum200Response to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); } } ", - "src/main/java/test/test/runtime/model/AbstractOpenApiSchema.java": "/* + "src/main/java/test/test/runtime/model/InlineEnum200ResponseCategoryEnum.java": "/* * Edge Cases * * @@ -37150,142 +39156,107 @@ public class HttpBearerAuth implements Authentication { package test.test.runtime.model; -import test.test.runtime.ApiException; import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; +import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; import java.util.Map; -import javax.ws.rs.core.GenericType; +import java.util.Map.Entry; +import java.util.List; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; -//import com.fasterxml.jackson.annotation.JsonValue; +import test.test.runtime.JSON; /** - * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec + * Gets or Sets InlineEnum200ResponseCategoryEnum */ -@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder -public abstract class AbstractOpenApiSchema { - - // store the actual instance of the schema/object - private Object instance; - - // is nullable - private Boolean isNullable; - - // schema type (e.g. oneOf, anyOf) - private final String schemaType; +@JsonAdapter(InlineEnum200ResponseCategoryEnum.Adapter.class) +public enum InlineEnum200ResponseCategoryEnum { - public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { - this.schemaType = schemaType; - this.isNullable = isNullable; - } + FRUIT("fruit"), - /** - * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object - * - * @return an instance of the actual schema/object - */ - public abstract Map getSchemas(); + VEGETABLE("vegetable"); - /** - * Get the actual instance - * - * @return an instance of the actual schema/object - */ - //@JsonValue - public Object getActualInstance() {return instance;} + private String value; - /** - * Set the actual instance - * - * @param instance the actual instance of the schema/object - */ - public void setActualInstance(Object instance) {this.instance = instance;} + InlineEnum200ResponseCategoryEnum(String value) { + this.value = value; + } - /** - * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well - * - * @return an instance of the actual schema/object - */ - public Object getActualInstanceRecursively() { - return getActualInstanceRecursively(this); - } + public String getValue() { + return value; + } - private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { - if (object.getActualInstance() == null) { - return null; - } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { - return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); - } else { - return object.getActualInstance(); - } - } + @Override + public String toString() { + return String.valueOf(value); + } - /** - * Get the schema type (e.g. anyOf, oneOf) - * - * @return the schema type - */ - public String getSchemaType() { - return schemaType; + public static InlineEnum200ResponseCategoryEnum fromValue(String value) { + for (InlineEnum200ResponseCategoryEnum b : InlineEnum200ResponseCategoryEnum.values()) { + if (b.value.equals(value)) { + return b; + } } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + public static class Adapter extends TypeAdapter { @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ").append(getClass()).append(" {\\n"); - sb.append(" instance: ").append(toIndentedString(instance)).append("\\n"); - sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\\n"); - sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\\n", "\\n "); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; - return Objects.equals(this.instance, a.instance) && - Objects.equals(this.isNullable, a.isNullable) && - Objects.equals(this.schemaType, a.schemaType); + public void write(final JsonWriter jsonWriter, final InlineEnum200ResponseCategoryEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); } @Override - public int hashCode() { - return Objects.hash(instance, isNullable, schemaType); - } - - /** - * Is nullable - * - * @return true if it's nullable - */ - public Boolean isNullable() { - if (Boolean.TRUE.equals(isNullable)) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } + public InlineEnum200ResponseCategoryEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return InlineEnum200ResponseCategoryEnum.fromValue(value); } - - - + } } ", - "src/main/java/test/test/runtime/model/InlineEnum200Response.java": "/* + "src/main/java/test/test/runtime/model/InlineRequestBodyRequestContent.java": "/* * Edge Cases * * @@ -37301,7 +39272,6 @@ package test.test.runtime.model; import java.util.Objects; import java.util.Arrays; -import test.test.runtime.model.InlineEnum200ResponseCategoryEnum; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; @@ -37353,35 +39323,35 @@ import com.google.gson.JsonParseException; import test.test.runtime.JSON; /** - * InlineEnum200Response + * InlineRequestBodyRequestContent */ @lombok.AllArgsConstructor @lombok.experimental.SuperBuilder -public class InlineEnum200Response { - public static final String SERIALIZED_NAME_CATEGORY = "category"; - @SerializedName(SERIALIZED_NAME_CATEGORY) - private InlineEnum200ResponseCategoryEnum category; +public class InlineRequestBodyRequestContent { + public static final String SERIALIZED_NAME_SOME_PROPERTY = "someProperty"; + @SerializedName(SERIALIZED_NAME_SOME_PROPERTY) + private String someProperty; - public InlineEnum200Response() { + public InlineRequestBodyRequestContent() { } - public InlineEnum200Response category(InlineEnum200ResponseCategoryEnum category) { + public InlineRequestBodyRequestContent someProperty(String someProperty) { - this.category = category; + this.someProperty = someProperty; return this; } /** - * Get category - * @return category + * Get someProperty + * @return someProperty **/ - @javax.annotation.Nullable - public InlineEnum200ResponseCategoryEnum getCategory() { - return category; + @javax.annotation.Nonnull + public String getSomeProperty() { + return someProperty; } - public void setCategory(InlineEnum200ResponseCategoryEnum category) { - this.category = category; + public void setSomeProperty(String someProperty) { + this.someProperty = someProperty; } @@ -37393,21 +39363,21 @@ public class InlineEnum200Response { if (o == null || getClass() != o.getClass()) { return false; } - InlineEnum200Response inlineEnum200Response = (InlineEnum200Response) o; - return Objects.equals(this.category, inlineEnum200Response.category); + InlineRequestBodyRequestContent inlineRequestBodyRequestContent = (InlineRequestBodyRequestContent) o; + return Objects.equals(this.someProperty, inlineRequestBodyRequestContent.someProperty); } @Override public int hashCode() { - return Objects.hash(category); + return Objects.hash(someProperty); } @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class InlineEnum200Response {\\n"); - sb.append(" category: ").append(toIndentedString(category)).append("\\n"); + sb.append("class InlineRequestBodyRequestContent {\\n"); + sb.append(" someProperty: ").append(toIndentedString(someProperty)).append("\\n"); sb.append("}"); return sb.toString(); } @@ -37430,35 +39400,42 @@ public class InlineEnum200Response { static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet(); - openapiFields.add("category"); + openapiFields.add("someProperty"); // a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("someProperty"); } /** * Validates the JSON Object and throws an exception if issues found * * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to InlineEnum200Response + * @throws IOException if the JSON Object is invalid with respect to InlineRequestBodyRequestContent */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (!InlineEnum200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null - throw new IllegalArgumentException(String.format("The required field(s) %s in InlineEnum200Response is not found in the empty JSON string", InlineEnum200Response.openapiRequiredFields.toString())); + if (!InlineRequestBodyRequestContent.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in InlineRequestBodyRequestContent is not found in the empty JSON string", InlineRequestBodyRequestContent.openapiRequiredFields.toString())); } } Set> entries = jsonObj.entrySet(); // check to see if the JSON string contains additional fields for (Entry entry : entries) { - if (!InlineEnum200Response.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`InlineEnum200Response\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + if (!InlineRequestBodyRequestContent.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`InlineRequestBodyRequestContent\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - // validate the optional field \`category\` - if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { - InlineEnum200ResponseCategoryEnum.validateJsonObject(jsonObj.getAsJsonObject("category")); + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : InlineRequestBodyRequestContent.openapiRequiredFields) { + if (jsonObj.get(requiredField) == null) { + throw new IllegalArgumentException(String.format("The required field \`%s\` is not found in the JSON string: %s", requiredField, jsonObj.toString())); + } + } + if (!jsonObj.get("someProperty").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`someProperty\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("someProperty").toString())); } } @@ -37466,22 +39443,22 @@ public class InlineEnum200Response { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { - if (!InlineEnum200Response.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'InlineEnum200Response' and its subtypes + if (!InlineRequestBodyRequestContent.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'InlineRequestBodyRequestContent' and its subtypes } final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(InlineEnum200Response.class)); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(InlineRequestBodyRequestContent.class)); - return (TypeAdapter) new TypeAdapter() { + return (TypeAdapter) new TypeAdapter() { @Override - public void write(JsonWriter out, InlineEnum200Response value) throws IOException { + public void write(JsonWriter out, InlineRequestBodyRequestContent value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); elementAdapter.write(out, obj); } @Override - public InlineEnum200Response read(JsonReader in) throws IOException { + public InlineRequestBodyRequestContent read(JsonReader in) throws IOException { JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); validateJsonObject(jsonObj); return thisAdapter.fromJsonTree(jsonObj); @@ -37492,18 +39469,18 @@ public class InlineEnum200Response { } /** - * Create an instance of InlineEnum200Response given an JSON string + * Create an instance of InlineRequestBodyRequestContent given an JSON string * * @param jsonString JSON string - * @return An instance of InlineEnum200Response - * @throws IOException if the JSON string is invalid with respect to InlineEnum200Response + * @return An instance of InlineRequestBodyRequestContent + * @throws IOException if the JSON string is invalid with respect to InlineRequestBodyRequestContent */ - public static InlineEnum200Response fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, InlineEnum200Response.class); + public static InlineRequestBodyRequestContent fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, InlineRequestBodyRequestContent.class); } /** - * Convert an instance of InlineEnum200Response to an JSON string + * Convert an instance of InlineRequestBodyRequestContent to an JSON string * * @return JSON string */ @@ -37512,7 +39489,7 @@ public class InlineEnum200Response { } } ", - "src/main/java/test/test/runtime/model/InlineEnum200ResponseCategoryEnum.java": "/* + "src/main/java/test/test/runtime/model/MyEnum.java": "/* * Edge Cases * * @@ -37579,18 +39556,20 @@ import com.google.gson.JsonParseException; import test.test.runtime.JSON; /** - * Gets or Sets InlineEnum200ResponseCategoryEnum + * Gets or Sets MyEnum */ -@JsonAdapter(InlineEnum200ResponseCategoryEnum.Adapter.class) -public enum InlineEnum200ResponseCategoryEnum { +@JsonAdapter(MyEnum.Adapter.class) +public enum MyEnum { - FRUIT("fruit"), + ONE("one"), - VEGETABLE("vegetable"); + TWO("two"), + + THREE("three"); private String value; - InlineEnum200ResponseCategoryEnum(String value) { + MyEnum(String value) { this.value = value; } @@ -37603,8 +39582,8 @@ public enum InlineEnum200ResponseCategoryEnum { return String.valueOf(value); } - public static InlineEnum200ResponseCategoryEnum fromValue(String value) { - for (InlineEnum200ResponseCategoryEnum b : InlineEnum200ResponseCategoryEnum.values()) { + public static MyEnum fromValue(String value) { + for (MyEnum b : MyEnum.values()) { if (b.value.equals(value)) { return b; } @@ -37612,21 +39591,21 @@ public enum InlineEnum200ResponseCategoryEnum { throw new IllegalArgumentException("Unexpected value '" + value + "'"); } - public static class Adapter extends TypeAdapter { + public static class Adapter extends TypeAdapter { @Override - public void write(final JsonWriter jsonWriter, final InlineEnum200ResponseCategoryEnum enumeration) throws IOException { + public void write(final JsonWriter jsonWriter, final MyEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override - public InlineEnum200ResponseCategoryEnum read(final JsonReader jsonReader) throws IOException { + public MyEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); - return InlineEnum200ResponseCategoryEnum.fromValue(value); + return MyEnum.fromValue(value); } } } ", - "src/main/java/test/test/runtime/model/InlineRequestBodyRequestContent.java": "/* + "src/main/java/test/test/runtime/model/NamedOneOf.java": "/* * Edge Cases * * @@ -37693,35 +39672,35 @@ import com.google.gson.JsonParseException; import test.test.runtime.JSON; /** - * InlineRequestBodyRequestContent + * NamedOneOf */ @lombok.AllArgsConstructor @lombok.experimental.SuperBuilder -public class InlineRequestBodyRequestContent { - public static final String SERIALIZED_NAME_SOME_PROPERTY = "someProperty"; - @SerializedName(SERIALIZED_NAME_SOME_PROPERTY) - private String someProperty; +public class NamedOneOf { + public static final String SERIALIZED_NAME_FOO = "foo"; + @SerializedName(SERIALIZED_NAME_FOO) + private String foo; - public InlineRequestBodyRequestContent() { + public NamedOneOf() { } - public InlineRequestBodyRequestContent someProperty(String someProperty) { + public NamedOneOf foo(String foo) { - this.someProperty = someProperty; + this.foo = foo; return this; } /** - * Get someProperty - * @return someProperty + * Get foo + * @return foo **/ - @javax.annotation.Nonnull - public String getSomeProperty() { - return someProperty; + @javax.annotation.Nullable + public String getFoo() { + return foo; } - public void setSomeProperty(String someProperty) { - this.someProperty = someProperty; + public void setFoo(String foo) { + this.foo = foo; } @@ -37733,21 +39712,21 @@ public class InlineRequestBodyRequestContent { if (o == null || getClass() != o.getClass()) { return false; } - InlineRequestBodyRequestContent inlineRequestBodyRequestContent = (InlineRequestBodyRequestContent) o; - return Objects.equals(this.someProperty, inlineRequestBodyRequestContent.someProperty); + NamedOneOf namedOneOf = (NamedOneOf) o; + return Objects.equals(this.foo, namedOneOf.foo); } @Override public int hashCode() { - return Objects.hash(someProperty); + return Objects.hash(foo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class InlineRequestBodyRequestContent {\\n"); - sb.append(" someProperty: ").append(toIndentedString(someProperty)).append("\\n"); + sb.append("class NamedOneOf {\\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\\n"); sb.append("}"); return sb.toString(); } @@ -37770,42 +39749,34 @@ public class InlineRequestBodyRequestContent { static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet(); - openapiFields.add("someProperty"); + openapiFields.add("foo"); // a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("someProperty"); } /** * Validates the JSON Object and throws an exception if issues found * * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to InlineRequestBodyRequestContent + * @throws IOException if the JSON Object is invalid with respect to NamedOneOf */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (!InlineRequestBodyRequestContent.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null - throw new IllegalArgumentException(String.format("The required field(s) %s in InlineRequestBodyRequestContent is not found in the empty JSON string", InlineRequestBodyRequestContent.openapiRequiredFields.toString())); + if (!NamedOneOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in NamedOneOf is not found in the empty JSON string", NamedOneOf.openapiRequiredFields.toString())); } } Set> entries = jsonObj.entrySet(); // check to see if the JSON string contains additional fields for (Entry entry : entries) { - if (!InlineRequestBodyRequestContent.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`InlineRequestBodyRequestContent\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : InlineRequestBodyRequestContent.openapiRequiredFields) { - if (jsonObj.get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field \`%s\` is not found in the JSON string: %s", requiredField, jsonObj.toString())); + if (!NamedOneOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`NamedOneOf\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (!jsonObj.get("someProperty").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field \`someProperty\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("someProperty").toString())); + if ((jsonObj.get("foo") != null && !jsonObj.get("foo").isJsonNull()) && !jsonObj.get("foo").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`foo\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("foo").toString())); } } @@ -37813,22 +39784,22 @@ public class InlineRequestBodyRequestContent { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { - if (!InlineRequestBodyRequestContent.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'InlineRequestBodyRequestContent' and its subtypes + if (!NamedOneOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NamedOneOf' and its subtypes } final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(InlineRequestBodyRequestContent.class)); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NamedOneOf.class)); - return (TypeAdapter) new TypeAdapter() { + return (TypeAdapter) new TypeAdapter() { @Override - public void write(JsonWriter out, InlineRequestBodyRequestContent value) throws IOException { + public void write(JsonWriter out, NamedOneOf value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); elementAdapter.write(out, obj); } @Override - public InlineRequestBodyRequestContent read(JsonReader in) throws IOException { + public NamedOneOf read(JsonReader in) throws IOException { JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); validateJsonObject(jsonObj); return thisAdapter.fromJsonTree(jsonObj); @@ -37839,18 +39810,18 @@ public class InlineRequestBodyRequestContent { } /** - * Create an instance of InlineRequestBodyRequestContent given an JSON string + * Create an instance of NamedOneOf given an JSON string * * @param jsonString JSON string - * @return An instance of InlineRequestBodyRequestContent - * @throws IOException if the JSON string is invalid with respect to InlineRequestBodyRequestContent + * @return An instance of NamedOneOf + * @throws IOException if the JSON string is invalid with respect to NamedOneOf */ - public static InlineRequestBodyRequestContent fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, InlineRequestBodyRequestContent.class); + public static NamedOneOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NamedOneOf.class); } /** - * Convert an instance of InlineRequestBodyRequestContent to an JSON string + * Convert an instance of NamedOneOf to an JSON string * * @return JSON string */ @@ -37859,7 +39830,7 @@ public class InlineRequestBodyRequestContent { } } ", - "src/main/java/test/test/runtime/model/MyEnum.java": "/* + "src/main/java/test/test/runtime/model/NamedOneOfUnion.java": "/* * Edge Cases * * @@ -37875,6 +39846,8 @@ package test.test.runtime.model; import java.util.Objects; import java.util.Arrays; +import test.test.runtime.model.AnotherNamedOneOf; +import test.test.runtime.model.NamedOneOf; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; @@ -37925,54 +39898,230 @@ import com.google.gson.JsonParseException; import test.test.runtime.JSON; -/** - * Gets or Sets MyEnum - */ -@JsonAdapter(MyEnum.Adapter.class) -public enum MyEnum { +@lombok.experimental.SuperBuilder +public class NamedOneOfUnion extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(NamedOneOfUnion.class.getName()); - ONE("one"), + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NamedOneOfUnion.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NamedOneOfUnion' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterNamedOneOf = gson.getDelegateAdapter(this, TypeToken.get(NamedOneOf.class)); + final TypeAdapter adapterAnotherNamedOneOf = gson.getDelegateAdapter(this, TypeToken.get(AnotherNamedOneOf.class)); - TWO("two"), + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NamedOneOfUnion value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } - THREE("three"); + // check if the actual instance is of the type \`NamedOneOf\` + if (value.getActualInstance() instanceof NamedOneOf) { + JsonObject obj = adapterNamedOneOf.toJsonTree((NamedOneOf)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } - private String value; + // check if the actual instance is of the type \`AnotherNamedOneOf\` + if (value.getActualInstance() instanceof AnotherNamedOneOf) { + JsonObject obj = adapterAnotherNamedOneOf.toJsonTree((AnotherNamedOneOf)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + return; + } - MyEnum(String value) { - this.value = value; - } + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: NamedOneOf, AnotherNamedOneOf"); + } - public String getValue() { - return value; - } + @Override + public NamedOneOfUnion read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); - @Override - public String toString() { - return String.valueOf(value); - } + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; - public static MyEnum fromValue(String value) { - for (MyEnum b : MyEnum.values()) { - if (b.value.equals(value)) { - return b; - } + // deserialize NamedOneOf + try { + // validate the JSON object to see if any exception is thrown + NamedOneOf.validateJsonObject(jsonObject); + actualAdapter = adapterNamedOneOf; + match++; + log.log(Level.FINER, "Input data matches schema 'NamedOneOf'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for NamedOneOf failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'NamedOneOf'", e); + } + + // deserialize AnotherNamedOneOf + try { + // validate the JSON object to see if any exception is thrown + AnotherNamedOneOf.validateJsonObject(jsonObject); + actualAdapter = adapterAnotherNamedOneOf; + match++; + log.log(Level.FINER, "Input data matches schema 'AnotherNamedOneOf'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for AnotherNamedOneOf failed with \`%s\`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'AnotherNamedOneOf'", e); + } + + if (match == 1) { + NamedOneOfUnion ret = new NamedOneOfUnion(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject)); + return ret; + } + + throw new IOException(String.format("Failed deserialization for NamedOneOfUnion: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonObject.toString())); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map schemas = new HashMap(); + + public NamedOneOfUnion() { + super("oneOf", Boolean.FALSE); + } + + public NamedOneOfUnion(NamedOneOf o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public NamedOneOfUnion(AnotherNamedOneOf o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("NamedOneOf", new GenericType() { + }); + schemas.put("AnotherNamedOneOf", new GenericType() { + }); } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - public static class Adapter extends TypeAdapter { @Override - public void write(final JsonWriter jsonWriter, final MyEnum enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); + public Map getSchemas() { + return NamedOneOfUnion.schemas; } + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * NamedOneOf, AnotherNamedOneOf + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ @Override - public MyEnum read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return MyEnum.fromValue(value); + public void setActualInstance(Object instance) { + if (instance instanceof NamedOneOf) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof AnotherNamedOneOf) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be NamedOneOf, AnotherNamedOneOf"); + } + + /** + * Get the actual instance, which can be the following: + * NamedOneOf, AnotherNamedOneOf + * + * @return The actual instance (NamedOneOf, AnotherNamedOneOf) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of \`NamedOneOf\`. If the actual instance is not \`NamedOneOf\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`NamedOneOf\` + * @throws ClassCastException if the instance is not \`NamedOneOf\` + */ + public NamedOneOf getNamedOneOf() throws ClassCastException { + return (NamedOneOf)super.getActualInstance(); + } + + /** + * Get the actual instance of \`AnotherNamedOneOf\`. If the actual instance is not \`AnotherNamedOneOf\`, + * the ClassCastException will be thrown. + * + * @return The actual instance of \`AnotherNamedOneOf\` + * @throws ClassCastException if the instance is not \`AnotherNamedOneOf\` + */ + public AnotherNamedOneOf getAnotherNamedOneOf() throws ClassCastException { + return (AnotherNamedOneOf)super.getActualInstance(); + } + + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to NamedOneOfUnion + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + // validate oneOf schemas one by one + int validCount = 0; + ArrayList errorMessages = new ArrayList<>(); + // validate the json string with NamedOneOf + try { + NamedOneOf.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for NamedOneOf failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + // validate the json string with AnotherNamedOneOf + try { + AnotherNamedOneOf.validateJsonObject(jsonObj); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for AnotherNamedOneOf failed with \`%s\`.", e.getMessage())); + // continue to the next one + } + if (validCount != 1) { + throw new IOException(String.format("The JSON string is invalid for NamedOneOfUnion with oneOf schemas: NamedOneOf, AnotherNamedOneOf. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString())); } } + + /** + * Create an instance of NamedOneOfUnion given an JSON string + * + * @param jsonString JSON string + * @return An instance of NamedOneOfUnion + * @throws IOException if the JSON string is invalid with respect to NamedOneOfUnion + */ + public static NamedOneOfUnion fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NamedOneOfUnion.class); + } + + /** + * Convert an instance of NamedOneOfUnion to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } + } ", } diff --git a/packages/type-safe-api/test/scripts/generators/__snapshots__/python.test.ts.snap b/packages/type-safe-api/test/scripts/generators/__snapshots__/python.test.ts.snap index 76f476dfd..09861e8a1 100644 --- a/packages/type-safe-api/test/scripts/generators/__snapshots__/python.test.ts.snap +++ b/packages/type-safe-api/test/scripts/generators/__snapshots__/python.test.ts.snap @@ -17428,10 +17428,14 @@ test_project/__init__.py test_project/py.typed test_project/rest.py docs/DefaultApi.md +docs/AnotherNamedOneOf.md +docs/ArrayOfOneOfs.md docs/InlineEnum200Response.md docs/InlineEnum200ResponseCategoryEnum.md docs/InlineRequestBodyRequestContent.md docs/MyEnum.md +docs/NamedOneOf.md +docs/NamedOneOfUnion.md README.md test_project/interceptors/try_catch.py test_project/interceptors/response_headers.py @@ -17444,10 +17448,14 @@ test_project/response.py test_project/api/default_api.py test_project/api/__init__.py test_project/models/__init__.py +test_project/models/another_named_one_of.py +test_project/models/array_of_one_ofs.py test_project/models/inline_enum200_response.py test_project/models/inline_enum200_response_category_enum.py test_project/models/inline_request_body_request_content.py -test_project/models/my_enum.py", +test_project/models/my_enum.py +test_project/models/named_one_of.py +test_project/models/named_one_of_union.py", "README.md": "# Edge Cases @@ -17479,47 +17487,152 @@ configuration = test_project.Configuration( with test_project.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = test_project.DefaultApi(api_client) - my_string_array_request_params = [] # List[str] | (optional) - my_enum_array_request_params = [] # List[MyEnum] | (optional) - my_integer_array_request_params = [2436284417048576,6600606720458752,2769288930787328] # List[int] | (optional) - my_long_array_request_params = [3479256564760576,857015102472192,5661035377721344] # List[int] | (optional) - my_int32_array_request_params = [] # List[int] | (optional) - my_number_array_request_params = [0.1599486346822232,0.4432248624507338,0.8626475473865867] # List[float] | (optional) - my_float_array_request_params = [0.7941185790114105,0.005342561984434724,0.36126157245598733] # List[float] | (optional) - my_double_array_request_params = [0.3810686601791531] # List[float] | (optional) - my_enum_request_param = test_project.MyEnum() # MyEnum | (optional) try: - api_instance.array_request_parameters(my_string_array_request_params=my_string_array_request_params, my_enum_array_request_params=my_enum_array_request_params, my_integer_array_request_params=my_integer_array_request_params, my_long_array_request_params=my_long_array_request_params, my_int32_array_request_params=my_int32_array_request_params, my_number_array_request_params=my_number_array_request_params, my_float_array_request_params=my_float_array_request_params, my_double_array_request_params=my_double_array_request_params, my_enum_request_param=my_enum_request_param) + api_response = api_instance.array_of_one_ofs() + print("The response of DefaultApi->array_of_one_ofs:\\n") + pprint(api_response) except ApiException as e: - print("Exception when calling DefaultApi->array_request_parameters: %s\\n" % e) + print("Exception when calling DefaultApi->array_of_one_ofs: %s\\n" % e) \`\`\` ## Documentation for API Endpoints Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**array_of_one_ofs**](docs/DefaultApi.md#array_of_one_ofs) | **POST** /array-of-one-ofs | *DefaultApi* | [**array_request_parameters**](docs/DefaultApi.md#array_request_parameters) | **GET** /array-request-parameters | *DefaultApi* | [**inline_enum**](docs/DefaultApi.md#inline_enum) | **GET** /inline-enum | *DefaultApi* | [**inline_request_body**](docs/DefaultApi.md#inline_request_body) | **POST** /inline-request-body | +*DefaultApi* | [**named_one_of**](docs/DefaultApi.md#named_one_of) | **POST** /named-one-of | *DefaultApi* | [**reserved_keywords**](docs/DefaultApi.md#reserved_keywords) | **GET** /reserved-keywords | ## Documentation For Models + - [AnotherNamedOneOf](docs/AnotherNamedOneOf.md) + - [ArrayOfOneOfs](docs/ArrayOfOneOfs.md) - [InlineEnum200Response](docs/InlineEnum200Response.md) - [InlineEnum200ResponseCategoryEnum](docs/InlineEnum200ResponseCategoryEnum.md) - [InlineRequestBodyRequestContent](docs/InlineRequestBodyRequestContent.md) - [MyEnum](docs/MyEnum.md) + - [NamedOneOf](docs/NamedOneOf.md) + - [NamedOneOfUnion](docs/NamedOneOfUnion.md) +", + "docs/AnotherNamedOneOf.md": "# AnotherNamedOneOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **str** | | [optional] + +## Example + +\`\`\`python +from test_project.models.another_named_one_of import AnotherNamedOneOf + +# TODO update the JSON string below +json = "{}" +# create an instance of AnotherNamedOneOf from a JSON string +another_named_one_of_instance = AnotherNamedOneOf.from_json(json) +# print the JSON string representation of the object +print(AnotherNamedOneOf.to_json()) + +# convert the object into a dict +another_named_one_of_dict = another_named_one_of_instance.to_dict() +# create an instance of AnotherNamedOneOf from a dict +another_named_one_of_form_dict = another_named_one_of.from_dict(another_named_one_of_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +", + "docs/ArrayOfOneOfs.md": "# ArrayOfOneOfs + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**one_ofs** | **List[NamedOneOfUnion]** | | [optional] + +## Example + +\`\`\`python +from test_project.models.array_of_one_ofs import ArrayOfOneOfs + +# TODO update the JSON string below +json = "{}" +# create an instance of ArrayOfOneOfs from a JSON string +array_of_one_ofs_instance = ArrayOfOneOfs.from_json(json) +# print the JSON string representation of the object +print(ArrayOfOneOfs.to_json()) + +# convert the object into a dict +array_of_one_ofs_dict = array_of_one_ofs_instance.to_dict() +# create an instance of ArrayOfOneOfs from a dict +array_of_one_ofs_form_dict = array_of_one_ofs.from_dict(array_of_one_ofs_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + ", "docs/DefaultApi.md": "# test_project.DefaultApi Method | HTTP request | Description ------------- | ------------- | ------------- +[**array_of_one_ofs**](DefaultApi.md#array_of_one_ofs) | **POST** /array-of-one-ofs | [**array_request_parameters**](DefaultApi.md#array_request_parameters) | **GET** /array-request-parameters | [**inline_enum**](DefaultApi.md#inline_enum) | **GET** /inline-enum | [**inline_request_body**](DefaultApi.md#inline_request_body) | **POST** /inline-request-body | +[**named_one_of**](DefaultApi.md#named_one_of) | **POST** /named-one-of | [**reserved_keywords**](DefaultApi.md#reserved_keywords) | **GET** /reserved-keywords | +# **array_of_one_ofs** +> ArrayOfOneOfs array_of_one_ofs() + + +### Example + +\`\`\`python +import time +import test_project +from test_project.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = test_project.Configuration( + host = "http://localhost" +) + +# Enter a context with an instance of the API client +with test_project.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = test_project.DefaultApi(api_client) + + try: + api_response = api_instance.array_of_one_ofs() + print("The response of DefaultApi->array_of_one_ofs:\\n") + pprint(api_response) + except ApiException as e: + print("Exception when calling DefaultApi->array_of_one_ofs: %s\\n" % e) +\`\`\` + +### Parameters +This endpoint does not need any parameters. + +### Return type + +[**ArrayOfOneOfs**](ArrayOfOneOfs.md) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **array_request_parameters** > array_request_parameters(my_string_array_request_params=my_string_array_request_params, my_enum_array_request_params=my_enum_array_request_params, my_integer_array_request_params=my_integer_array_request_params, my_long_array_request_params=my_long_array_request_params, my_int32_array_request_params=my_int32_array_request_params, my_number_array_request_params=my_number_array_request_params, my_float_array_request_params=my_float_array_request_params, my_double_array_request_params=my_double_array_request_params, my_enum_request_param=my_enum_request_param) @@ -17688,6 +17801,56 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **named_one_of** +> NamedOneOfUnion named_one_of() + + +### Example + +\`\`\`python +import time +import test_project +from test_project.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = test_project.Configuration( + host = "http://localhost" +) + +# Enter a context with an instance of the API client +with test_project.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = test_project.DefaultApi(api_client) + + try: + api_response = api_instance.named_one_of() + print("The response of DefaultApi->named_one_of:\\n") + pprint(api_response) + except ApiException as e: + print("Exception when calling DefaultApi->named_one_of: %s\\n" % e) +\`\`\` + +### Parameters +This endpoint does not need any parameters. + +### Return type + +[**NamedOneOfUnion**](NamedOneOfUnion.md) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **reserved_keywords** > reserved_keywords(var_with=var_with, var_if=var_if, var_class=var_class) @@ -17815,6 +17978,64 @@ Name | Type | Description | Notes [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) +", + "docs/NamedOneOf.md": "# NamedOneOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**foo** | **str** | | [optional] + +## Example + +\`\`\`python +from test_project.models.named_one_of import NamedOneOf + +# TODO update the JSON string below +json = "{}" +# create an instance of NamedOneOf from a JSON string +named_one_of_instance = NamedOneOf.from_json(json) +# print the JSON string representation of the object +print(NamedOneOf.to_json()) + +# convert the object into a dict +named_one_of_dict = named_one_of_instance.to_dict() +# create an instance of NamedOneOf from a dict +named_one_of_form_dict = named_one_of.from_dict(named_one_of_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +", + "docs/NamedOneOfUnion.md": "# NamedOneOfUnion + +## Composed Of + +This model can be set to one of the following types: + +Type | Description | Notes +------------- | ------------- | ------------- +[**NamedOneOf**](NamedOneOf.md) | +[**AnotherNamedOneOf**](AnotherNamedOneOf.md) | + +## Example + +\`\`\`python +from test_project.models.named_one_of_union import NamedOneOfUnion + +# TODO update the JSON string below +json = "{}" +# create an instance of NamedOneOfUnion from a JSON string +named_one_of_union_instance = NamedOneOfUnion.from_json(json) +# print the JSON string representation of the object +print(NamedOneOfUnion.to_json()) + +# convert the object into a dict +named_one_of_union_dict = named_one_of_union_instance.to_dict() +# create an instance of NamedOneOfUnion from a dict +named_one_of_union_form_dict = named_one_of_union.from_dict(named_one_of_union_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + ", "poetry.toml": "# ~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen". @@ -17884,10 +18105,14 @@ from test_project.exceptions import ApiAttributeError from test_project.exceptions import ApiException # import models into sdk package +from test_project.models.another_named_one_of import AnotherNamedOneOf +from test_project.models.array_of_one_ofs import ArrayOfOneOfs from test_project.models.inline_enum200_response import InlineEnum200Response from test_project.models.inline_enum200_response_category_enum import InlineEnum200ResponseCategoryEnum from test_project.models.inline_request_body_request_content import InlineRequestBodyRequestContent from test_project.models.my_enum import MyEnum +from test_project.models.named_one_of import NamedOneOf +from test_project.models.named_one_of_union import NamedOneOfUnion ", "test_project/api/__init__.py": "# flake8: noqa @@ -17918,9 +18143,11 @@ try: except ImportError: from typing_extensions import Annotated +from test_project.models.array_of_one_ofs import ArrayOfOneOfs from test_project.models.inline_enum200_response import InlineEnum200Response from test_project.models.inline_request_body_request_content import InlineRequestBodyRequestContent from test_project.models.my_enum import MyEnum +from test_project.models.named_one_of_union import NamedOneOfUnion from test_project.api_client import ApiClient from test_project.api_response import ApiResponse @@ -17939,17 +18166,8 @@ class DefaultApi: self.api_client = api_client @validate_call - def array_request_parameters( + def array_of_one_ofs( self, - my_string_array_request_params: Optional[List[StrictStr]] = None, - my_enum_array_request_params: Optional[List[MyEnum]] = None, - my_integer_array_request_params: Optional[List[StrictInt]] = None, - my_long_array_request_params: Optional[List[StrictInt]] = None, - my_int32_array_request_params: Optional[List[StrictInt]] = None, - my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_enum_request_param: Optional[MyEnum] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -17962,26 +18180,8 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> None: - """array_request_parameters - :param my_string_array_request_params: (optional) - :type my_string_array_request_params: List[str], optional - :param my_enum_array_request_params: (optional) - :type my_enum_array_request_params: List[MyEnum], optional - :param my_integer_array_request_params: (optional) - :type my_integer_array_request_params: List[int], optional - :param my_long_array_request_params: (optional) - :type my_long_array_request_params: List[int], optional - :param my_int32_array_request_params: (optional) - :type my_int32_array_request_params: List[int], optional - :param my_number_array_request_params: (optional) - :type my_number_array_request_params: List[float], optional - :param my_float_array_request_params: (optional) - :type my_float_array_request_params: List[float], optional - :param my_double_array_request_params: (optional) - :type my_double_array_request_params: List[float], optional - :param my_enum_request_param: (optional) - :type my_enum_request_param: MyEnum, optional + ) -> ArrayOfOneOfs: + """array_of_one_ofs :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -18004,16 +18204,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._array_request_parameters_serialize( - my_string_array_request_params=my_string_array_request_params, - my_enum_array_request_params=my_enum_array_request_params, - my_integer_array_request_params=my_integer_array_request_params, - my_long_array_request_params=my_long_array_request_params, - my_int32_array_request_params=my_int32_array_request_params, - my_number_array_request_params=my_number_array_request_params, - my_float_array_request_params=my_float_array_request_params, - my_double_array_request_params=my_double_array_request_params, - my_enum_request_param=my_enum_request_param, + _param = self._array_of_one_ofs_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18021,6 +18212,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "ArrayOfOneOfs" } response_data = self.api_client.call_api( @@ -18035,17 +18227,8 @@ class DefaultApi: @validate_call - def array_request_parameters_with_http_info( + def array_of_one_ofs_with_http_info( self, - my_string_array_request_params: Optional[List[StrictStr]] = None, - my_enum_array_request_params: Optional[List[MyEnum]] = None, - my_integer_array_request_params: Optional[List[StrictInt]] = None, - my_long_array_request_params: Optional[List[StrictInt]] = None, - my_int32_array_request_params: Optional[List[StrictInt]] = None, - my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_enum_request_param: Optional[MyEnum] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18058,26 +18241,8 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[None]: - """array_request_parameters - :param my_string_array_request_params: (optional) - :type my_string_array_request_params: List[str], optional - :param my_enum_array_request_params: (optional) - :type my_enum_array_request_params: List[MyEnum], optional - :param my_integer_array_request_params: (optional) - :type my_integer_array_request_params: List[int], optional - :param my_long_array_request_params: (optional) - :type my_long_array_request_params: List[int], optional - :param my_int32_array_request_params: (optional) - :type my_int32_array_request_params: List[int], optional - :param my_number_array_request_params: (optional) - :type my_number_array_request_params: List[float], optional - :param my_float_array_request_params: (optional) - :type my_float_array_request_params: List[float], optional - :param my_double_array_request_params: (optional) - :type my_double_array_request_params: List[float], optional - :param my_enum_request_param: (optional) - :type my_enum_request_param: MyEnum, optional + ) -> ApiResponse[ArrayOfOneOfs]: + """array_of_one_ofs :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -18100,16 +18265,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._array_request_parameters_serialize( - my_string_array_request_params=my_string_array_request_params, - my_enum_array_request_params=my_enum_array_request_params, - my_integer_array_request_params=my_integer_array_request_params, - my_long_array_request_params=my_long_array_request_params, - my_int32_array_request_params=my_int32_array_request_params, - my_number_array_request_params=my_number_array_request_params, - my_float_array_request_params=my_float_array_request_params, - my_double_array_request_params=my_double_array_request_params, - my_enum_request_param=my_enum_request_param, + _param = self._array_of_one_ofs_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18117,6 +18273,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "ArrayOfOneOfs" } response_data = self.api_client.call_api( @@ -18131,17 +18288,8 @@ class DefaultApi: @validate_call - def array_request_parameters_without_preload_content( + def array_of_one_ofs_without_preload_content( self, - my_string_array_request_params: Optional[List[StrictStr]] = None, - my_enum_array_request_params: Optional[List[MyEnum]] = None, - my_integer_array_request_params: Optional[List[StrictInt]] = None, - my_long_array_request_params: Optional[List[StrictInt]] = None, - my_int32_array_request_params: Optional[List[StrictInt]] = None, - my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, - my_enum_request_param: Optional[MyEnum] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18155,25 +18303,7 @@ class DefaultApi: _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """array_request_parameters - :param my_string_array_request_params: (optional) - :type my_string_array_request_params: List[str], optional - :param my_enum_array_request_params: (optional) - :type my_enum_array_request_params: List[MyEnum], optional - :param my_integer_array_request_params: (optional) - :type my_integer_array_request_params: List[int], optional - :param my_long_array_request_params: (optional) - :type my_long_array_request_params: List[int], optional - :param my_int32_array_request_params: (optional) - :type my_int32_array_request_params: List[int], optional - :param my_number_array_request_params: (optional) - :type my_number_array_request_params: List[float], optional - :param my_float_array_request_params: (optional) - :type my_float_array_request_params: List[float], optional - :param my_double_array_request_params: (optional) - :type my_double_array_request_params: List[float], optional - :param my_enum_request_param: (optional) - :type my_enum_request_param: MyEnum, optional + """array_of_one_ofs :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -18196,16 +18326,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._array_request_parameters_serialize( - my_string_array_request_params=my_string_array_request_params, - my_enum_array_request_params=my_enum_array_request_params, - my_integer_array_request_params=my_integer_array_request_params, - my_long_array_request_params=my_long_array_request_params, - my_int32_array_request_params=my_int32_array_request_params, - my_number_array_request_params=my_number_array_request_params, - my_float_array_request_params=my_float_array_request_params, - my_double_array_request_params=my_double_array_request_params, - my_enum_request_param=my_enum_request_param, + _param = self._array_of_one_ofs_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18213,6 +18334,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "ArrayOfOneOfs" } response_data = self.api_client.call_api( @@ -18222,17 +18344,8 @@ class DefaultApi: return response_data.response - def _array_request_parameters_serialize( + def _array_of_one_ofs_serialize( self, - my_string_array_request_params, - my_enum_array_request_params, - my_integer_array_request_params, - my_long_array_request_params, - my_int32_array_request_params, - my_number_array_request_params, - my_float_array_request_params, - my_double_array_request_params, - my_enum_request_param, _request_auth, _content_type, _headers, @@ -18242,14 +18355,6 @@ class DefaultApi: _host = None _collection_formats: Dict[str, str] = { - 'my-string-array-request-params': 'multi', - 'my-enum-array-request-params': 'multi', - 'my-integer-array-request-params': 'multi', - 'my-long-array-request-params': 'multi', - 'my-int32-array-request-params': 'multi', - 'my-number-array-request-params': 'multi', - 'my-float-array-request-params': 'multi', - 'my-double-array-request-params': 'multi', } _path_params: Dict[str, str] = {} @@ -18261,29 +18366,17 @@ class DefaultApi: # process the path parameters # process the query parameters - if my_string_array_request_params is not None: - _query_params.append(('my-string-array-request-params', my_string_array_request_params)) - if my_enum_array_request_params is not None: - _query_params.append(('my-enum-array-request-params', my_enum_array_request_params)) - if my_integer_array_request_params is not None: - _query_params.append(('my-integer-array-request-params', my_integer_array_request_params)) - if my_long_array_request_params is not None: - _query_params.append(('my-long-array-request-params', my_long_array_request_params)) - if my_int32_array_request_params is not None: - _query_params.append(('my-int32-array-request-params', my_int32_array_request_params)) - if my_number_array_request_params is not None: - _query_params.append(('my-number-array-request-params', my_number_array_request_params)) - if my_float_array_request_params is not None: - _query_params.append(('my-float-array-request-params', my_float_array_request_params)) - if my_double_array_request_params is not None: - _query_params.append(('my-double-array-request-params', my_double_array_request_params)) - if my_enum_request_param is not None: - _query_params.append(('my-enum-request-param', my_enum_request_param)) # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header \`Accept\` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # authentication setting @@ -18291,8 +18384,8 @@ class DefaultApi: ] return self.api_client.param_serialize( - method='GET', - resource_path='/array-request-parameters', + method='POST', + resource_path='/array-of-one-ofs', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -18308,8 +18401,17 @@ class DefaultApi: @validate_call - def inline_enum( + def array_request_parameters( self, + my_string_array_request_params: Optional[List[StrictStr]] = None, + my_enum_array_request_params: Optional[List[MyEnum]] = None, + my_integer_array_request_params: Optional[List[StrictInt]] = None, + my_long_array_request_params: Optional[List[StrictInt]] = None, + my_int32_array_request_params: Optional[List[StrictInt]] = None, + my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_enum_request_param: Optional[MyEnum] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18322,8 +18424,26 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> InlineEnum200Response: - """inline_enum + ) -> None: + """array_request_parameters + :param my_string_array_request_params: (optional) + :type my_string_array_request_params: List[str], optional + :param my_enum_array_request_params: (optional) + :type my_enum_array_request_params: List[MyEnum], optional + :param my_integer_array_request_params: (optional) + :type my_integer_array_request_params: List[int], optional + :param my_long_array_request_params: (optional) + :type my_long_array_request_params: List[int], optional + :param my_int32_array_request_params: (optional) + :type my_int32_array_request_params: List[int], optional + :param my_number_array_request_params: (optional) + :type my_number_array_request_params: List[float], optional + :param my_float_array_request_params: (optional) + :type my_float_array_request_params: List[float], optional + :param my_double_array_request_params: (optional) + :type my_double_array_request_params: List[float], optional + :param my_enum_request_param: (optional) + :type my_enum_request_param: MyEnum, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -18346,7 +18466,16 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._inline_enum_serialize( + _param = self._array_request_parameters_serialize( + my_string_array_request_params=my_string_array_request_params, + my_enum_array_request_params=my_enum_array_request_params, + my_integer_array_request_params=my_integer_array_request_params, + my_long_array_request_params=my_long_array_request_params, + my_int32_array_request_params=my_int32_array_request_params, + my_number_array_request_params=my_number_array_request_params, + my_float_array_request_params=my_float_array_request_params, + my_double_array_request_params=my_double_array_request_params, + my_enum_request_param=my_enum_request_param, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18354,7 +18483,6 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { - '200': "InlineEnum200Response" } response_data = self.api_client.call_api( @@ -18369,8 +18497,17 @@ class DefaultApi: @validate_call - def inline_enum_with_http_info( + def array_request_parameters_with_http_info( self, + my_string_array_request_params: Optional[List[StrictStr]] = None, + my_enum_array_request_params: Optional[List[MyEnum]] = None, + my_integer_array_request_params: Optional[List[StrictInt]] = None, + my_long_array_request_params: Optional[List[StrictInt]] = None, + my_int32_array_request_params: Optional[List[StrictInt]] = None, + my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_enum_request_param: Optional[MyEnum] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18383,8 +18520,26 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[InlineEnum200Response]: - """inline_enum + ) -> ApiResponse[None]: + """array_request_parameters + :param my_string_array_request_params: (optional) + :type my_string_array_request_params: List[str], optional + :param my_enum_array_request_params: (optional) + :type my_enum_array_request_params: List[MyEnum], optional + :param my_integer_array_request_params: (optional) + :type my_integer_array_request_params: List[int], optional + :param my_long_array_request_params: (optional) + :type my_long_array_request_params: List[int], optional + :param my_int32_array_request_params: (optional) + :type my_int32_array_request_params: List[int], optional + :param my_number_array_request_params: (optional) + :type my_number_array_request_params: List[float], optional + :param my_float_array_request_params: (optional) + :type my_float_array_request_params: List[float], optional + :param my_double_array_request_params: (optional) + :type my_double_array_request_params: List[float], optional + :param my_enum_request_param: (optional) + :type my_enum_request_param: MyEnum, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -18407,7 +18562,16 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._inline_enum_serialize( + _param = self._array_request_parameters_serialize( + my_string_array_request_params=my_string_array_request_params, + my_enum_array_request_params=my_enum_array_request_params, + my_integer_array_request_params=my_integer_array_request_params, + my_long_array_request_params=my_long_array_request_params, + my_int32_array_request_params=my_int32_array_request_params, + my_number_array_request_params=my_number_array_request_params, + my_float_array_request_params=my_float_array_request_params, + my_double_array_request_params=my_double_array_request_params, + my_enum_request_param=my_enum_request_param, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18415,7 +18579,6 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { - '200': "InlineEnum200Response" } response_data = self.api_client.call_api( @@ -18430,8 +18593,17 @@ class DefaultApi: @validate_call - def inline_enum_without_preload_content( + def array_request_parameters_without_preload_content( self, + my_string_array_request_params: Optional[List[StrictStr]] = None, + my_enum_array_request_params: Optional[List[MyEnum]] = None, + my_integer_array_request_params: Optional[List[StrictInt]] = None, + my_long_array_request_params: Optional[List[StrictInt]] = None, + my_int32_array_request_params: Optional[List[StrictInt]] = None, + my_number_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_float_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_double_array_request_params: Optional[List[Union[StrictFloat, StrictInt]]] = None, + my_enum_request_param: Optional[MyEnum] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18445,7 +18617,25 @@ class DefaultApi: _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """inline_enum + """array_request_parameters + :param my_string_array_request_params: (optional) + :type my_string_array_request_params: List[str], optional + :param my_enum_array_request_params: (optional) + :type my_enum_array_request_params: List[MyEnum], optional + :param my_integer_array_request_params: (optional) + :type my_integer_array_request_params: List[int], optional + :param my_long_array_request_params: (optional) + :type my_long_array_request_params: List[int], optional + :param my_int32_array_request_params: (optional) + :type my_int32_array_request_params: List[int], optional + :param my_number_array_request_params: (optional) + :type my_number_array_request_params: List[float], optional + :param my_float_array_request_params: (optional) + :type my_float_array_request_params: List[float], optional + :param my_double_array_request_params: (optional) + :type my_double_array_request_params: List[float], optional + :param my_enum_request_param: (optional) + :type my_enum_request_param: MyEnum, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -18468,7 +18658,16 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._inline_enum_serialize( + _param = self._array_request_parameters_serialize( + my_string_array_request_params=my_string_array_request_params, + my_enum_array_request_params=my_enum_array_request_params, + my_integer_array_request_params=my_integer_array_request_params, + my_long_array_request_params=my_long_array_request_params, + my_int32_array_request_params=my_int32_array_request_params, + my_number_array_request_params=my_number_array_request_params, + my_float_array_request_params=my_float_array_request_params, + my_double_array_request_params=my_double_array_request_params, + my_enum_request_param=my_enum_request_param, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18476,7 +18675,6 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { - '200': "InlineEnum200Response" } response_data = self.api_client.call_api( @@ -18486,8 +18684,17 @@ class DefaultApi: return response_data.response - def _inline_enum_serialize( + def _array_request_parameters_serialize( self, + my_string_array_request_params, + my_enum_array_request_params, + my_integer_array_request_params, + my_long_array_request_params, + my_int32_array_request_params, + my_number_array_request_params, + my_float_array_request_params, + my_double_array_request_params, + my_enum_request_param, _request_auth, _content_type, _headers, @@ -18497,6 +18704,14 @@ class DefaultApi: _host = None _collection_formats: Dict[str, str] = { + 'my-string-array-request-params': 'multi', + 'my-enum-array-request-params': 'multi', + 'my-integer-array-request-params': 'multi', + 'my-long-array-request-params': 'multi', + 'my-int32-array-request-params': 'multi', + 'my-number-array-request-params': 'multi', + 'my-float-array-request-params': 'multi', + 'my-double-array-request-params': 'multi', } _path_params: Dict[str, str] = {} @@ -18508,17 +18723,29 @@ class DefaultApi: # process the path parameters # process the query parameters + if my_string_array_request_params is not None: + _query_params.append(('my-string-array-request-params', my_string_array_request_params)) + if my_enum_array_request_params is not None: + _query_params.append(('my-enum-array-request-params', my_enum_array_request_params)) + if my_integer_array_request_params is not None: + _query_params.append(('my-integer-array-request-params', my_integer_array_request_params)) + if my_long_array_request_params is not None: + _query_params.append(('my-long-array-request-params', my_long_array_request_params)) + if my_int32_array_request_params is not None: + _query_params.append(('my-int32-array-request-params', my_int32_array_request_params)) + if my_number_array_request_params is not None: + _query_params.append(('my-number-array-request-params', my_number_array_request_params)) + if my_float_array_request_params is not None: + _query_params.append(('my-float-array-request-params', my_float_array_request_params)) + if my_double_array_request_params is not None: + _query_params.append(('my-double-array-request-params', my_double_array_request_params)) + if my_enum_request_param is not None: + _query_params.append(('my-enum-request-param', my_enum_request_param)) # process the header parameters # process the form parameters # process the body parameter - # set the HTTP header \`Accept\` - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) # authentication setting @@ -18527,7 +18754,7 @@ class DefaultApi: return self.api_client.param_serialize( method='GET', - resource_path='/inline-enum', + resource_path='/array-request-parameters', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -18543,9 +18770,8 @@ class DefaultApi: @validate_call - def inline_request_body( + def inline_enum( self, - inline_request_body_request_content: Optional[InlineRequestBodyRequestContent] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18558,10 +18784,8 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> None: - """inline_request_body - :param inline_request_body_request_content: (optional) - :type inline_request_body_request_content: InlineRequestBodyRequestContent, optional + ) -> InlineEnum200Response: + """inline_enum :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -18584,8 +18808,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._inline_request_body_serialize( - inline_request_body_request_content=inline_request_body_request_content, + _param = self._inline_enum_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18593,6 +18816,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "InlineEnum200Response" } response_data = self.api_client.call_api( @@ -18607,9 +18831,8 @@ class DefaultApi: @validate_call - def inline_request_body_with_http_info( + def inline_enum_with_http_info( self, - inline_request_body_request_content: Optional[InlineRequestBodyRequestContent] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18622,10 +18845,8 @@ class DefaultApi: _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[None]: - """inline_request_body - :param inline_request_body_request_content: (optional) - :type inline_request_body_request_content: InlineRequestBodyRequestContent, optional + ) -> ApiResponse[InlineEnum200Response]: + """inline_enum :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -18648,8 +18869,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._inline_request_body_serialize( - inline_request_body_request_content=inline_request_body_request_content, + _param = self._inline_enum_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18657,6 +18877,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "InlineEnum200Response" } response_data = self.api_client.call_api( @@ -18671,9 +18892,8 @@ class DefaultApi: @validate_call - def inline_request_body_without_preload_content( + def inline_enum_without_preload_content( self, - inline_request_body_request_content: Optional[InlineRequestBodyRequestContent] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18687,9 +18907,7 @@ class DefaultApi: _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """inline_request_body - :param inline_request_body_request_content: (optional) - :type inline_request_body_request_content: InlineRequestBodyRequestContent, optional + """inline_enum :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -18712,8 +18930,7 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._inline_request_body_serialize( - inline_request_body_request_content=inline_request_body_request_content, + _param = self._inline_enum_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18721,6 +18938,7 @@ class DefaultApi: ) _response_types_map: Dict[str, Optional[str]] = { + '200': "InlineEnum200Response" } response_data = self.api_client.call_api( @@ -18730,9 +18948,8 @@ class DefaultApi: return response_data.response - def _inline_request_body_serialize( + def _inline_enum_serialize( self, - inline_request_body_request_content, _request_auth, _content_type, _headers, @@ -18756,32 +18973,23 @@ class DefaultApi: # process the header parameters # process the form parameters # process the body parameter - if inline_request_body_request_content is not None: - _body_params = inline_request_body_request_content + # set the HTTP header \`Accept\` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) - # set the HTTP header \`Content-Type\` - if _content_type: - _header_params['Content-Type'] = _content_type - else: - _default_content_type = ( - self.api_client.select_header_content_type( - [ - 'application/json' - ] - ) - ) - if _default_content_type is not None: - _header_params['Content-Type'] = _default_content_type # authentication setting _auth_settings: List[str] = [ ] return self.api_client.param_serialize( - method='POST', - resource_path='/inline-request-body', + method='GET', + resource_path='/inline-enum', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -18797,11 +19005,9 @@ class DefaultApi: @validate_call - def reserved_keywords( + def inline_request_body( self, - var_with: Optional[StrictStr] = None, - var_if: Optional[StrictStr] = None, - var_class: Optional[StrictStr] = None, + inline_request_body_request_content: Optional[InlineRequestBodyRequestContent] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18815,13 +19021,9 @@ class DefaultApi: _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """reserved_keywords - :param var_with: (optional) - :type var_with: str, optional - :param var_if: (optional) - :type var_if: str, optional - :param var_class: (optional) - :type var_class: str, optional + """inline_request_body + :param inline_request_body_request_content: (optional) + :type inline_request_body_request_content: InlineRequestBodyRequestContent, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -18844,10 +19046,8 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._reserved_keywords_serialize( - var_with=var_with, - var_if=var_if, - var_class=var_class, + _param = self._inline_request_body_serialize( + inline_request_body_request_content=inline_request_body_request_content, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18869,11 +19069,9 @@ class DefaultApi: @validate_call - def reserved_keywords_with_http_info( + def inline_request_body_with_http_info( self, - var_with: Optional[StrictStr] = None, - var_if: Optional[StrictStr] = None, - var_class: Optional[StrictStr] = None, + inline_request_body_request_content: Optional[InlineRequestBodyRequestContent] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18887,13 +19085,9 @@ class DefaultApi: _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[None]: - """reserved_keywords - :param var_with: (optional) - :type var_with: str, optional - :param var_if: (optional) - :type var_if: str, optional - :param var_class: (optional) - :type var_class: str, optional + """inline_request_body + :param inline_request_body_request_content: (optional) + :type inline_request_body_request_content: InlineRequestBodyRequestContent, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -18916,10 +19110,8 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._reserved_keywords_serialize( - var_with=var_with, - var_if=var_if, - var_class=var_class, + _param = self._inline_request_body_serialize( + inline_request_body_request_content=inline_request_body_request_content, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -18941,11 +19133,9 @@ class DefaultApi: @validate_call - def reserved_keywords_without_preload_content( + def inline_request_body_without_preload_content( self, - var_with: Optional[StrictStr] = None, - var_if: Optional[StrictStr] = None, - var_class: Optional[StrictStr] = None, + inline_request_body_request_content: Optional[InlineRequestBodyRequestContent] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -18959,13 +19149,9 @@ class DefaultApi: _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """reserved_keywords - :param var_with: (optional) - :type var_with: str, optional - :param var_if: (optional) - :type var_if: str, optional - :param var_class: (optional) - :type var_class: str, optional + """inline_request_body + :param inline_request_body_request_content: (optional) + :type inline_request_body_request_content: InlineRequestBodyRequestContent, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -18988,10 +19174,8 @@ class DefaultApi: :return: Returns the result object. """ # noqa: E501 - _param = self._reserved_keywords_serialize( - var_with=var_with, - var_if=var_if, - var_class=var_class, + _param = self._inline_request_body_serialize( + inline_request_body_request_content=inline_request_body_request_content, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -19008,11 +19192,9 @@ class DefaultApi: return response_data.response - def _reserved_keywords_serialize( + def _inline_request_body_serialize( self, - var_with, - var_if, - var_class, + inline_request_body_request_content, _request_auth, _content_type, _headers, @@ -19033,26 +19215,35 @@ class DefaultApi: # process the path parameters # process the query parameters - if var_with is not None: - _query_params.append(('with', var_with)) - if var_if is not None: - _query_params.append(('if', var_if)) - if var_class is not None: - _query_params.append(('class', var_class)) # process the header parameters # process the form parameters # process the body parameter + if inline_request_body_request_content is not None: + _body_params = inline_request_body_request_content + # set the HTTP header \`Content-Type\` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting _auth_settings: List[str] = [ ] return self.api_client.param_serialize( - method='GET', - resource_path='/reserved-keywords', + method='POST', + resource_path='/inline-request-body', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -19066,56 +19257,574 @@ class DefaultApi: ) -", - "test_project/api/operation_config.py": "from __future__ import annotations -import urllib.parse -import json -from typing import Callable, Any, Dict, List, NamedTuple, TypeVar, Generic, Union, TypedDict, Protocol, Optional, Literal, Annotated -from functools import wraps -from dataclasses import dataclass, fields -from datetime import datetime -import dateutil.parser -from pydantic import BaseModel, Field, StrictStr, conlist, StrictBool, StrictInt, StrictFloat - -from test_project.models import * -T = TypeVar('T') + @validate_call + def named_one_of( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> NamedOneOfUnion: + """named_one_of + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 -# Generic type for object keyed by operation names -@dataclass -class OperationConfig(Generic[T]): - array_request_parameters: T - inline_enum: T - inline_request_body: T - reserved_keywords: T - ... + _param = self._named_one_of_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) -# Look up path and http method for a given operation name -OperationLookup = { - "array_request_parameters": { - "path": "/array-request-parameters", - "method": "GET", - "contentTypes": ["application/json"] - }, - "inline_enum": { - "path": "/inline-enum", - "method": "GET", - "contentTypes": ["application/json"] - }, - "inline_request_body": { - "path": "/inline-request-body", - "method": "POST", - "contentTypes": ["application/json"] - }, - "reserved_keywords": { - "path": "/reserved-keywords", - "method": "GET", - "contentTypes": ["application/json"] - }, -} + _response_types_map: Dict[str, Optional[str]] = { + '200': "NamedOneOfUnion" + } -class Operations: - @staticmethod + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def named_one_of_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[NamedOneOfUnion]: + """named_one_of + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._named_one_of_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "NamedOneOfUnion" + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def named_one_of_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """named_one_of + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._named_one_of_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "NamedOneOfUnion" + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _named_one_of_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header \`Accept\` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/named-one-of', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + @validate_call + def reserved_keywords( + self, + var_with: Optional[StrictStr] = None, + var_if: Optional[StrictStr] = None, + var_class: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """reserved_keywords + :param var_with: (optional) + :type var_with: str, optional + :param var_if: (optional) + :type var_if: str, optional + :param var_class: (optional) + :type var_class: str, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._reserved_keywords_serialize( + var_with=var_with, + var_if=var_if, + var_class=var_class, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def reserved_keywords_with_http_info( + self, + var_with: Optional[StrictStr] = None, + var_if: Optional[StrictStr] = None, + var_class: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """reserved_keywords + :param var_with: (optional) + :type var_with: str, optional + :param var_if: (optional) + :type var_if: str, optional + :param var_class: (optional) + :type var_class: str, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._reserved_keywords_serialize( + var_with=var_with, + var_if=var_if, + var_class=var_class, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def reserved_keywords_without_preload_content( + self, + var_with: Optional[StrictStr] = None, + var_if: Optional[StrictStr] = None, + var_class: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """reserved_keywords + :param var_with: (optional) + :type var_with: str, optional + :param var_if: (optional) + :type var_if: str, optional + :param var_class: (optional) + :type var_class: str, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._reserved_keywords_serialize( + var_with=var_with, + var_if=var_if, + var_class=var_class, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _reserved_keywords_serialize( + self, + var_with, + var_if, + var_class, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if var_with is not None: + _query_params.append(('with', var_with)) + if var_if is not None: + _query_params.append(('if', var_if)) + if var_class is not None: + _query_params.append(('class', var_class)) + # process the header parameters + # process the form parameters + # process the body parameter + + + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/reserved-keywords', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + +", + "test_project/api/operation_config.py": "from __future__ import annotations +import urllib.parse +import json +from typing import Callable, Any, Dict, List, NamedTuple, TypeVar, Generic, Union, TypedDict, Protocol, Optional, Literal, Annotated +from functools import wraps +from dataclasses import dataclass, fields +from datetime import datetime +import dateutil.parser +from pydantic import BaseModel, Field, StrictStr, conlist, StrictBool, StrictInt, StrictFloat + +from test_project.models import * + +T = TypeVar('T') + +# Generic type for object keyed by operation names +@dataclass +class OperationConfig(Generic[T]): + array_of_one_ofs: T + array_request_parameters: T + inline_enum: T + inline_request_body: T + named_one_of: T + reserved_keywords: T + ... + +# Look up path and http method for a given operation name +OperationLookup = { + "array_of_one_ofs": { + "path": "/array-of-one-ofs", + "method": "POST", + "contentTypes": ["application/json"] + }, + "array_request_parameters": { + "path": "/array-request-parameters", + "method": "GET", + "contentTypes": ["application/json"] + }, + "inline_enum": { + "path": "/inline-enum", + "method": "GET", + "contentTypes": ["application/json"] + }, + "inline_request_body": { + "path": "/inline-request-body", + "method": "POST", + "contentTypes": ["application/json"] + }, + "named_one_of": { + "path": "/named-one-of", + "method": "POST", + "contentTypes": ["application/json"] + }, + "reserved_keywords": { + "path": "/reserved-keywords", + "method": "GET", + "contentTypes": ["application/json"] + }, +} + +class Operations: + @staticmethod def all(value: T) -> OperationConfig[T]: """ Returns an OperationConfig with the same value for every operation @@ -19277,6 +19986,121 @@ def _build_handler_chain(_interceptors, handler) -> HandlerChain: return RemainingHandlerChain() +class ArrayOfOneOfsRequestParameters(BaseModel): + """ + Query, path and header parameters for the ArrayOfOneOfs operation + """ + + class Config: + """Pydantic configuration""" + populate_by_name = True + validate_assignment = True + + def to_json(self) -> str: + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> ArrayOfOneOfsRequestParameters: + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + return self.model_dump(exclude={}, exclude_none=True) + + @classmethod + def from_dict(cls, obj: dict) -> ArrayOfOneOfsRequestParameters: + if obj is None: + return None + return ArrayOfOneOfsRequestParameters.model_validate(obj) + + +# Request body type (default to Any when no body parameters exist, or leave unchanged as str if it's a primitive type) +ArrayOfOneOfsRequestBody = Any + +ArrayOfOneOfs200OperationResponse = ApiResponse[Literal[200], ArrayOfOneOfs] + +ArrayOfOneOfsOperationResponses = Union[ArrayOfOneOfs200OperationResponse, ] + +# Request type for array_of_one_ofs +ArrayOfOneOfsRequest = ApiRequest[ArrayOfOneOfsRequestParameters, ArrayOfOneOfsRequestBody] +ArrayOfOneOfsChainedRequest = ChainedApiRequest[ArrayOfOneOfsRequestParameters, ArrayOfOneOfsRequestBody] + +class ArrayOfOneOfsHandlerFunction(Protocol): + def __call__(self, input: ArrayOfOneOfsRequest, **kwargs) -> ArrayOfOneOfsOperationResponses: + ... + +ArrayOfOneOfsInterceptor = Callable[[ArrayOfOneOfsChainedRequest], ArrayOfOneOfsOperationResponses] + +def array_of_one_ofs_handler(_handler: ArrayOfOneOfsHandlerFunction = None, interceptors: List[ArrayOfOneOfsInterceptor] = []): + """ + Decorator for an api handler for the array_of_one_ofs operation, providing a typed interface for inputs and outputs + """ + def _handler_wrapper(handler: ArrayOfOneOfsHandlerFunction): + @wraps(handler) + def wrapper(event, context, additional_interceptors = [], **kwargs): + all_interceptors = additional_interceptors + interceptors + + raw_string_parameters = decode_request_parameters({ + **(event.get('pathParameters', {}) or {}), + **(event.get('queryStringParameters', {}) or {}), + **(event.get('headers', {}) or {}), + }) + raw_string_array_parameters = decode_request_parameters({ + **(event.get('multiValueQueryStringParameters', {}) or {}), + **(event.get('multiValueHeaders', {}) or {}), + }) + + def response_headers_for_status_code(status_code): + headers_for_status = {} + return headers_for_status + + request_parameters = None + try: + request_parameters = ArrayOfOneOfsRequestParameters.from_dict({ + }) + except Exception as e: + return { + 'statusCode': 400, + 'headers': {**response_headers_for_status_code(400), **extract_response_headers_from_interceptors(all_interceptors)}, + 'body': '{"message": "' + str(e) + '"}', + } + + body = {} + interceptor_context = { + "operationId": "array_of_one_ofs", + } + + chain = _build_handler_chain(all_interceptors, handler) + response = chain.next(ApiRequest( + request_parameters, + body, + event, + context, + interceptor_context, + ), **kwargs) + + response_headers = {** (response.headers or {}), **response_headers_for_status_code(response.status_code)} + response_body = '' + if response.body is None: + pass + elif response.status_code == 200: + response_body = response.body.to_json() + + return { + 'statusCode': response.status_code, + 'headers': response_headers, + 'multiValueHeaders': response.multi_value_headers or {}, + 'body': response_body, + } + return wrapper + + # Support use as a decorator with no arguments, or with interceptor arguments + if callable(_handler): + return _handler_wrapper(_handler) + elif _handler is None: + return _handler_wrapper + else: + raise Exception("Positional arguments are not supported by array_of_one_ofs_handler.") + class ArrayRequestParametersRequestParameters(BaseModel): """ Query, path and header parameters for the ArrayRequestParameters operation @@ -19375,7 +20199,122 @@ def array_request_parameters_handler(_handler: ArrayRequestParametersHandlerFunc body = {} interceptor_context = { - "operationId": "array_request_parameters", + "operationId": "array_request_parameters", + } + + chain = _build_handler_chain(all_interceptors, handler) + response = chain.next(ApiRequest( + request_parameters, + body, + event, + context, + interceptor_context, + ), **kwargs) + + response_headers = {** (response.headers or {}), **response_headers_for_status_code(response.status_code)} + response_body = '' + if response.body is None: + pass + elif response.status_code == 200: + response_body = response.body + + return { + 'statusCode': response.status_code, + 'headers': response_headers, + 'multiValueHeaders': response.multi_value_headers or {}, + 'body': response_body, + } + return wrapper + + # Support use as a decorator with no arguments, or with interceptor arguments + if callable(_handler): + return _handler_wrapper(_handler) + elif _handler is None: + return _handler_wrapper + else: + raise Exception("Positional arguments are not supported by array_request_parameters_handler.") + +class InlineEnumRequestParameters(BaseModel): + """ + Query, path and header parameters for the InlineEnum operation + """ + + class Config: + """Pydantic configuration""" + populate_by_name = True + validate_assignment = True + + def to_json(self) -> str: + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> InlineEnumRequestParameters: + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + return self.model_dump(exclude={}, exclude_none=True) + + @classmethod + def from_dict(cls, obj: dict) -> InlineEnumRequestParameters: + if obj is None: + return None + return InlineEnumRequestParameters.model_validate(obj) + + +# Request body type (default to Any when no body parameters exist, or leave unchanged as str if it's a primitive type) +InlineEnumRequestBody = Any + +InlineEnum200OperationResponse = ApiResponse[Literal[200], InlineEnum200Response] + +InlineEnumOperationResponses = Union[InlineEnum200OperationResponse, ] + +# Request type for inline_enum +InlineEnumRequest = ApiRequest[InlineEnumRequestParameters, InlineEnumRequestBody] +InlineEnumChainedRequest = ChainedApiRequest[InlineEnumRequestParameters, InlineEnumRequestBody] + +class InlineEnumHandlerFunction(Protocol): + def __call__(self, input: InlineEnumRequest, **kwargs) -> InlineEnumOperationResponses: + ... + +InlineEnumInterceptor = Callable[[InlineEnumChainedRequest], InlineEnumOperationResponses] + +def inline_enum_handler(_handler: InlineEnumHandlerFunction = None, interceptors: List[InlineEnumInterceptor] = []): + """ + Decorator for an api handler for the inline_enum operation, providing a typed interface for inputs and outputs + """ + def _handler_wrapper(handler: InlineEnumHandlerFunction): + @wraps(handler) + def wrapper(event, context, additional_interceptors = [], **kwargs): + all_interceptors = additional_interceptors + interceptors + + raw_string_parameters = decode_request_parameters({ + **(event.get('pathParameters', {}) or {}), + **(event.get('queryStringParameters', {}) or {}), + **(event.get('headers', {}) or {}), + }) + raw_string_array_parameters = decode_request_parameters({ + **(event.get('multiValueQueryStringParameters', {}) or {}), + **(event.get('multiValueHeaders', {}) or {}), + }) + + def response_headers_for_status_code(status_code): + headers_for_status = {} + return headers_for_status + + request_parameters = None + try: + request_parameters = InlineEnumRequestParameters.from_dict({ + }) + except Exception as e: + return { + 'statusCode': 400, + 'headers': {**response_headers_for_status_code(400), **extract_response_headers_from_interceptors(all_interceptors)}, + 'body': '{"message": "' + str(e) + '"}', + } + + body = {} + interceptor_context = { + "operationId": "inline_enum", } chain = _build_handler_chain(all_interceptors, handler) @@ -19392,7 +20331,7 @@ def array_request_parameters_handler(_handler: ArrayRequestParametersHandlerFunc if response.body is None: pass elif response.status_code == 200: - response_body = response.body + response_body = response.body.to_json() return { 'statusCode': response.status_code, @@ -19408,11 +20347,11 @@ def array_request_parameters_handler(_handler: ArrayRequestParametersHandlerFunc elif _handler is None: return _handler_wrapper else: - raise Exception("Positional arguments are not supported by array_request_parameters_handler.") + raise Exception("Positional arguments are not supported by inline_enum_handler.") -class InlineEnumRequestParameters(BaseModel): +class InlineRequestBodyRequestParameters(BaseModel): """ - Query, path and header parameters for the InlineEnum operation + Query, path and header parameters for the InlineRequestBody operation """ class Config: @@ -19424,41 +20363,41 @@ class InlineEnumRequestParameters(BaseModel): return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> InlineEnumRequestParameters: + def from_json(cls, json_str: str) -> InlineRequestBodyRequestParameters: return cls.from_dict(json.loads(json_str)) def to_dict(self): return self.model_dump(exclude={}, exclude_none=True) @classmethod - def from_dict(cls, obj: dict) -> InlineEnumRequestParameters: + def from_dict(cls, obj: dict) -> InlineRequestBodyRequestParameters: if obj is None: return None - return InlineEnumRequestParameters.model_validate(obj) + return InlineRequestBodyRequestParameters.model_validate(obj) # Request body type (default to Any when no body parameters exist, or leave unchanged as str if it's a primitive type) -InlineEnumRequestBody = Any +InlineRequestBodyRequestBody = InlineRequestBodyRequestContent -InlineEnum200OperationResponse = ApiResponse[Literal[200], InlineEnum200Response] +InlineRequestBody204OperationResponse = ApiResponse[Literal[204], None] -InlineEnumOperationResponses = Union[InlineEnum200OperationResponse, ] +InlineRequestBodyOperationResponses = Union[InlineRequestBody204OperationResponse, ] -# Request type for inline_enum -InlineEnumRequest = ApiRequest[InlineEnumRequestParameters, InlineEnumRequestBody] -InlineEnumChainedRequest = ChainedApiRequest[InlineEnumRequestParameters, InlineEnumRequestBody] +# Request type for inline_request_body +InlineRequestBodyRequest = ApiRequest[InlineRequestBodyRequestParameters, InlineRequestBodyRequestBody] +InlineRequestBodyChainedRequest = ChainedApiRequest[InlineRequestBodyRequestParameters, InlineRequestBodyRequestBody] -class InlineEnumHandlerFunction(Protocol): - def __call__(self, input: InlineEnumRequest, **kwargs) -> InlineEnumOperationResponses: +class InlineRequestBodyHandlerFunction(Protocol): + def __call__(self, input: InlineRequestBodyRequest, **kwargs) -> InlineRequestBodyOperationResponses: ... -InlineEnumInterceptor = Callable[[InlineEnumChainedRequest], InlineEnumOperationResponses] +InlineRequestBodyInterceptor = Callable[[InlineRequestBodyChainedRequest], InlineRequestBodyOperationResponses] -def inline_enum_handler(_handler: InlineEnumHandlerFunction = None, interceptors: List[InlineEnumInterceptor] = []): +def inline_request_body_handler(_handler: InlineRequestBodyHandlerFunction = None, interceptors: List[InlineRequestBodyInterceptor] = []): """ - Decorator for an api handler for the inline_enum operation, providing a typed interface for inputs and outputs + Decorator for an api handler for the inline_request_body operation, providing a typed interface for inputs and outputs """ - def _handler_wrapper(handler: InlineEnumHandlerFunction): + def _handler_wrapper(handler: InlineRequestBodyHandlerFunction): @wraps(handler) def wrapper(event, context, additional_interceptors = [], **kwargs): all_interceptors = additional_interceptors + interceptors @@ -19479,7 +20418,7 @@ def inline_enum_handler(_handler: InlineEnumHandlerFunction = None, interceptors request_parameters = None try: - request_parameters = InlineEnumRequestParameters.from_dict({ + request_parameters = InlineRequestBodyRequestParameters.from_dict({ }) except Exception as e: return { @@ -19488,9 +20427,10 @@ def inline_enum_handler(_handler: InlineEnumHandlerFunction = None, interceptors 'body': '{"message": "' + str(e) + '"}', } - body = {} + # Non-primitive type so parse the body into the appropriate model + body = parse_body(event['body'], ['application/json'], InlineRequestBodyRequestBody) interceptor_context = { - "operationId": "inline_enum", + "operationId": "inline_request_body", } chain = _build_handler_chain(all_interceptors, handler) @@ -19506,8 +20446,8 @@ def inline_enum_handler(_handler: InlineEnumHandlerFunction = None, interceptors response_body = '' if response.body is None: pass - elif response.status_code == 200: - response_body = response.body.to_json() + elif response.status_code == 204: + response_body = response.body return { 'statusCode': response.status_code, @@ -19523,11 +20463,11 @@ def inline_enum_handler(_handler: InlineEnumHandlerFunction = None, interceptors elif _handler is None: return _handler_wrapper else: - raise Exception("Positional arguments are not supported by inline_enum_handler.") + raise Exception("Positional arguments are not supported by inline_request_body_handler.") -class InlineRequestBodyRequestParameters(BaseModel): +class NamedOneOfRequestParameters(BaseModel): """ - Query, path and header parameters for the InlineRequestBody operation + Query, path and header parameters for the NamedOneOf operation """ class Config: @@ -19539,41 +20479,41 @@ class InlineRequestBodyRequestParameters(BaseModel): return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> InlineRequestBodyRequestParameters: + def from_json(cls, json_str: str) -> NamedOneOfRequestParameters: return cls.from_dict(json.loads(json_str)) def to_dict(self): return self.model_dump(exclude={}, exclude_none=True) @classmethod - def from_dict(cls, obj: dict) -> InlineRequestBodyRequestParameters: + def from_dict(cls, obj: dict) -> NamedOneOfRequestParameters: if obj is None: return None - return InlineRequestBodyRequestParameters.model_validate(obj) + return NamedOneOfRequestParameters.model_validate(obj) # Request body type (default to Any when no body parameters exist, or leave unchanged as str if it's a primitive type) -InlineRequestBodyRequestBody = InlineRequestBodyRequestContent +NamedOneOfRequestBody = Any -InlineRequestBody204OperationResponse = ApiResponse[Literal[204], None] +NamedOneOf200OperationResponse = ApiResponse[Literal[200], NamedOneOfUnion] -InlineRequestBodyOperationResponses = Union[InlineRequestBody204OperationResponse, ] +NamedOneOfOperationResponses = Union[NamedOneOf200OperationResponse, ] -# Request type for inline_request_body -InlineRequestBodyRequest = ApiRequest[InlineRequestBodyRequestParameters, InlineRequestBodyRequestBody] -InlineRequestBodyChainedRequest = ChainedApiRequest[InlineRequestBodyRequestParameters, InlineRequestBodyRequestBody] +# Request type for named_one_of +NamedOneOfRequest = ApiRequest[NamedOneOfRequestParameters, NamedOneOfRequestBody] +NamedOneOfChainedRequest = ChainedApiRequest[NamedOneOfRequestParameters, NamedOneOfRequestBody] -class InlineRequestBodyHandlerFunction(Protocol): - def __call__(self, input: InlineRequestBodyRequest, **kwargs) -> InlineRequestBodyOperationResponses: +class NamedOneOfHandlerFunction(Protocol): + def __call__(self, input: NamedOneOfRequest, **kwargs) -> NamedOneOfOperationResponses: ... -InlineRequestBodyInterceptor = Callable[[InlineRequestBodyChainedRequest], InlineRequestBodyOperationResponses] +NamedOneOfInterceptor = Callable[[NamedOneOfChainedRequest], NamedOneOfOperationResponses] -def inline_request_body_handler(_handler: InlineRequestBodyHandlerFunction = None, interceptors: List[InlineRequestBodyInterceptor] = []): +def named_one_of_handler(_handler: NamedOneOfHandlerFunction = None, interceptors: List[NamedOneOfInterceptor] = []): """ - Decorator for an api handler for the inline_request_body operation, providing a typed interface for inputs and outputs + Decorator for an api handler for the named_one_of operation, providing a typed interface for inputs and outputs """ - def _handler_wrapper(handler: InlineRequestBodyHandlerFunction): + def _handler_wrapper(handler: NamedOneOfHandlerFunction): @wraps(handler) def wrapper(event, context, additional_interceptors = [], **kwargs): all_interceptors = additional_interceptors + interceptors @@ -19594,7 +20534,7 @@ def inline_request_body_handler(_handler: InlineRequestBodyHandlerFunction = Non request_parameters = None try: - request_parameters = InlineRequestBodyRequestParameters.from_dict({ + request_parameters = NamedOneOfRequestParameters.from_dict({ }) except Exception as e: return { @@ -19603,10 +20543,9 @@ def inline_request_body_handler(_handler: InlineRequestBodyHandlerFunction = Non 'body': '{"message": "' + str(e) + '"}', } - # Non-primitive type so parse the body into the appropriate model - body = parse_body(event['body'], ['application/json'], InlineRequestBodyRequestBody) + body = {} interceptor_context = { - "operationId": "inline_request_body", + "operationId": "named_one_of", } chain = _build_handler_chain(all_interceptors, handler) @@ -19622,8 +20561,8 @@ def inline_request_body_handler(_handler: InlineRequestBodyHandlerFunction = Non response_body = '' if response.body is None: pass - elif response.status_code == 204: - response_body = response.body + elif response.status_code == 200: + response_body = response.body.to_json() return { 'statusCode': response.status_code, @@ -19639,7 +20578,7 @@ def inline_request_body_handler(_handler: InlineRequestBodyHandlerFunction = Non elif _handler is None: return _handler_wrapper else: - raise Exception("Positional arguments are not supported by inline_request_body_handler.") + raise Exception("Positional arguments are not supported by named_one_of_handler.") class ReservedKeywordsRequestParameters(BaseModel): """ @@ -19771,9 +20710,11 @@ OperationIdByMethodAndPath = { concat_method_and_path(method_and_path["method"], @dataclass class HandlerRouterHandlers: + array_of_one_ofs: Callable[[Dict, Any], Dict] array_request_parameters: Callable[[Dict, Any], Dict] inline_enum: Callable[[Dict, Any], Dict] inline_request_body: Callable[[Dict, Any], Dict] + named_one_of: Callable[[Dict, Any], Dict] reserved_keywords: Callable[[Dict, Any], Dict] def handler_router(handlers: HandlerRouterHandlers, interceptors: List[Interceptor] = []): @@ -21308,45 +22249,231 @@ cors_interceptor = build_response_headers_interceptor(CORS_HEADERS) from test_project.response import Response -def try_catch_interceptor(request: ChainedApiRequest) -> ApiResponse: - """ - Interceptor for catching unhandled exceptions and returning a 500 error. - Uncaught exceptions which are ApiResponses will be returned, such that deeply nested code may return error - responses, eg: \`throw Response.not_found(...)\` - """ - try: - return request.chain.next(request) - except ApiResponse as response: - # If the error is a response, return it as the response - return response - except Exception as e: - if request.interceptor_context.get("logger") is not None: - request.interceptor_context.get("logger").exception("Interceptor caught exception") - else: - print("Interceptor caught exception") - print(e) +def try_catch_interceptor(request: ChainedApiRequest) -> ApiResponse: + """ + Interceptor for catching unhandled exceptions and returning a 500 error. + Uncaught exceptions which are ApiResponses will be returned, such that deeply nested code may return error + responses, eg: \`throw Response.not_found(...)\` + """ + try: + return request.chain.next(request) + except ApiResponse as response: + # If the error is a response, return it as the response + return response + except Exception as e: + if request.interceptor_context.get("logger") is not None: + request.interceptor_context.get("logger").exception("Interceptor caught exception") + else: + print("Interceptor caught exception") + print(e) + + return Response.internal_failure({ "message": "Internal Error" }) +", + "test_project/models/__init__.py": "# coding: utf-8 + +# flake8: noqa +""" + Edge Cases + + No description provided + + The version of the OpenAPI document: 1.0.0 + + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 + +# import models into model package +from test_project.models.another_named_one_of import AnotherNamedOneOf +from test_project.models.array_of_one_ofs import ArrayOfOneOfs +from test_project.models.inline_enum200_response import InlineEnum200Response +from test_project.models.inline_enum200_response_category_enum import InlineEnum200ResponseCategoryEnum +from test_project.models.inline_request_body_request_content import InlineRequestBodyRequestContent +from test_project.models.my_enum import MyEnum +from test_project.models.named_one_of import NamedOneOf +from test_project.models.named_one_of_union import NamedOneOfUnion +", + "test_project/models/another_named_one_of.py": "# coding: utf-8 + +""" + Edge Cases + + No description provided + + The version of the OpenAPI document: 1.0.0 + + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class AnotherNamedOneOf(BaseModel): + """ + AnotherNamedOneOf + """ # noqa: E501 + bar: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["bar"] + + + model_config = { + "populate_by_name": True, + "validate_assignment": True + } + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AnotherNamedOneOf from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + \`self.model_dump(by_alias=True)\`: + + * \`None\` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value \`None\` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of AnotherNamedOneOf from a dict""" + + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "bar": obj.get("bar") + }) + return _obj + +", + "test_project/models/array_of_one_ofs.py": "# coding: utf-8 + +""" + Edge Cases + + No description provided + + The version of the OpenAPI document: 1.0.0 + + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +from test_project.models.named_one_of_union import NamedOneOfUnion +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class ArrayOfOneOfs(BaseModel): + """ + ArrayOfOneOfs + """ # noqa: E501 + one_ofs: Optional[List[Any]] = Field(default=None, alias="oneOfs") + __properties: ClassVar[List[str]] = ["oneOfs"] + + + model_config = { + "populate_by_name": True, + "validate_assignment": True + } + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ArrayOfOneOfs from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + \`self.model_dump(by_alias=True)\`: - return Response.internal_failure({ "message": "Internal Error" }) -", - "test_project/models/__init__.py": "# coding: utf-8 + * \`None\` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value \`None\` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling \`to_dict()\` of one_ofs + if self.one_ofs: + _dict['oneOfs'] = self.one_ofs.to_dict() + return _dict -# flake8: noqa -""" - Edge Cases + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of ArrayOfOneOfs from a dict""" - No description provided + if obj is None: + return None - The version of the OpenAPI document: 1.0.0 + if not isinstance(obj, dict): + return cls.model_validate(obj) - NOTE: This class is auto generated. - Do not edit the class manually. -""" # noqa: E501 + _obj = cls.model_validate({ + "oneOfs": List[NamedOneOfUnion].from_dict(obj.get("oneOfs")) if obj.get("oneOfs") is not None else None + }) + return _obj -# import models into model package -from test_project.models.inline_enum200_response import InlineEnum200Response -from test_project.models.inline_enum200_response_category_enum import InlineEnum200ResponseCategoryEnum -from test_project.models.inline_request_body_request_content import InlineRequestBodyRequestContent -from test_project.models.my_enum import MyEnum ", "test_project/models/inline_enum200_response.py": "# coding: utf-8 @@ -21624,6 +22751,237 @@ class MyEnum(str, Enum): +", + "test_project/models/named_one_of.py": "# coding: utf-8 + +""" + Edge Cases + + No description provided + + The version of the OpenAPI document: 1.0.0 + + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class NamedOneOf(BaseModel): + """ + NamedOneOf + """ # noqa: E501 + foo: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["foo"] + + + model_config = { + "populate_by_name": True, + "validate_assignment": True + } + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of NamedOneOf from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + \`self.model_dump(by_alias=True)\`: + + * \`None\` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value \`None\` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of NamedOneOf from a dict""" + + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "foo": obj.get("foo") + }) + return _obj + +", + "test_project/models/named_one_of_union.py": "# coding: utf-8 + +""" + Edge Cases + + No description provided + + The version of the OpenAPI document: 1.0.0 + + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +from test_project.models.another_named_one_of import AnotherNamedOneOf +from test_project.models.named_one_of import NamedOneOf +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +NAMEDONEOFUNION_ONE_OF_SCHEMAS = ["NamedOneOf", "AnotherNamedOneOf"] + +class NamedOneOfUnion(BaseModel): + """ + NamedOneOfUnion + """ # noqa: E501 + # data type: NamedOneOf + oneof_schema_1_validator: Optional[NamedOneOf] = None + # data type: AnotherNamedOneOf + oneof_schema_2_validator: Optional[AnotherNamedOneOf] = None + actual_instance: Optional[Union[NamedOneOf, AnotherNamedOneOf]] = None + one_of_schemas: List[str] = Literal["NamedOneOf", "AnotherNamedOneOf"] + + model_config = { + "validate_assignment": True + } + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set \`actual_instance\`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = NamedOneOfUnion.model_construct() + error_messages = [] + match = 0 + # validate data type: NamedOneOf + if not isinstance(v, NamedOneOf): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`NamedOneOf\`") + else: + match += 1 + # validate data type: AnotherNamedOneOf + if not isinstance(v, AnotherNamedOneOf): + error_messages.append(f"Error! Input type \`{type(v)}\` is not \`AnotherNamedOneOf\`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting \`actual_instance\` in NamedOneOfUnion with oneOf schemas: NamedOneOf, AnotherNamedOneOf. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting \`actual_instance\` in NamedOneOfUnion with oneOf schemas: NamedOneOf, AnotherNamedOneOf. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into NamedOneOf + try: + instance.actual_instance = NamedOneOf.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into AnotherNamedOneOf + try: + instance.actual_instance = AnotherNamedOneOf.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into NamedOneOfUnion with oneOf schemas: NamedOneOf, AnotherNamedOneOf. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into NamedOneOfUnion with oneOf schemas: NamedOneOf, AnotherNamedOneOf. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + to_dict = getattr(self.actual_instance, "to_dict", None) + if callable(to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + ", "test_project/py.typed": "", "test_project/response.py": "from typing import TypeVar, Generic, Dict, List diff --git a/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript.test.ts.snap b/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript.test.ts.snap index 82ef4cbab..d08e86eb8 100644 --- a/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript.test.ts.snap +++ b/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript.test.ts.snap @@ -8237,10 +8237,14 @@ src/apis/DefaultApi.ts src/apis/index.ts src/models/index.ts src/models/model-utils.ts +src/models/AnotherNamedOneOf.ts +src/models/ArrayOfOneOfs.ts src/models/InlineEnum200Response.ts src/models/InlineEnum200ResponseCategoryEnum.ts src/models/InlineRequestBodyRequestContent.ts -src/models/MyEnum.ts", +src/models/MyEnum.ts +src/models/NamedOneOf.ts +src/models/NamedOneOfUnion.ts", "src/apis/DefaultApi.ts": "/* tslint:disable */ /* eslint-disable */ /** @@ -8256,19 +8260,26 @@ src/models/MyEnum.ts", import * as runtime from '../runtime'; import type { + ArrayOfOneOfs, InlineEnum200Response, InlineRequestBodyRequestContent, MyEnum, + NamedOneOfUnion, } from '../models'; import { + ArrayOfOneOfsFromJSON, + ArrayOfOneOfsToJSON, InlineEnum200ResponseFromJSON, InlineEnum200ResponseToJSON, InlineRequestBodyRequestContentFromJSON, InlineRequestBodyRequestContentToJSON, MyEnumFromJSON, MyEnumToJSON, + NamedOneOfUnionFromJSON, + NamedOneOfUnionToJSON, } from '../models'; + export interface ArrayRequestParametersRequest { myStringArrayRequestParams?: Array; myEnumArrayRequestParams?: Array; @@ -8286,6 +8297,7 @@ export interface InlineRequestBodyRequest { inlineRequestBodyRequestContent?: InlineRequestBodyRequestContent; } + export interface ReservedKeywordsRequest { _with?: string; _if?: string; @@ -8296,6 +8308,35 @@ export interface ReservedKeywordsRequest { * */ export class DefaultApi extends runtime.BaseAPI { + /** + * + */ + async arrayOfOneOfsRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + + const headerParameters: runtime.HTTPHeaders = {}; + + + + const response = await this.request({ + path: \`/array-of-one-ofs\`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => ArrayOfOneOfsFromJSON(jsonValue)); + } + + /** + * + */ + async arrayOfOneOfs(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.arrayOfOneOfsRaw(initOverrides); + return await response.value(); + } + /** * */ @@ -8419,6 +8460,35 @@ export class DefaultApi extends runtime.BaseAPI { await this.inlineRequestBodyRaw(requestParameters, initOverrides); } + /** + * + */ + async namedOneOfRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + + const headerParameters: runtime.HTTPHeaders = {}; + + + + const response = await this.request({ + path: \`/named-one-of\`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => NamedOneOfUnionFromJSON(jsonValue)); + } + + /** + * + */ + async namedOneOf(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.namedOneOfRaw(initOverrides); + return await response.value(); + } + /** * */ @@ -8464,6 +8534,12 @@ export class DefaultApi extends runtime.BaseAPI { ", "src/apis/DefaultApi/OperationConfig.ts": "// Import models import { + AnotherNamedOneOf, + AnotherNamedOneOfFromJSON, + AnotherNamedOneOfToJSON, + ArrayOfOneOfs, + ArrayOfOneOfsFromJSON, + ArrayOfOneOfsToJSON, InlineEnum200Response, InlineEnum200ResponseFromJSON, InlineEnum200ResponseToJSON, @@ -8476,6 +8552,12 @@ import { MyEnum, MyEnumFromJSON, MyEnumToJSON, + NamedOneOf, + NamedOneOfFromJSON, + NamedOneOfToJSON, + NamedOneOfUnion, + NamedOneOfUnionFromJSON, + NamedOneOfUnionToJSON, } from '../../models'; // Import request parameter interfaces import { @@ -8489,14 +8571,21 @@ import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from "aws-lambda // Generic type for object keyed by operation names export interface OperationConfig { + arrayOfOneOfs: T; arrayRequestParameters: T; inlineEnum: T; inlineRequestBody: T; + namedOneOf: T; reservedKeywords: T; } // Look up path and http method for a given operation name export const OperationLookup = { + arrayOfOneOfs: { + path: '/array-of-one-ofs', + method: 'POST', + contentTypes: ['application/json'], + }, arrayRequestParameters: { path: '/array-request-parameters', method: 'GET', @@ -8512,6 +8601,11 @@ export const OperationLookup = { method: 'POST', contentTypes: ['application/json'], }, + namedOneOf: { + path: '/named-one-of', + method: 'POST', + contentTypes: ['application/json'], + }, reservedKeywords: { path: '/reserved-keywords', method: 'GET', @@ -8633,7 +8727,7 @@ const extractResponseHeadersFromInterceptors = (interceptors: any[]): { [key: st }), {} as { [key: string]: string }); }; -export type OperationIds = | 'arrayRequestParameters' | 'inlineEnum' | 'inlineRequestBody' | 'reservedKeywords'; +export type OperationIds = | 'arrayOfOneOfs' | 'arrayRequestParameters' | 'inlineEnum' | 'inlineRequestBody' | 'namedOneOf' | 'reservedKeywords'; export type OperationApiGatewayProxyResult = APIGatewayProxyResult & { __operationId?: T }; // Api gateway lambda handler type @@ -8709,6 +8803,115 @@ const buildHandlerChain = ( }; }; +/** + * Path, Query and Header parameters for ArrayOfOneOfs + */ +export interface ArrayOfOneOfsRequestParameters { +} + +/** + * Request body parameter for ArrayOfOneOfs + */ +export type ArrayOfOneOfsRequestBody = never; + +export type ArrayOfOneOfs200OperationResponse = OperationResponse<200, ArrayOfOneOfs>; + +export type ArrayOfOneOfsOperationResponses = | ArrayOfOneOfs200OperationResponse ; + +// Type that the handler function provided to the wrapper must conform to +export type ArrayOfOneOfsHandlerFunction = LambdaHandlerFunction; +export type ArrayOfOneOfsChainedHandlerFunction = ChainedLambdaHandlerFunction; +export type ArrayOfOneOfsChainedRequestInput = ChainedRequestInput; + +/** + * Lambda handler wrapper to provide typed interface for the implementation of arrayOfOneOfs + */ +export const arrayOfOneOfsHandler = ( + ...handlers: [ArrayOfOneOfsChainedHandlerFunction, ...ArrayOfOneOfsChainedHandlerFunction[]] +): OperationApiGatewayLambdaHandler<'arrayOfOneOfs'> => async (event: any, context: any, _callback?: any, additionalInterceptors: ArrayOfOneOfsChainedHandlerFunction[] = []): Promise => { + const operationId = "arrayOfOneOfs"; + + const rawSingleValueParameters = decodeRequestParameters({ + ...(event.pathParameters || {}), + ...(event.queryStringParameters || {}), + ...(event.headers || {}), + }) as { [key: string]: string | undefined }; + const rawMultiValueParameters = decodeRequestParameters({ + ...(event.multiValueQueryStringParameters || {}), + ...(event.multiValueHeaders || {}), + }) as { [key: string]: string[] | undefined }; + + const marshal = (statusCode: number, responseBody: any): string => { + let marshalledBody = responseBody; + switch(statusCode) { + case 200: + marshalledBody = JSON.stringify(ArrayOfOneOfsToJSON(marshalledBody)); + break; + default: + break; + } + + return marshalledBody; + }; + + const errorHeaders = (statusCode: number): { [key: string]: string } => { + let headers = {}; + + switch(statusCode) { + default: + break; + } + + return headers; + }; + + let requestParameters: ArrayOfOneOfsRequestParameters | undefined = undefined; + + try { + requestParameters = { + + }; + } catch (e: any) { + const res = { + statusCode: 400, + body: { message: e.message }, + headers: extractResponseHeadersFromInterceptors(handlers), + }; + return { + ...res, + headers: { + ...errorHeaders(res.statusCode), + ...res.headers, + }, + body: res.body ? marshal(res.statusCode, res.body) : '', + }; + } + + const demarshal = (bodyString: string): any => { + return {}; + }; + const body = parseBody(event.body, demarshal, ['application/json']) as ArrayOfOneOfsRequestBody; + + const chain = buildHandlerChain(...additionalInterceptors, ...handlers); + const response = await chain.next({ + input: { + requestParameters, + body, + }, + event, + context, + interceptorContext: { operationId }, + }); + + return { + ...response, + headers: { + ...errorHeaders(response.statusCode), + ...response.headers, + }, + body: response.body ? marshal(response.statusCode, response.body) : '', + }; +}; /** * Path, Query and Header parameters for ArrayRequestParameters */ @@ -9052,6 +9255,115 @@ export const inlineRequestBodyHandler = ( body: response.body ? marshal(response.statusCode, response.body) : '', }; }; +/** + * Path, Query and Header parameters for NamedOneOf + */ +export interface NamedOneOfRequestParameters { +} + +/** + * Request body parameter for NamedOneOf + */ +export type NamedOneOfRequestBody = never; + +export type NamedOneOf200OperationResponse = OperationResponse<200, NamedOneOfUnion>; + +export type NamedOneOfOperationResponses = | NamedOneOf200OperationResponse ; + +// Type that the handler function provided to the wrapper must conform to +export type NamedOneOfHandlerFunction = LambdaHandlerFunction; +export type NamedOneOfChainedHandlerFunction = ChainedLambdaHandlerFunction; +export type NamedOneOfChainedRequestInput = ChainedRequestInput; + +/** + * Lambda handler wrapper to provide typed interface for the implementation of namedOneOf + */ +export const namedOneOfHandler = ( + ...handlers: [NamedOneOfChainedHandlerFunction, ...NamedOneOfChainedHandlerFunction[]] +): OperationApiGatewayLambdaHandler<'namedOneOf'> => async (event: any, context: any, _callback?: any, additionalInterceptors: NamedOneOfChainedHandlerFunction[] = []): Promise => { + const operationId = "namedOneOf"; + + const rawSingleValueParameters = decodeRequestParameters({ + ...(event.pathParameters || {}), + ...(event.queryStringParameters || {}), + ...(event.headers || {}), + }) as { [key: string]: string | undefined }; + const rawMultiValueParameters = decodeRequestParameters({ + ...(event.multiValueQueryStringParameters || {}), + ...(event.multiValueHeaders || {}), + }) as { [key: string]: string[] | undefined }; + + const marshal = (statusCode: number, responseBody: any): string => { + let marshalledBody = responseBody; + switch(statusCode) { + case 200: + marshalledBody = JSON.stringify(NamedOneOfUnionToJSON(marshalledBody)); + break; + default: + break; + } + + return marshalledBody; + }; + + const errorHeaders = (statusCode: number): { [key: string]: string } => { + let headers = {}; + + switch(statusCode) { + default: + break; + } + + return headers; + }; + + let requestParameters: NamedOneOfRequestParameters | undefined = undefined; + + try { + requestParameters = { + + }; + } catch (e: any) { + const res = { + statusCode: 400, + body: { message: e.message }, + headers: extractResponseHeadersFromInterceptors(handlers), + }; + return { + ...res, + headers: { + ...errorHeaders(res.statusCode), + ...res.headers, + }, + body: res.body ? marshal(res.statusCode, res.body) : '', + }; + } + + const demarshal = (bodyString: string): any => { + return {}; + }; + const body = parseBody(event.body, demarshal, ['application/json']) as NamedOneOfRequestBody; + + const chain = buildHandlerChain(...additionalInterceptors, ...handlers); + const response = await chain.next({ + input: { + requestParameters, + body, + }, + event, + context, + interceptorContext: { operationId }, + }); + + return { + ...response, + headers: { + ...errorHeaders(response.statusCode), + ...response.headers, + }, + body: response.body ? marshal(response.statusCode, response.body) : '', + }; +}; /** * Path, Query and Header parameters for ReservedKeywords */ @@ -9168,15 +9480,17 @@ export const reservedKeywordsHandler = ( }; export interface HandlerRouterHandlers { + readonly arrayOfOneOfs: OperationApiGatewayLambdaHandler<'arrayOfOneOfs'>; readonly arrayRequestParameters: OperationApiGatewayLambdaHandler<'arrayRequestParameters'>; readonly inlineEnum: OperationApiGatewayLambdaHandler<'inlineEnum'>; readonly inlineRequestBody: OperationApiGatewayLambdaHandler<'inlineRequestBody'>; + readonly namedOneOf: OperationApiGatewayLambdaHandler<'namedOneOf'>; readonly reservedKeywords: OperationApiGatewayLambdaHandler<'reservedKeywords'>; } -export type AnyOperationRequestParameters = | ArrayRequestParametersRequestParameters| InlineEnumRequestParameters| InlineRequestBodyRequestParameters| ReservedKeywordsRequestParameters; -export type AnyOperationRequestBodies = | ArrayRequestParametersRequestBody| InlineEnumRequestBody| InlineRequestBodyRequestBody| ReservedKeywordsRequestBody; -export type AnyOperationResponses = | ArrayRequestParametersOperationResponses| InlineEnumOperationResponses| InlineRequestBodyOperationResponses| ReservedKeywordsOperationResponses; +export type AnyOperationRequestParameters = | ArrayOfOneOfsRequestParameters| ArrayRequestParametersRequestParameters| InlineEnumRequestParameters| InlineRequestBodyRequestParameters| NamedOneOfRequestParameters| ReservedKeywordsRequestParameters; +export type AnyOperationRequestBodies = | ArrayOfOneOfsRequestBody| ArrayRequestParametersRequestBody| InlineEnumRequestBody| InlineRequestBodyRequestBody| NamedOneOfRequestBody| ReservedKeywordsRequestBody; +export type AnyOperationResponses = | ArrayOfOneOfsOperationResponses| ArrayRequestParametersOperationResponses| InlineEnumOperationResponses| InlineRequestBodyOperationResponses| NamedOneOfOperationResponses| ReservedKeywordsOperationResponses; export interface HandlerRouterProps< RequestParameters, @@ -9520,6 +9834,143 @@ export const buildTryCatchInterceptor = } + * @memberof ArrayOfOneOfs + */ + oneOfs?: Array; +} + + +/** + * Check if a given object implements the ArrayOfOneOfs interface. + */ +export function instanceOfArrayOfOneOfs(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function ArrayOfOneOfsFromJSON(json: any): ArrayOfOneOfs { + return ArrayOfOneOfsFromJSONTyped(json, false); +} + +export function ArrayOfOneOfsFromJSONTyped(json: any, ignoreDiscriminator: boolean): ArrayOfOneOfs { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'oneOfs': !exists(json, 'oneOfs') ? undefined : ((json['oneOfs'] as Array).map(NamedOneOfUnionFromJSON)), + }; +} + +export function ArrayOfOneOfsToJSON(value?: ArrayOfOneOfs | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'oneOfs': value.oneOfs === undefined ? undefined : ((value.oneOfs as Array).map(NamedOneOfUnionToJSON)), + }; +} + ", "src/models/InlineEnum200Response.ts": "/* tslint:disable */ /* eslint-disable */ @@ -9736,13 +10187,153 @@ export function MyEnumToJSON(value?: MyEnum | null): any { return value; } +", + "src/models/NamedOneOf.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ +import { exists, mapValues } from './model-utils'; + +/** + * + * @export + * @interface NamedOneOf + */ +export interface NamedOneOf { + /** + * + * @type {string} + * @memberof NamedOneOf + */ + foo?: string; +} + + +/** + * Check if a given object implements the NamedOneOf interface. + */ +export function instanceOfNamedOneOf(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function NamedOneOfFromJSON(json: any): NamedOneOf { + return NamedOneOfFromJSONTyped(json, false); +} + +export function NamedOneOfFromJSONTyped(json: any, ignoreDiscriminator: boolean): NamedOneOf { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'foo': !exists(json, 'foo') ? undefined : json['foo'], + }; +} + +export function NamedOneOfToJSON(value?: NamedOneOf | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'foo': value.foo, + }; +} + +", + "src/models/NamedOneOfUnion.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ +import { exists, mapValues } from './model-utils'; +import type { AnotherNamedOneOf } from './AnotherNamedOneOf'; +import { + AnotherNamedOneOfFromJSON, + AnotherNamedOneOfFromJSONTyped, + AnotherNamedOneOfToJSON, + instanceOfAnotherNamedOneOf, +} from './AnotherNamedOneOf'; +import type { NamedOneOf } from './NamedOneOf'; +import { + NamedOneOfFromJSON, + NamedOneOfFromJSONTyped, + NamedOneOfToJSON, + instanceOfNamedOneOf, +} from './NamedOneOf'; + +/** + * @type NamedOneOfUnion + * + * @export + */ +export type NamedOneOfUnion = NamedOneOf | AnotherNamedOneOf; + + +/** + * Check if a given object implements the NamedOneOfUnion interface. + */ +export function instanceOfNamedOneOfUnion(value: object): boolean { + return instanceOfNamedOneOf(value) || instanceOfAnotherNamedOneOf(value) +} + +export function NamedOneOfUnionFromJSON(json: any): NamedOneOfUnion { + return NamedOneOfUnionFromJSONTyped(json, false); +} + +export function NamedOneOfUnionFromJSONTyped(json: any, ignoreDiscriminator: boolean): NamedOneOfUnion { + if ((json === undefined) || (json === null)) { + return json; + } + return { + ...NamedOneOfFromJSONTyped(json, true), + ...AnotherNamedOneOfFromJSONTyped(json, true), + }; +} + +export function NamedOneOfUnionToJSON(value?: NamedOneOfUnion | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + ...NamedOneOfToJSON(value as any), + ...AnotherNamedOneOfToJSON(value as any), + }; +} + ", "src/models/index.ts": "/* tslint:disable */ /* eslint-disable */ +export * from './AnotherNamedOneOf'; +export * from './ArrayOfOneOfs'; export * from './InlineEnum200Response'; export * from './InlineEnum200ResponseCategoryEnum'; export * from './InlineRequestBodyRequestContent'; export * from './MyEnum'; +export * from './NamedOneOf'; +export * from './NamedOneOfUnion'; ", "src/models/model-utils.ts": "/* tslint:disable */ /* eslint-disable */ From d47822cd550341489ef90e5ec59b3f4e8f09be49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9F=9A=80=20Jack?= Date: Wed, 30 Oct 2024 15:54:38 +1100 Subject: [PATCH 2/2] fix(type-safe-api): fix typescript generated code for dictionary types --- .../templates/client/models/models.ejs | 8 +- .../test/resources/specs/edge-cases.yaml | 30 + .../__snapshots__/java.test.ts.snap | 1862 ++++++++++++++--- .../__snapshots__/python.test.ts.snap | 798 ++++++- .../__snapshots__/typescript.test.ts.snap | 371 +++- 5 files changed, 2761 insertions(+), 308 deletions(-) diff --git a/packages/type-safe-api/scripts/type-safe-api/generators/typescript/templates/client/models/models.ejs b/packages/type-safe-api/scripts/type-safe-api/generators/typescript/templates/client/models/models.ejs index 78d5c434e..a28a68295 100644 --- a/packages/type-safe-api/scripts/type-safe-api/generators/typescript/templates/client/models/models.ejs +++ b/packages/type-safe-api/scripts/type-safe-api/generators/typescript/templates/client/models/models.ejs @@ -62,8 +62,8 @@ export type <%- model.name %> =<% model.properties.forEach((composedType, i) => <%_ } _%> */ export interface <%= model.name %> { -<%_ if (model.additionalProperties) { _%> - [key: string]: <%- model.additionalProperties.typescriptType %>; +<%_ if (model.export === "dictionary" && model.link) { _%> + [key: string]: <%- model.link.typescriptType %>; <%_ } _%> <%_ model.properties.forEach((property) => { _%> /** @@ -126,7 +126,7 @@ export function <%= model.name %>FromJSONTyped(json: any, ignoreDiscriminator: b <%_ } else { _%> return { -<%_ if (model.additionalProperties) { _%> +<%_ if (model.export === "dictionary") { _%> ...json, <%_ } _%> <%_ model.properties.forEach((property) => { _%> @@ -173,7 +173,7 @@ export function <%= model.name %>ToJSON(value?: <%= model.name %> | null): any { <%_ } else { _%> return { -<%_ if (model.additionalProperties) { _%> +<%_ if (model.export === "dictionary") { _%> ...value, <%_ } _%> <%_ model.properties.forEach((property) => { _%> diff --git a/packages/type-safe-api/test/resources/specs/edge-cases.yaml b/packages/type-safe-api/test/resources/specs/edge-cases.yaml index 31aa20015..cf100a7a6 100644 --- a/packages/type-safe-api/test/resources/specs/edge-cases.yaml +++ b/packages/type-safe-api/test/resources/specs/edge-cases.yaml @@ -138,6 +138,16 @@ paths: application/json: schema: $ref: "#/components/schemas/ArrayOfOneOfs" + /additional-properties: + post: + operationId: dictionary + responses: + 200: + description: ok + content: + application/json: + schema: + $ref: "#/components/schemas/AdditionalPropertiesResponse" components: schemas: MyEnum: @@ -165,3 +175,23 @@ components: type: array items: $ref: "#/components/schemas/NamedOneOfUnion" + AdditionalPropertiesResponse: + type: object + properties: + dictionaryOfObjects: + $ref: "#/components/schemas/Dictionary" + dictionaryOfPrimitives: + type: object + additionalProperties: + type: string + Dictionary: + type: object + additionalProperties: + type: array + items: + $ref: "#/components/schemas/SomeObject" + SomeObject: + type: object + properties: + a: + type: string diff --git a/packages/type-safe-api/test/scripts/generators/__snapshots__/java.test.ts.snap b/packages/type-safe-api/test/scripts/generators/__snapshots__/java.test.ts.snap index 9b11037d2..9cdcbc318 100644 --- a/packages/type-safe-api/test/scripts/generators/__snapshots__/java.test.ts.snap +++ b/packages/type-safe-api/test/scripts/generators/__snapshots__/java.test.ts.snap @@ -30335,36 +30335,42 @@ src/main/java/test/test/runtime/api/handlers/InterceptorWarmupChainedRequestInpu src/main/java/test/test/runtime/api/handlers/InterceptorWithWarmup.java src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsResponse.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersResponse.java +src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryResponse.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumResponse.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyResponse.java src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfResponse.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsResponse.java src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfs200Response.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParameters200Response.java +src/main/java/test/test/runtime/api/handlers/dictionary/Dictionary200Response.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnum200Response.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody204Response.java src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOf200Response.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords200Response.java src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsRequestParameters.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersRequestParameters.java +src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryRequestParameters.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestParameters.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestParameters.java src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestParameters.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsRequestParameters.java src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsInput.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersInput.java +src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryInput.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumInput.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyInput.java src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfInput.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsInput.java src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfsRequestInput.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParametersRequestInput.java +src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryRequestInput.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestInput.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestInput.java src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestInput.java src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywordsRequestInput.java src/main/java/test/test/runtime/api/handlers/array_of_one_ofs/ArrayOfOneOfs.java src/main/java/test/test/runtime/api/handlers/array_request_parameters/ArrayRequestParameters.java +src/main/java/test/test/runtime/api/handlers/dictionary/Dictionary.java src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnum.java src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody.java src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOf.java @@ -30398,14 +30404,17 @@ src/main/java/test/test/runtime/ServerConfiguration.java src/main/java/test/test/runtime/ServerVariable.java src/main/java/test/test/runtime/StringUtil.java src/main/java/test/test/runtime/model/AbstractOpenApiSchema.java +src/main/java/test/test/runtime/model/AdditionalPropertiesResponse.java src/main/java/test/test/runtime/model/AnotherNamedOneOf.java src/main/java/test/test/runtime/model/ArrayOfOneOfs.java +src/main/java/test/test/runtime/model/Dictionary.java src/main/java/test/test/runtime/model/InlineEnum200Response.java src/main/java/test/test/runtime/model/InlineEnum200ResponseCategoryEnum.java src/main/java/test/test/runtime/model/InlineRequestBodyRequestContent.java src/main/java/test/test/runtime/model/MyEnum.java src/main/java/test/test/runtime/model/NamedOneOf.java -src/main/java/test/test/runtime/model/NamedOneOfUnion.java", +src/main/java/test/test/runtime/model/NamedOneOfUnion.java +src/main/java/test/test/runtime/model/SomeObject.java", "src/main/java/test/test/runtime/ApiCallback.java": "/* * Edge Cases * @@ -32472,12 +32481,15 @@ public class JSON { gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AdditionalPropertiesResponse.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.AnotherNamedOneOf.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.ArrayOfOneOfs.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.Dictionary.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.InlineEnum200Response.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.InlineRequestBodyRequestContent.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.NamedOneOf.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.NamedOneOfUnion.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new test.test.runtime.model.SomeObject.CustomTypeAdapterFactory()); gson = gsonBuilder.create(); } @@ -33178,6 +33190,7 @@ import java.io.IOException; import java.math.BigDecimal; import java.io.File; +import test.test.runtime.model.AdditionalPropertiesResponse; import test.test.runtime.model.ArrayOfOneOfs; import test.test.runtime.model.InlineEnum200Response; import test.test.runtime.model.InlineRequestBodyRequestContent; @@ -33648,6 +33661,151 @@ public class DefaultApi { public APIarrayRequestParametersRequest arrayRequestParameters() { return new APIarrayRequestParametersRequest(); } + private okhttp3.Call dictionaryCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/additional-properties"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + + @SuppressWarnings("rawtypes") + private okhttp3.Call dictionaryValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return dictionaryCall(_callback); + + } + + private ApiResponse dictionaryWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = dictionaryValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + + private okhttp3.Call dictionaryAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = dictionaryValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APIdictionaryRequest { + + private APIdictionaryRequest() { + } + + /** + * Build call for dictionary + * @param _callback ApiCallback API callback + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return dictionaryCall(_callback); + } + + /** + * Execute dictionary request + * @return AdditionalPropertiesResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public AdditionalPropertiesResponse execute() throws ApiException { + ApiResponse localVarResp = dictionaryWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Execute dictionary request with HTTP info returned + * @return ApiResponse<AdditionalPropertiesResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return dictionaryWithHttpInfo(); + } + + /** + * Execute dictionary request (asynchronously) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return dictionaryAsync(_callback); + } + } + + /** + * + * + * @return APIdictionaryRequest + * @http.response.details + + + +
Status Code Description Response Headers
200 ok -
+ */ + + public APIdictionaryRequest dictionary() { + return new APIdictionaryRequest(); + } private okhttp3.Call inlineEnumCall(final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers @@ -34325,6 +34483,7 @@ package test.test.runtime.api.handlers; import test.test.runtime.api.handlers.array_of_one_ofs.*; import test.test.runtime.api.handlers.array_request_parameters.*; +import test.test.runtime.api.handlers.dictionary.*; import test.test.runtime.api.handlers.inline_enum.*; import test.test.runtime.api.handlers.inline_request_body.*; import test.test.runtime.api.handlers.named_one_of.*; @@ -34348,6 +34507,7 @@ import java.util.Collections; public abstract class HandlerRouter implements RequestHandler { private static final String arrayOfOneOfsMethodAndPath = Handlers.concatMethodAndPath("POST", "/array-of-one-ofs"); private static final String arrayRequestParametersMethodAndPath = Handlers.concatMethodAndPath("GET", "/array-request-parameters"); + private static final String dictionaryMethodAndPath = Handlers.concatMethodAndPath("POST", "/additional-properties"); private static final String inlineEnumMethodAndPath = Handlers.concatMethodAndPath("GET", "/inline-enum"); private static final String inlineRequestBodyMethodAndPath = Handlers.concatMethodAndPath("POST", "/inline-request-body"); private static final String namedOneOfMethodAndPath = Handlers.concatMethodAndPath("POST", "/named-one-of"); @@ -34355,6 +34515,7 @@ public abstract class HandlerRouter implements RequestHandler> arrayRequestParametersInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); arrayRequestParametersInterceptors.addAll(this.getInterceptors()); return this.constructedArrayRequestParameters.handleRequestWithAdditionalInterceptors(event, context, arrayRequestParametersInterceptors); + case dictionaryRoute: + List> dictionaryInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); + dictionaryInterceptors.addAll(this.getInterceptors()); + return this.constructedDictionary.handleRequestWithAdditionalInterceptors(event, context, dictionaryInterceptors); case inlineEnumRoute: List> inlineEnumInterceptors = Handlers.getAnnotationInterceptors(this.getClass()); inlineEnumInterceptors.addAll(this.getInterceptors()); @@ -35976,8 +36148,8 @@ import test.test.runtime.api.handlers.Response; */ public interface ArrayRequestParametersResponse extends Response {} ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnum.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/dictionary/Dictionary.java": " +package test.test.runtime.api.handlers.dictionary; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -36001,50 +36173,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the inlineEnum operation + * Lambda handler wrapper for the dictionary operation */ -public abstract class InlineEnum implements RequestHandler, Resource { +public abstract class Dictionary implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the inlineEnum operation + * Handle the request for the dictionary operation */ - public abstract InlineEnumResponse handle(final InlineEnumRequestInput request); + public abstract DictionaryResponse handle(final DictionaryRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(InlineEnum.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(Dictionary.class); /** * For more complex interceptors that require instantiation with parameters, you may override this method to * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, * prefer the @Interceptors annotation. */ - public List> getInterceptors() { + public List> getInterceptors() { return Collections.emptyList(); } - private List> getHandlerInterceptors() { - List> interceptors = new ArrayList<>(); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); interceptors.addAll(annotationInterceptors); interceptors.addAll(this.getInterceptors()); return interceptors; } - private HandlerChain buildChain(List> interceptors) { - return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { @Override - public Response next(ChainedRequestInput input) { - return handle(new InlineEnumRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new DictionaryRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final InlineEnumInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final DictionaryInput input, final Map interceptorContext) { + return new ChainedRequestInput() { @Override public HandlerChain getChain() { // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining @@ -36063,7 +36235,7 @@ public abstract class InlineEnum implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -36124,20 +36296,20 @@ public abstract class InlineEnum implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "inlineEnum"); + interceptorContext.put("operationId", "dictionary"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - InlineEnumInput input; + DictionaryInput input; try { - input = new InlineEnumInput(event); + input = new DictionaryInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -36162,8 +36334,8 @@ public abstract class InlineEnum implements RequestHandler headers; private final Map> multiValueHeaders; - private InlineEnum200Response(final InlineEnum200Response body, final Map headers, final Map> multiValueHeaders) { + private Dictionary200Response(final AdditionalPropertiesResponse body, final Map headers, final Map> multiValueHeaders) { this.typedBody = body; this.body = body.toJson(); this.headers = headers; @@ -36205,7 +36377,7 @@ public class InlineEnum200Response extends RuntimeException implements InlineEnu return this.body; } - public InlineEnum200Response getTypedBody() { + public AdditionalPropertiesResponse getTypedBody() { return this.typedBody; } @@ -36220,29 +36392,29 @@ public class InlineEnum200Response extends RuntimeException implements InlineEnu } /** - * Create a InlineEnum200Response with a body + * Create a Dictionary200Response with a body */ - public static InlineEnum200Response of(final InlineEnum200Response body) { - return new InlineEnum200Response(body, new HashMap<>(), new HashMap<>()); + public static Dictionary200Response of(final AdditionalPropertiesResponse body) { + return new Dictionary200Response(body, new HashMap<>(), new HashMap<>()); } /** - * Create a InlineEnum200Response with a body and headers + * Create a Dictionary200Response with a body and headers */ - public static InlineEnum200Response of(final InlineEnum200Response body, final Map headers) { - return new InlineEnum200Response(body, headers, new HashMap<>()); + public static Dictionary200Response of(final AdditionalPropertiesResponse body, final Map headers) { + return new Dictionary200Response(body, headers, new HashMap<>()); } /** - * Create a InlineEnum200Response with a body, headers and multi-value headers + * Create a Dictionary200Response with a body, headers and multi-value headers */ - public static InlineEnum200Response of(final InlineEnum200Response body, final Map headers, final Map> multiValueHeaders) { - return new InlineEnum200Response(body, headers, multiValueHeaders); + public static Dictionary200Response of(final AdditionalPropertiesResponse body, final Map headers, final Map> multiValueHeaders) { + return new Dictionary200Response(body, headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumInput.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryInput.java": " +package test.test.runtime.api.handlers.dictionary; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -36255,11 +36427,11 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import java.io.IOException; /** - * Input for the inlineEnum operation + * Input for the dictionary operation */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineEnumInput { +public class DictionaryInput { static { // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. // Create an instance here if required to ensure that the static Gson instance is always available. @@ -36268,20 +36440,20 @@ public class InlineEnumInput { } } - private final InlineEnumRequestParameters requestParameters; + private final DictionaryRequestParameters requestParameters; - public InlineEnumInput(final APIGatewayProxyRequestEvent event) { - this.requestParameters = new InlineEnumRequestParameters(event); + public DictionaryInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new DictionaryRequestParameters(event); } - public InlineEnumRequestParameters getRequestParameters() { + public DictionaryRequestParameters getRequestParameters() { return this.requestParameters; } } ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestInput.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryRequestInput.java": " +package test.test.runtime.api.handlers.dictionary; import test.test.runtime.model.*; import test.test.runtime.api.handlers.RequestInput; @@ -36294,20 +36466,20 @@ import java.io.IOException; import com.amazonaws.services.lambda.runtime.Context; /** - * Full request input for the inlineEnum operation, including the raw API Gateway event + * Full request input for the dictionary operation, including the raw API Gateway event */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineEnumRequestInput implements RequestInput { +public class DictionaryRequestInput implements RequestInput { private final APIGatewayProxyRequestEvent event; private final Context context; private final Map interceptorContext; - private final InlineEnumInput input; + private final DictionaryInput input; /** * Returns the typed request input, with path, query and body parameters */ - public InlineEnumInput getInput() { + public DictionaryInput getInput() { return this.input; } @@ -36333,8 +36505,8 @@ public class InlineEnumRequestInput implements RequestInput { } } ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestParameters.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryRequestParameters.java": " +package test.test.runtime.api.handlers.dictionary; import test.test.runtime.api.handlers.Handlers; import java.util.Optional; @@ -36351,13 +36523,13 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import test.test.runtime.model.*; /** - * Query, path and header parameters for the InlineEnum operation + * Query, path and header parameters for the Dictionary operation */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineEnumRequestParameters { +public class DictionaryRequestParameters { - public InlineEnumRequestParameters(final APIGatewayProxyRequestEvent event) { + public DictionaryRequestParameters(final APIGatewayProxyRequestEvent event) { Map rawStringParameters = new HashMap<>(); Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); @@ -36373,18 +36545,18 @@ public class InlineEnumRequestParameters { } ", - "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumResponse.java": " -package test.test.runtime.api.handlers.inline_enum; + "src/main/java/test/test/runtime/api/handlers/dictionary/DictionaryResponse.java": " +package test.test.runtime.api.handlers.dictionary; import test.test.runtime.api.handlers.Response; /** - * Response for the inlineEnum operation + * Response for the dictionary operation */ -public interface InlineEnumResponse extends Response {} +public interface DictionaryResponse extends Response {} ", - "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody.java": " -package test.test.runtime.api.handlers.inline_request_body; + "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnum.java": " +package test.test.runtime.api.handlers.inline_enum; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -36408,50 +36580,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the inlineRequestBody operation + * Lambda handler wrapper for the inlineEnum operation */ -public abstract class InlineRequestBody implements RequestHandler, Resource { +public abstract class InlineEnum implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the inlineRequestBody operation + * Handle the request for the inlineEnum operation */ - public abstract InlineRequestBodyResponse handle(final InlineRequestBodyRequestInput request); + public abstract InlineEnumResponse handle(final InlineEnumRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(InlineRequestBody.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(InlineEnum.class); /** * For more complex interceptors that require instantiation with parameters, you may override this method to * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, * prefer the @Interceptors annotation. */ - public List> getInterceptors() { + public List> getInterceptors() { return Collections.emptyList(); } - private List> getHandlerInterceptors() { - List> interceptors = new ArrayList<>(); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); interceptors.addAll(annotationInterceptors); interceptors.addAll(this.getInterceptors()); return interceptors; } - private HandlerChain buildChain(List> interceptors) { - return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { @Override - public Response next(ChainedRequestInput input) { - return handle(new InlineRequestBodyRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new InlineEnumRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final InlineRequestBodyInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final InlineEnumInput input, final Map interceptorContext) { + return new ChainedRequestInput() { @Override public HandlerChain getChain() { // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining @@ -36470,7 +36642,7 @@ public abstract class InlineRequestBody implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -36531,20 +36703,20 @@ public abstract class InlineRequestBody implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "inlineRequestBody"); + interceptorContext.put("operationId", "inlineEnum"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - InlineRequestBodyInput input; + InlineEnumInput input; try { - input = new InlineRequestBodyInput(event); + input = new InlineEnumInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -36569,8 +36741,8 @@ public abstract class InlineRequestBody implements RequestHandler headers; private final Map> multiValueHeaders; - private InlineRequestBody204Response(final Map headers, final Map> multiValueHeaders) { - - this.body = ""; + private InlineEnum200Response(final InlineEnum200Response body, final Map headers, final Map> multiValueHeaders) { + this.typedBody = body; + this.body = body.toJson(); this.headers = headers; this.multiValueHeaders = multiValueHeaders; } @Override public int getStatusCode() { - return 204; + return 200; } @Override @@ -36612,6 +36784,9 @@ public class InlineRequestBody204Response extends RuntimeException implements In return this.body; } + public InlineEnum200Response getTypedBody() { + return this.typedBody; + } @Override public Map getHeaders() { @@ -36624,29 +36799,29 @@ public class InlineRequestBody204Response extends RuntimeException implements In } /** - * Create a InlineRequestBody204Response without a body + * Create a InlineEnum200Response with a body */ - public static InlineRequestBody204Response of() { - return new InlineRequestBody204Response(new HashMap<>(), new HashMap<>()); + public static InlineEnum200Response of(final InlineEnum200Response body) { + return new InlineEnum200Response(body, new HashMap<>(), new HashMap<>()); } /** - * Create a InlineRequestBody204Response without a body and headers + * Create a InlineEnum200Response with a body and headers */ - public static InlineRequestBody204Response of(final Map headers) { - return new InlineRequestBody204Response(headers, new HashMap<>()); + public static InlineEnum200Response of(final InlineEnum200Response body, final Map headers) { + return new InlineEnum200Response(body, headers, new HashMap<>()); } /** - * Create a InlineRequestBody204Response without a body, headers and multi-value headers + * Create a InlineEnum200Response with a body, headers and multi-value headers */ - public static InlineRequestBody204Response of(final Map headers, final Map> multiValueHeaders) { - return new InlineRequestBody204Response(headers, multiValueHeaders); + public static InlineEnum200Response of(final InlineEnum200Response body, final Map headers, final Map> multiValueHeaders) { + return new InlineEnum200Response(body, headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyInput.java": " -package test.test.runtime.api.handlers.inline_request_body; + "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumInput.java": " +package test.test.runtime.api.handlers.inline_enum; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -36659,11 +36834,11 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import java.io.IOException; /** - * Input for the inlineRequestBody operation + * Input for the inlineEnum operation */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineRequestBodyInput { +public class InlineEnumInput { static { // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. // Create an instance here if required to ensure that the static Gson instance is always available. @@ -36672,29 +36847,20 @@ public class InlineRequestBodyInput { } } - private final InlineRequestBodyRequestParameters requestParameters; - private final InlineRequestBodyRequestContent body; + private final InlineEnumRequestParameters requestParameters; - public InlineRequestBodyInput(final APIGatewayProxyRequestEvent event) { - this.requestParameters = new InlineRequestBodyRequestParameters(event); - try { - this.body = InlineRequestBodyRequestContent.fromJson(event.getBody()); - } catch (IOException e) { - throw new RuntimeException(e); - }; + public InlineEnumInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new InlineEnumRequestParameters(event); } - public InlineRequestBodyRequestParameters getRequestParameters() { + public InlineEnumRequestParameters getRequestParameters() { return this.requestParameters; } - public InlineRequestBodyRequestContent getBody() { - return this.body; - } } ", - "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestInput.java": " -package test.test.runtime.api.handlers.inline_request_body; + "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumRequestInput.java": " +package test.test.runtime.api.handlers.inline_enum; import test.test.runtime.model.*; import test.test.runtime.api.handlers.RequestInput; @@ -36707,20 +36873,20 @@ import java.io.IOException; import com.amazonaws.services.lambda.runtime.Context; /** - * Full request input for the inlineRequestBody operation, including the raw API Gateway event + * Full request input for the inlineEnum operation, including the raw API Gateway event */ @lombok.Builder @lombok.AllArgsConstructor -public class InlineRequestBodyRequestInput implements RequestInput { +public class InlineEnumRequestInput implements RequestInput { private final APIGatewayProxyRequestEvent event; private final Context context; private final Map interceptorContext; - private final InlineRequestBodyInput input; + private final InlineEnumInput input; /** * Returns the typed request input, with path, query and body parameters */ - public InlineRequestBodyInput getInput() { + public InlineEnumInput getInput() { return this.input; } @@ -36746,8 +36912,8 @@ public class InlineRequestBodyRequestInput implements RequestInput rawStringParameters = new HashMap<>(); Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); @@ -36786,18 +36952,18 @@ public class InlineRequestBodyRequestParameters { } ", - "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyResponse.java": " -package test.test.runtime.api.handlers.inline_request_body; + "src/main/java/test/test/runtime/api/handlers/inline_enum/InlineEnumResponse.java": " +package test.test.runtime.api.handlers.inline_enum; import test.test.runtime.api.handlers.Response; /** - * Response for the inlineRequestBody operation + * Response for the inlineEnum operation */ -public interface InlineRequestBodyResponse extends Response {} +public interface InlineEnumResponse extends Response {} ", - "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOf.java": " -package test.test.runtime.api.handlers.named_one_of; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBody.java": " +package test.test.runtime.api.handlers.inline_request_body; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -36821,50 +36987,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the namedOneOf operation + * Lambda handler wrapper for the inlineRequestBody operation */ -public abstract class NamedOneOf implements RequestHandler, Resource { +public abstract class InlineRequestBody implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the namedOneOf operation + * Handle the request for the inlineRequestBody operation */ - public abstract NamedOneOfResponse handle(final NamedOneOfRequestInput request); + public abstract InlineRequestBodyResponse handle(final InlineRequestBodyRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(NamedOneOf.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(InlineRequestBody.class); /** * For more complex interceptors that require instantiation with parameters, you may override this method to * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, * prefer the @Interceptors annotation. */ - public List> getInterceptors() { + public List> getInterceptors() { return Collections.emptyList(); } - private List> getHandlerInterceptors() { - List> interceptors = new ArrayList<>(); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); interceptors.addAll(annotationInterceptors); interceptors.addAll(this.getInterceptors()); return interceptors; } - private HandlerChain buildChain(List> interceptors) { - return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { @Override - public Response next(ChainedRequestInput input) { - return handle(new NamedOneOfRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new InlineRequestBodyRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final NamedOneOfInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final InlineRequestBodyInput input, final Map interceptorContext) { + return new ChainedRequestInput() { @Override public HandlerChain getChain() { // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining @@ -36883,7 +37049,7 @@ public abstract class NamedOneOf implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -36944,20 +37110,20 @@ public abstract class NamedOneOf implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "namedOneOf"); + interceptorContext.put("operationId", "inlineRequestBody"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - NamedOneOfInput input; + InlineRequestBodyInput input; try { - input = new NamedOneOfInput(event); + input = new InlineRequestBodyInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -36982,8 +37148,8 @@ public abstract class NamedOneOf implements RequestHandler headers; private final Map> multiValueHeaders; - private NamedOneOf200Response(final NamedOneOfUnion body, final Map headers, final Map> multiValueHeaders) { - this.typedBody = body; - this.body = body.toJson(); + private InlineRequestBody204Response(final Map headers, final Map> multiValueHeaders) { + + this.body = ""; this.headers = headers; this.multiValueHeaders = multiValueHeaders; } @Override public int getStatusCode() { - return 200; + return 204; } @Override @@ -37025,9 +37191,6 @@ public class NamedOneOf200Response extends RuntimeException implements NamedOneO return this.body; } - public NamedOneOfUnion getTypedBody() { - return this.typedBody; - } @Override public Map getHeaders() { @@ -37040,29 +37203,29 @@ public class NamedOneOf200Response extends RuntimeException implements NamedOneO } /** - * Create a NamedOneOf200Response with a body + * Create a InlineRequestBody204Response without a body */ - public static NamedOneOf200Response of(final NamedOneOfUnion body) { - return new NamedOneOf200Response(body, new HashMap<>(), new HashMap<>()); + public static InlineRequestBody204Response of() { + return new InlineRequestBody204Response(new HashMap<>(), new HashMap<>()); } /** - * Create a NamedOneOf200Response with a body and headers + * Create a InlineRequestBody204Response without a body and headers */ - public static NamedOneOf200Response of(final NamedOneOfUnion body, final Map headers) { - return new NamedOneOf200Response(body, headers, new HashMap<>()); + public static InlineRequestBody204Response of(final Map headers) { + return new InlineRequestBody204Response(headers, new HashMap<>()); } /** - * Create a NamedOneOf200Response with a body, headers and multi-value headers + * Create a InlineRequestBody204Response without a body, headers and multi-value headers */ - public static NamedOneOf200Response of(final NamedOneOfUnion body, final Map headers, final Map> multiValueHeaders) { - return new NamedOneOf200Response(body, headers, multiValueHeaders); + public static InlineRequestBody204Response of(final Map headers, final Map> multiValueHeaders) { + return new InlineRequestBody204Response(headers, multiValueHeaders); } } ", - "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfInput.java": " -package test.test.runtime.api.handlers.named_one_of; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyInput.java": " +package test.test.runtime.api.handlers.inline_request_body; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -37075,11 +37238,11 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import java.io.IOException; /** - * Input for the namedOneOf operation + * Input for the inlineRequestBody operation */ @lombok.Builder @lombok.AllArgsConstructor -public class NamedOneOfInput { +public class InlineRequestBodyInput { static { // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. // Create an instance here if required to ensure that the static Gson instance is always available. @@ -37088,20 +37251,29 @@ public class NamedOneOfInput { } } - private final NamedOneOfRequestParameters requestParameters; + private final InlineRequestBodyRequestParameters requestParameters; + private final InlineRequestBodyRequestContent body; - public NamedOneOfInput(final APIGatewayProxyRequestEvent event) { - this.requestParameters = new NamedOneOfRequestParameters(event); + public InlineRequestBodyInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new InlineRequestBodyRequestParameters(event); + try { + this.body = InlineRequestBodyRequestContent.fromJson(event.getBody()); + } catch (IOException e) { + throw new RuntimeException(e); + }; } - public NamedOneOfRequestParameters getRequestParameters() { + public InlineRequestBodyRequestParameters getRequestParameters() { return this.requestParameters; } + public InlineRequestBodyRequestContent getBody() { + return this.body; + } } ", - "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestInput.java": " -package test.test.runtime.api.handlers.named_one_of; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestInput.java": " +package test.test.runtime.api.handlers.inline_request_body; import test.test.runtime.model.*; import test.test.runtime.api.handlers.RequestInput; @@ -37114,20 +37286,20 @@ import java.io.IOException; import com.amazonaws.services.lambda.runtime.Context; /** - * Full request input for the namedOneOf operation, including the raw API Gateway event + * Full request input for the inlineRequestBody operation, including the raw API Gateway event */ @lombok.Builder @lombok.AllArgsConstructor -public class NamedOneOfRequestInput implements RequestInput { +public class InlineRequestBodyRequestInput implements RequestInput { private final APIGatewayProxyRequestEvent event; private final Context context; private final Map interceptorContext; - private final NamedOneOfInput input; + private final InlineRequestBodyInput input; /** * Returns the typed request input, with path, query and body parameters */ - public NamedOneOfInput getInput() { + public InlineRequestBodyInput getInput() { return this.input; } @@ -37153,8 +37325,8 @@ public class NamedOneOfRequestInput implements RequestInput { } } ", - "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestParameters.java": " -package test.test.runtime.api.handlers.named_one_of; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyRequestParameters.java": " +package test.test.runtime.api.handlers.inline_request_body; import test.test.runtime.api.handlers.Handlers; import java.util.Optional; @@ -37171,13 +37343,13 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import test.test.runtime.model.*; /** - * Query, path and header parameters for the NamedOneOf operation + * Query, path and header parameters for the InlineRequestBody operation */ @lombok.Builder @lombok.AllArgsConstructor -public class NamedOneOfRequestParameters { +public class InlineRequestBodyRequestParameters { - public NamedOneOfRequestParameters(final APIGatewayProxyRequestEvent event) { + public InlineRequestBodyRequestParameters(final APIGatewayProxyRequestEvent event) { Map rawStringParameters = new HashMap<>(); Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); @@ -37193,18 +37365,18 @@ public class NamedOneOfRequestParameters { } ", - "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfResponse.java": " -package test.test.runtime.api.handlers.named_one_of; + "src/main/java/test/test/runtime/api/handlers/inline_request_body/InlineRequestBodyResponse.java": " +package test.test.runtime.api.handlers.inline_request_body; import test.test.runtime.api.handlers.Response; /** - * Response for the namedOneOf operation + * Response for the inlineRequestBody operation */ -public interface NamedOneOfResponse extends Response {} +public interface InlineRequestBodyResponse extends Response {} ", - "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords.java": " -package test.test.runtime.api.handlers.reserved_keywords; + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOf.java": " +package test.test.runtime.api.handlers.named_one_of; import test.test.runtime.model.*; import test.test.runtime.JSON; @@ -37228,50 +37400,50 @@ import org.crac.Resource; /** - * Lambda handler wrapper for the reservedKeywords operation + * Lambda handler wrapper for the namedOneOf operation */ -public abstract class ReservedKeywords implements RequestHandler, Resource { +public abstract class NamedOneOf implements RequestHandler, Resource { { Core.getGlobalContext().register(this); } /** - * Handle the request for the reservedKeywords operation + * Handle the request for the namedOneOf operation */ - public abstract ReservedKeywordsResponse handle(final ReservedKeywordsRequestInput request); + public abstract NamedOneOfResponse handle(final NamedOneOfRequestInput request); /** * Interceptors that the handler class has been decorated with */ - private List> annotationInterceptors = Handlers.getAnnotationInterceptors(ReservedKeywords.class); + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(NamedOneOf.class); /** * For more complex interceptors that require instantiation with parameters, you may override this method to * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, * prefer the @Interceptors annotation. */ - public List> getInterceptors() { + public List> getInterceptors() { return Collections.emptyList(); } - private List> getHandlerInterceptors() { - List> interceptors = new ArrayList<>(); + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); interceptors.addAll(annotationInterceptors); interceptors.addAll(this.getInterceptors()); return interceptors; } - private HandlerChain buildChain(List> interceptors) { - return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { @Override - public Response next(ChainedRequestInput input) { - return handle(new ReservedKeywordsRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + public Response next(ChainedRequestInput input) { + return handle(new NamedOneOfRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); } }); } - private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final ReservedKeywordsInput input, final Map interceptorContext) { - return new ChainedRequestInput() { + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final NamedOneOfInput input, final Map interceptorContext) { + return new ChainedRequestInput() { @Override public HandlerChain getChain() { // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining @@ -37290,7 +37462,7 @@ public abstract class ReservedKeywords implements RequestHandler()) .withQueryStringParameters(new HashMap<>()) @@ -37351,20 +37523,20 @@ public abstract class ReservedKeywords implements RequestHandler> additionalInterceptors) { + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { final Map interceptorContext = new HashMap<>(); - interceptorContext.put("operationId", "reservedKeywords"); + interceptorContext.put("operationId", "namedOneOf"); - List> interceptors = new ArrayList<>(); + List> interceptors = new ArrayList<>(); interceptors.addAll(additionalInterceptors); interceptors.addAll(this.getHandlerInterceptors()); final HandlerChain chain = this.buildChain(interceptors); - ReservedKeywordsInput input; + NamedOneOfInput input; try { - input = new ReservedKeywordsInput(event); + input = new NamedOneOfInput(event); } catch (RuntimeException e) { Map headers = new HashMap<>(); headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); @@ -37389,8 +37561,8 @@ public abstract class ReservedKeywords implements RequestHandler headers; + private final Map> multiValueHeaders; + + private NamedOneOf200Response(final NamedOneOfUnion body, final Map headers, final Map> multiValueHeaders) { + this.typedBody = body; + this.body = body.toJson(); + this.headers = headers; + this.multiValueHeaders = multiValueHeaders; + } + + @Override + public int getStatusCode() { + return 200; + } + + @Override + public String getBody() { + return this.body; + } + + public NamedOneOfUnion getTypedBody() { + return this.typedBody; + } + + @Override + public Map getHeaders() { + return this.headers; + } + + @Override + public Map> getMultiValueHeaders() { + return this.multiValueHeaders; + } + + /** + * Create a NamedOneOf200Response with a body + */ + public static NamedOneOf200Response of(final NamedOneOfUnion body) { + return new NamedOneOf200Response(body, new HashMap<>(), new HashMap<>()); + } + + /** + * Create a NamedOneOf200Response with a body and headers + */ + public static NamedOneOf200Response of(final NamedOneOfUnion body, final Map headers) { + return new NamedOneOf200Response(body, headers, new HashMap<>()); + } + + /** + * Create a NamedOneOf200Response with a body, headers and multi-value headers + */ + public static NamedOneOf200Response of(final NamedOneOfUnion body, final Map headers, final Map> multiValueHeaders) { + return new NamedOneOf200Response(body, headers, multiValueHeaders); + } +} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfInput.java": " +package test.test.runtime.api.handlers.named_one_of; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import java.util.List; +import java.util.ArrayList; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import java.io.IOException; + +/** + * Input for the namedOneOf operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class NamedOneOfInput { + static { + // JSON has a static instance of Gson which is instantiated lazily the first time it is initialised. + // Create an instance here if required to ensure that the static Gson instance is always available. + if (JSON.getGson() == null) { + new JSON(); + } + } + + private final NamedOneOfRequestParameters requestParameters; + + public NamedOneOfInput(final APIGatewayProxyRequestEvent event) { + this.requestParameters = new NamedOneOfRequestParameters(event); + } + + public NamedOneOfRequestParameters getRequestParameters() { + return this.requestParameters; + } + +} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestInput.java": " +package test.test.runtime.api.handlers.named_one_of; + +import test.test.runtime.model.*; +import test.test.runtime.api.handlers.RequestInput; +import java.util.List; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import java.io.IOException; +import com.amazonaws.services.lambda.runtime.Context; + +/** + * Full request input for the namedOneOf operation, including the raw API Gateway event + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class NamedOneOfRequestInput implements RequestInput { + private final APIGatewayProxyRequestEvent event; + private final Context context; + private final Map interceptorContext; + private final NamedOneOfInput input; + + /** + * Returns the typed request input, with path, query and body parameters + */ + public NamedOneOfInput getInput() { + return this.input; + } + + /** + * Returns the raw API Gateway event + */ + public APIGatewayProxyRequestEvent getEvent() { + return this.event; + } + + /** + * Returns the lambda context + */ + public Context getContext() { + return this.context; + } + + /** + * Returns the interceptor context, which may contain values set by request interceptors + */ + public Map getInterceptorContext() { + return this.interceptorContext; + } +} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfRequestParameters.java": " +package test.test.runtime.api.handlers.named_one_of; + +import test.test.runtime.api.handlers.Handlers; +import java.util.Optional; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.time.OffsetDateTime; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.stream.Collectors; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; + +import test.test.runtime.model.*; + +/** + * Query, path and header parameters for the NamedOneOf operation + */ +@lombok.Builder +@lombok.AllArgsConstructor +public class NamedOneOfRequestParameters { + + public NamedOneOfRequestParameters(final APIGatewayProxyRequestEvent event) { + Map rawStringParameters = new HashMap<>(); + Handlers.putAllFromNullableMap(event.getPathParameters(), rawStringParameters); + Handlers.putAllFromNullableMap(event.getQueryStringParameters(), rawStringParameters); + Handlers.putAllFromNullableMap(event.getHeaders(), rawStringParameters); + Map decodedStringParameters = Handlers.decodeRequestParameters(rawStringParameters); + + Map> rawStringArrayParameters = new HashMap<>(); + Handlers.putAllFromNullableMap(event.getMultiValueQueryStringParameters(), rawStringArrayParameters); + Handlers.putAllFromNullableMap(event.getMultiValueHeaders(), rawStringArrayParameters); + Map> decodedStringArrayParameters = Handlers.decodeRequestArrayParameters(rawStringArrayParameters); + + } + +} +", + "src/main/java/test/test/runtime/api/handlers/named_one_of/NamedOneOfResponse.java": " +package test.test.runtime.api.handlers.named_one_of; + +import test.test.runtime.api.handlers.Response; + +/** + * Response for the namedOneOf operation + */ +public interface NamedOneOfResponse extends Response {} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import test.test.runtime.api.handlers.Interceptor; +import test.test.runtime.api.handlers.Handlers; +import test.test.runtime.api.handlers.*; + +import java.util.List; +import java.util.ArrayList; +import java.util.Optional; +import java.util.Map; +import java.util.HashMap; +import java.util.Collections; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; +import java.io.IOException; +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import org.crac.Core; +import org.crac.Resource; + + +/** + * Lambda handler wrapper for the reservedKeywords operation + */ +public abstract class ReservedKeywords implements RequestHandler, Resource { + { + Core.getGlobalContext().register(this); + } + + /** + * Handle the request for the reservedKeywords operation + */ + public abstract ReservedKeywordsResponse handle(final ReservedKeywordsRequestInput request); + + /** + * Interceptors that the handler class has been decorated with + */ + private List> annotationInterceptors = Handlers.getAnnotationInterceptors(ReservedKeywords.class); + + /** + * For more complex interceptors that require instantiation with parameters, you may override this method to + * return a list of instantiated interceptors. For simple interceptors with no need for constructor arguments, + * prefer the @Interceptors annotation. + */ + public List> getInterceptors() { + return Collections.emptyList(); + } + + private List> getHandlerInterceptors() { + List> interceptors = new ArrayList<>(); + interceptors.addAll(annotationInterceptors); + interceptors.addAll(this.getInterceptors()); + return interceptors; + } + + private HandlerChain buildChain(List> interceptors) { + return Handlers.buildHandlerChain(interceptors, new HandlerChain() { + @Override + public Response next(ChainedRequestInput input) { + return handle(new ReservedKeywordsRequestInput(input.getEvent(), input.getContext(), input.getInterceptorContext(), input.getInput())); + } + }); + } + + private ChainedRequestInput buildChainedRequestInput(final APIGatewayProxyRequestEvent event, final Context context, final ReservedKeywordsInput input, final Map interceptorContext) { + return new ChainedRequestInput() { + @Override + public HandlerChain getChain() { + // The chain's next method ignores the chain given as input, and is pre-built to follow the remaining + // chain. + return null; + } + + @Override + public APIGatewayProxyRequestEvent getEvent() { + return event; + } + + @Override + public Context getContext() { + return context; + } + + @Override + public ReservedKeywordsInput getInput() { + return input; + } + + @Override + public Map getInterceptorContext() { + return interceptorContext; + } + }; + } + + @Override + public void beforeCheckpoint(org.crac.Context context) { + // Prime building the handler chain which can take a few 100ms to JIT. + this.buildChain(this.getHandlerInterceptors()); + this.buildChainedRequestInput(null, null, null, null); + + // Initialise instance of Gson and prime serialisation and deserialisation + new JSON(); + JSON.getGson().fromJson(JSON.getGson().toJson(new ApiResponse("", 0, new HashMap<>(), new HashMap<>())), ApiResponse.class); + + try { + // Prime input validation - this will likely fail for the fake event but ensures the code path is optimised + // ready for a real invocation + new ReservedKeywordsInput(new APIGatewayProxyRequestEvent() + .withBody("{}") + .withPathParameters(new HashMap<>()) + .withQueryStringParameters(new HashMap<>()) + .withMultiValueQueryStringParameters(new HashMap<>()) + .withHeaders(new HashMap<>()) + .withMultiValueHeaders(new HashMap<>()) + ); + } catch (Exception e) { + + } + + this.warmUp(); + } + + @Override + public void afterRestore(org.crac.Context context) { + + } + + /** + * Override this method to perform any warmup activities which will be executed prior to the snap-start snapshot. + */ + public void warmUp() { + + } + + @Override + public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent event, final Context context) { + return this.handleRequestWithAdditionalInterceptors(event, context, new ArrayList<>()); + } + + private Map getErrorResponseHeaders(final int statusCode) { + Map headers = new HashMap<>(); + return headers; + } + + public APIGatewayProxyResponseEvent handleRequestWithAdditionalInterceptors(final APIGatewayProxyRequestEvent event, final Context context, final List> additionalInterceptors) { + final Map interceptorContext = new HashMap<>(); + interceptorContext.put("operationId", "reservedKeywords"); + + List> interceptors = new ArrayList<>(); + interceptors.addAll(additionalInterceptors); + interceptors.addAll(this.getHandlerInterceptors()); + + final HandlerChain chain = this.buildChain(interceptors); + + ReservedKeywordsInput input; + + try { + input = new ReservedKeywordsInput(event); + } catch (RuntimeException e) { + Map headers = new HashMap<>(); + headers.putAll(Handlers.extractResponseHeadersFromInterceptors(interceptors)); + headers.putAll(this.getErrorResponseHeaders(400)); + return new APIGatewayProxyResponseEvent() + .withStatusCode(400) + .withHeaders(headers) + .withBody("{\\"message\\": \\"" + e.getMessage() + "\\"}"); + } + + final Response response = chain.next(this.buildChainedRequestInput(event, context, input, interceptorContext)); + + Map responseHeaders = new HashMap<>(); + responseHeaders.putAll(this.getErrorResponseHeaders(response.getStatusCode())); + responseHeaders.putAll(response.getHeaders()); + + return new APIGatewayProxyResponseEvent() + .withStatusCode(response.getStatusCode()) + .withHeaders(responseHeaders) + .withMultiValueHeaders(response.getMultiValueHeaders()) + .withBody(response.getBody()); + } +} +", + "src/main/java/test/test/runtime/api/handlers/reserved_keywords/ReservedKeywords200Response.java": " +package test.test.runtime.api.handlers.reserved_keywords; + +import test.test.runtime.model.*; +import test.test.runtime.JSON; +import java.util.Map; +import java.util.HashMap; +import java.util.List; + +/** + * Response with status code 200 for the reservedKeywords operation */ public class ReservedKeywords200Response extends RuntimeException implements ReservedKeywordsResponse { static { @@ -37975,6 +38554,7 @@ import java.util.Map; public class OperationConfig { private T arrayOfOneOfs; private T arrayRequestParameters; + private T dictionary; private T inlineEnum; private T inlineRequestBody; private T namedOneOf; @@ -37984,6 +38564,7 @@ public class OperationConfig { Map map = new HashMap<>(); map.put("arrayOfOneOfs", this.arrayOfOneOfs); map.put("arrayRequestParameters", this.arrayRequestParameters); + map.put("dictionary", this.dictionary); map.put("inlineEnum", this.inlineEnum); map.put("inlineRequestBody", this.inlineRequestBody); map.put("namedOneOf", this.namedOneOf); @@ -38027,6 +38608,11 @@ public class OperationLookup { .method("GET") .contentTypes(Arrays.asList("application/json")) .build()); + config.put("dictionary", OperationLookupEntry.builder() + .path("/additional-properties") + .method("POST") + .contentTypes(Arrays.asList("application/json")) + .build()); config.put("inlineEnum", OperationLookupEntry.builder() .path("/inline-enum") .method("GET") @@ -38064,6 +38650,7 @@ public class Operations { return OperationConfig.builder() .arrayOfOneOfs(value) .arrayRequestParameters(value) + .dictionary(value) .inlineEnum(value) .inlineRequestBody(value) .namedOneOf(value) @@ -38409,50 +38996,315 @@ public abstract class AbstractOpenApiSchema { return sb.toString(); } - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\\n", "\\n "); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; + return Objects.equals(this.instance, a.instance) && + Objects.equals(this.isNullable, a.isNullable) && + Objects.equals(this.schemaType, a.schemaType); + } + + @Override + public int hashCode() { + return Objects.hash(instance, isNullable, schemaType); + } + + /** + * Is nullable + * + * @return true if it's nullable + */ + public Boolean isNullable() { + if (Boolean.TRUE.equals(isNullable)) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + + +} +", + "src/main/java/test/test/runtime/model/AdditionalPropertiesResponse.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; +import test.test.runtime.model.Dictionary; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; +import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.List; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import test.test.runtime.JSON; + +/** + * AdditionalPropertiesResponse + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public class AdditionalPropertiesResponse { + public static final String SERIALIZED_NAME_DICTIONARY_OF_OBJECTS = "dictionaryOfObjects"; + @SerializedName(SERIALIZED_NAME_DICTIONARY_OF_OBJECTS) + private Dictionary dictionaryOfObjects; + + public static final String SERIALIZED_NAME_DICTIONARY_OF_PRIMITIVES = "dictionaryOfPrimitives"; + @SerializedName(SERIALIZED_NAME_DICTIONARY_OF_PRIMITIVES) + private Map dictionaryOfPrimitives = null; + + public AdditionalPropertiesResponse() { + } + + public AdditionalPropertiesResponse dictionaryOfObjects(Dictionary dictionaryOfObjects) { + + this.dictionaryOfObjects = dictionaryOfObjects; + return this; + } + + /** + * Get dictionaryOfObjects + * @return dictionaryOfObjects + **/ + @javax.annotation.Nullable + public Dictionary getDictionaryOfObjects() { + return dictionaryOfObjects; + } + + + public void setDictionaryOfObjects(Dictionary dictionaryOfObjects) { + this.dictionaryOfObjects = dictionaryOfObjects; + } + + public AdditionalPropertiesResponse dictionaryOfPrimitives(Map dictionaryOfPrimitives) { + + this.dictionaryOfPrimitives = dictionaryOfPrimitives; + return this; + } + + public AdditionalPropertiesResponse putDictionaryOfPrimitivesItem(String key, String dictionaryOfPrimitivesItem) { + if (this.dictionaryOfPrimitives == null) { + this.dictionaryOfPrimitives = new HashMap<>(); + } + this.dictionaryOfPrimitives.put(key, dictionaryOfPrimitivesItem); + return this; + } + + /** + * Get dictionaryOfPrimitives + * @return dictionaryOfPrimitives + **/ + @javax.annotation.Nullable + public Map getDictionaryOfPrimitives() { + return dictionaryOfPrimitives; + } + + + public void setDictionaryOfPrimitives(Map dictionaryOfPrimitives) { + this.dictionaryOfPrimitives = dictionaryOfPrimitives; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesResponse additionalPropertiesResponse = (AdditionalPropertiesResponse) o; + return Objects.equals(this.dictionaryOfObjects, additionalPropertiesResponse.dictionaryOfObjects) && + Objects.equals(this.dictionaryOfPrimitives, additionalPropertiesResponse.dictionaryOfPrimitives); + + } + + @Override + public int hashCode() { + return Objects.hash(dictionaryOfObjects, dictionaryOfPrimitives); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesResponse {\\n"); + sb.append(" dictionaryOfObjects: ").append(toIndentedString(dictionaryOfObjects)).append("\\n"); + sb.append(" dictionaryOfPrimitives: ").append(toIndentedString(dictionaryOfPrimitives)).append("\\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\\n", "\\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("dictionaryOfObjects"); + openapiFields.add("dictionaryOfPrimitives"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to AdditionalPropertiesResponse + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!AdditionalPropertiesResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesResponse is not found in the empty JSON string", AdditionalPropertiesResponse.openapiRequiredFields.toString())); } - return o.toString().replace("\\n", "\\n "); - } + } - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!AdditionalPropertiesResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`AdditionalPropertiesResponse\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } - AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; - return Objects.equals(this.instance, a.instance) && - Objects.equals(this.isNullable, a.isNullable) && - Objects.equals(this.schemaType, a.schemaType); - } + } + // validate the optional field \`dictionaryOfObjects\` + if (jsonObj.get("dictionaryOfObjects") != null && !jsonObj.get("dictionaryOfObjects").isJsonNull()) { + Dictionary.validateJsonObject(jsonObj.getAsJsonObject("dictionaryOfObjects")); + } + if ((jsonObj.get("dictionaryOfPrimitives") != null && !jsonObj.get("dictionaryOfPrimitives").isJsonNull()) && !jsonObj.get("dictionaryOfPrimitives").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`dictionaryOfPrimitives\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("dictionaryOfPrimitives").toString())); + } + } + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") @Override - public int hashCode() { - return Objects.hash(instance, isNullable, schemaType); - } + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AdditionalPropertiesResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AdditionalPropertiesResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AdditionalPropertiesResponse.class)); - /** - * Is nullable - * - * @return true if it's nullable - */ - public Boolean isNullable() { - if (Boolean.TRUE.equals(isNullable)) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AdditionalPropertiesResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public AdditionalPropertiesResponse read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + }.nullSafe(); + } + } + /** + * Create an instance of AdditionalPropertiesResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of AdditionalPropertiesResponse + * @throws IOException if the JSON string is invalid with respect to AdditionalPropertiesResponse + */ + public static AdditionalPropertiesResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AdditionalPropertiesResponse.class); + } + /** + * Convert an instance of AdditionalPropertiesResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } } ", "src/main/java/test/test/runtime/model/AnotherNamedOneOf.java": "/* @@ -38783,8 +39635,210 @@ public class ArrayOfOneOfs { } - public void setOneOfs(List oneOfs) { - this.oneOfs = oneOfs; + public void setOneOfs(List oneOfs) { + this.oneOfs = oneOfs; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfOneOfs arrayOfOneOfs = (ArrayOfOneOfs) o; + return Objects.equals(this.oneOfs, arrayOfOneOfs.oneOfs); + + } + + @Override + public int hashCode() { + return Objects.hash(oneOfs); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfOneOfs {\\n"); + sb.append(" oneOfs: ").append(toIndentedString(oneOfs)).append("\\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\\n", "\\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("oneOfs"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to ArrayOfOneOfs + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!ArrayOfOneOfs.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfOneOfs is not found in the empty JSON string", ArrayOfOneOfs.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!ArrayOfOneOfs.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`ArrayOfOneOfs\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + // ensure the optional json data is an array if present + if (jsonObj.get("oneOfs") != null && !jsonObj.get("oneOfs").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field \`oneOfs\` to be an array in the JSON string but got \`%s\`", jsonObj.get("oneOfs").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayOfOneOfs.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayOfOneOfs' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayOfOneOfs.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayOfOneOfs value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ArrayOfOneOfs read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ArrayOfOneOfs given an JSON string + * + * @param jsonString JSON string + * @return An instance of ArrayOfOneOfs + * @throws IOException if the JSON string is invalid with respect to ArrayOfOneOfs + */ + public static ArrayOfOneOfs fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ArrayOfOneOfs.class); + } + + /** + * Convert an instance of ArrayOfOneOfs to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} +", + "src/main/java/test/test/runtime/model/Dictionary.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; +import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.List; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import test.test.runtime.JSON; + +/** + * Dictionary + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public class Dictionary { + public Dictionary() { } @@ -38796,21 +39850,19 @@ public class ArrayOfOneOfs { if (o == null || getClass() != o.getClass()) { return false; } - ArrayOfOneOfs arrayOfOneOfs = (ArrayOfOneOfs) o; - return Objects.equals(this.oneOfs, arrayOfOneOfs.oneOfs); - + Dictionary dictionary = (Dictionary) o; + return } @Override public int hashCode() { - return Objects.hash(oneOfs); + return Objects.hash(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class ArrayOfOneOfs {\\n"); - sb.append(" oneOfs: ").append(toIndentedString(oneOfs)).append("\\n"); + sb.append("class Dictionary {\\n"); sb.append("}"); return sb.toString(); } @@ -38833,7 +39885,6 @@ public class ArrayOfOneOfs { static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet(); - openapiFields.add("oneOfs"); // a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet(); @@ -38843,48 +39894,44 @@ public class ArrayOfOneOfs { * Validates the JSON Object and throws an exception if issues found * * @param jsonObj JSON Object - * @throws IOException if the JSON Object is invalid with respect to ArrayOfOneOfs + * @throws IOException if the JSON Object is invalid with respect to Dictionary */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (!ArrayOfOneOfs.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null - throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfOneOfs is not found in the empty JSON string", ArrayOfOneOfs.openapiRequiredFields.toString())); + if (!Dictionary.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in Dictionary is not found in the empty JSON string", Dictionary.openapiRequiredFields.toString())); } } Set> entries = jsonObj.entrySet(); // check to see if the JSON string contains additional fields for (Entry entry : entries) { - if (!ArrayOfOneOfs.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`ArrayOfOneOfs\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + if (!Dictionary.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`Dictionary\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - // ensure the optional json data is an array if present - if (jsonObj.get("oneOfs") != null && !jsonObj.get("oneOfs").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field \`oneOfs\` to be an array in the JSON string but got \`%s\`", jsonObj.get("oneOfs").toString())); - } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { - if (!ArrayOfOneOfs.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ArrayOfOneOfs' and its subtypes + if (!Dictionary.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Dictionary' and its subtypes } final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(ArrayOfOneOfs.class)); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Dictionary.class)); - return (TypeAdapter) new TypeAdapter() { + return (TypeAdapter) new TypeAdapter() { @Override - public void write(JsonWriter out, ArrayOfOneOfs value) throws IOException { + public void write(JsonWriter out, Dictionary value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); elementAdapter.write(out, obj); } @Override - public ArrayOfOneOfs read(JsonReader in) throws IOException { + public Dictionary read(JsonReader in) throws IOException { JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); validateJsonObject(jsonObj); return thisAdapter.fromJsonTree(jsonObj); @@ -38895,18 +39942,18 @@ public class ArrayOfOneOfs { } /** - * Create an instance of ArrayOfOneOfs given an JSON string + * Create an instance of Dictionary given an JSON string * * @param jsonString JSON string - * @return An instance of ArrayOfOneOfs - * @throws IOException if the JSON string is invalid with respect to ArrayOfOneOfs + * @return An instance of Dictionary + * @throws IOException if the JSON string is invalid with respect to Dictionary */ - public static ArrayOfOneOfs fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ArrayOfOneOfs.class); + public static Dictionary fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Dictionary.class); } /** - * Convert an instance of ArrayOfOneOfs to an JSON string + * Convert an instance of Dictionary to an JSON string * * @return JSON string */ @@ -40123,6 +41170,231 @@ public class NamedOneOfUnion extends AbstractOpenApiSchema { } } +", + "src/main/java/test/test/runtime/model/SomeObject.java": "/* + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ + + +package test.test.runtime.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.io.File; +import java.math.BigDecimal; +import java.net.URI; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.List; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import test.test.runtime.JSON; + +/** + * SomeObject + */ +@lombok.AllArgsConstructor @lombok.experimental.SuperBuilder +public class SomeObject { + public static final String SERIALIZED_NAME_A = "a"; + @SerializedName(SERIALIZED_NAME_A) + private String a; + + public SomeObject() { + } + + public SomeObject a(String a) { + + this.a = a; + return this; + } + + /** + * Get a + * @return a + **/ + @javax.annotation.Nullable + public String getA() { + return a; + } + + + public void setA(String a) { + this.a = a; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SomeObject someObject = (SomeObject) o; + return Objects.equals(this.a, someObject.a); + + } + + @Override + public int hashCode() { + return Objects.hash(a); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SomeObject {\\n"); + sb.append(" a: ").append(toIndentedString(a)).append("\\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\\n", "\\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("a"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to SomeObject + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!SomeObject.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in SomeObject is not found in the empty JSON string", SomeObject.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonObj.entrySet(); + // check to see if the JSON string contains additional fields + for (Entry entry : entries) { + if (!SomeObject.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field \`%s\` in the JSON string is not defined in the \`SomeObject\` properties. JSON: %s", entry.getKey(), jsonObj.toString())); + } + } + if ((jsonObj.get("a") != null && !jsonObj.get("a").isJsonNull()) && !jsonObj.get("a").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field \`a\` to be a primitive type in the JSON string but got \`%s\`", jsonObj.get("a").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!SomeObject.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'SomeObject' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(SomeObject.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, SomeObject value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public SomeObject read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + return thisAdapter.fromJsonTree(jsonObj); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of SomeObject given an JSON string + * + * @param jsonString JSON string + * @return An instance of SomeObject + * @throws IOException if the JSON string is invalid with respect to SomeObject + */ + public static SomeObject fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, SomeObject.class); + } + + /** + * Convert an instance of SomeObject to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} ", } `; diff --git a/packages/type-safe-api/test/scripts/generators/__snapshots__/python.test.ts.snap b/packages/type-safe-api/test/scripts/generators/__snapshots__/python.test.ts.snap index 09861e8a1..09e6756cc 100644 --- a/packages/type-safe-api/test/scripts/generators/__snapshots__/python.test.ts.snap +++ b/packages/type-safe-api/test/scripts/generators/__snapshots__/python.test.ts.snap @@ -17428,14 +17428,17 @@ test_project/__init__.py test_project/py.typed test_project/rest.py docs/DefaultApi.md +docs/AdditionalPropertiesResponse.md docs/AnotherNamedOneOf.md docs/ArrayOfOneOfs.md +docs/Dictionary.md docs/InlineEnum200Response.md docs/InlineEnum200ResponseCategoryEnum.md docs/InlineRequestBodyRequestContent.md docs/MyEnum.md docs/NamedOneOf.md docs/NamedOneOfUnion.md +docs/SomeObject.md README.md test_project/interceptors/try_catch.py test_project/interceptors/response_headers.py @@ -17448,14 +17451,17 @@ test_project/response.py test_project/api/default_api.py test_project/api/__init__.py test_project/models/__init__.py +test_project/models/additional_properties_response.py test_project/models/another_named_one_of.py test_project/models/array_of_one_ofs.py +test_project/models/dictionary.py test_project/models/inline_enum200_response.py test_project/models/inline_enum200_response_category_enum.py test_project/models/inline_request_body_request_content.py test_project/models/my_enum.py test_project/models/named_one_of.py -test_project/models/named_one_of_union.py", +test_project/models/named_one_of_union.py +test_project/models/some_object.py", "README.md": "# Edge Cases @@ -17502,6 +17508,7 @@ Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *DefaultApi* | [**array_of_one_ofs**](docs/DefaultApi.md#array_of_one_ofs) | **POST** /array-of-one-ofs | *DefaultApi* | [**array_request_parameters**](docs/DefaultApi.md#array_request_parameters) | **GET** /array-request-parameters | +*DefaultApi* | [**dictionary**](docs/DefaultApi.md#dictionary) | **POST** /additional-properties | *DefaultApi* | [**inline_enum**](docs/DefaultApi.md#inline_enum) | **GET** /inline-enum | *DefaultApi* | [**inline_request_body**](docs/DefaultApi.md#inline_request_body) | **POST** /inline-request-body | *DefaultApi* | [**named_one_of**](docs/DefaultApi.md#named_one_of) | **POST** /named-one-of | @@ -17509,14 +17516,45 @@ Class | Method | HTTP request | Description ## Documentation For Models + - [AdditionalPropertiesResponse](docs/AdditionalPropertiesResponse.md) - [AnotherNamedOneOf](docs/AnotherNamedOneOf.md) - [ArrayOfOneOfs](docs/ArrayOfOneOfs.md) + - [Dictionary](docs/Dictionary.md) - [InlineEnum200Response](docs/InlineEnum200Response.md) - [InlineEnum200ResponseCategoryEnum](docs/InlineEnum200ResponseCategoryEnum.md) - [InlineRequestBodyRequestContent](docs/InlineRequestBodyRequestContent.md) - [MyEnum](docs/MyEnum.md) - [NamedOneOf](docs/NamedOneOf.md) - [NamedOneOfUnion](docs/NamedOneOfUnion.md) + - [SomeObject](docs/SomeObject.md) +", + "docs/AdditionalPropertiesResponse.md": "# AdditionalPropertiesResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**dictionary_of_objects** | [**Dictionary**](Dictionary.md) | | [optional] +**dictionary_of_primitives** | **Dict[str, str]** | | [optional] + +## Example + +\`\`\`python +from test_project.models.additional_properties_response import AdditionalPropertiesResponse + +# TODO update the JSON string below +json = "{}" +# create an instance of AdditionalPropertiesResponse from a JSON string +additional_properties_response_instance = AdditionalPropertiesResponse.from_json(json) +# print the JSON string representation of the object +print(AdditionalPropertiesResponse.to_json()) + +# convert the object into a dict +additional_properties_response_dict = additional_properties_response_instance.to_dict() +# create an instance of AdditionalPropertiesResponse from a dict +additional_properties_response_form_dict = additional_properties_response.from_dict(additional_properties_response_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + ", "docs/AnotherNamedOneOf.md": "# AnotherNamedOneOf @@ -17578,6 +17616,7 @@ Method | HTTP request | Description ------------- | ------------- | ------------- [**array_of_one_ofs**](DefaultApi.md#array_of_one_ofs) | **POST** /array-of-one-ofs | [**array_request_parameters**](DefaultApi.md#array_request_parameters) | **GET** /array-request-parameters | +[**dictionary**](DefaultApi.md#dictionary) | **POST** /additional-properties | [**inline_enum**](DefaultApi.md#inline_enum) | **GET** /inline-enum | [**inline_request_body**](DefaultApi.md#inline_request_body) | **POST** /inline-request-body | [**named_one_of**](DefaultApi.md#named_one_of) | **POST** /named-one-of | @@ -17700,6 +17739,56 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **dictionary** +> AdditionalPropertiesResponse dictionary() + + +### Example + +\`\`\`python +import time +import test_project +from test_project.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = test_project.Configuration( + host = "http://localhost" +) + +# Enter a context with an instance of the API client +with test_project.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = test_project.DefaultApi(api_client) + + try: + api_response = api_instance.dictionary() + print("The response of DefaultApi->dictionary:\\n") + pprint(api_response) + except ApiException as e: + print("Exception when calling DefaultApi->dictionary: %s\\n" % e) +\`\`\` + +### Parameters +This endpoint does not need any parameters. + +### Return type + +[**AdditionalPropertiesResponse**](AdditionalPropertiesResponse.md) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **inline_enum** > InlineEnum200Response inline_enum() @@ -17906,6 +17995,32 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +", + "docs/Dictionary.md": "# Dictionary + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +\`\`\`python +from test_project.models.dictionary import Dictionary + +# TODO update the JSON string below +json = "{}" +# create an instance of Dictionary from a JSON string +dictionary_instance = Dictionary.from_json(json) +# print the JSON string representation of the object +print(Dictionary.to_json()) + +# convert the object into a dict +dictionary_dict = dictionary_instance.to_dict() +# create an instance of Dictionary from a dict +dictionary_form_dict = dictionary.from_dict(dictionary_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + ", "docs/InlineEnum200Response.md": "# InlineEnum200Response @@ -18036,6 +18151,33 @@ named_one_of_union_form_dict = named_one_of_union.from_dict(named_one_of_union_d \`\`\` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) +", + "docs/SomeObject.md": "# SomeObject + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**a** | **str** | | [optional] + +## Example + +\`\`\`python +from test_project.models.some_object import SomeObject + +# TODO update the JSON string below +json = "{}" +# create an instance of SomeObject from a JSON string +some_object_instance = SomeObject.from_json(json) +# print the JSON string representation of the object +print(SomeObject.to_json()) + +# convert the object into a dict +some_object_dict = some_object_instance.to_dict() +# create an instance of SomeObject from a dict +some_object_form_dict = some_object.from_dict(some_object_dict) +\`\`\` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + ", "poetry.toml": "# ~~ Generated by projen. To modify, edit .projenrc.py and run "npx projen". @@ -18105,14 +18247,17 @@ from test_project.exceptions import ApiAttributeError from test_project.exceptions import ApiException # import models into sdk package +from test_project.models.additional_properties_response import AdditionalPropertiesResponse from test_project.models.another_named_one_of import AnotherNamedOneOf from test_project.models.array_of_one_ofs import ArrayOfOneOfs +from test_project.models.dictionary import Dictionary from test_project.models.inline_enum200_response import InlineEnum200Response from test_project.models.inline_enum200_response_category_enum import InlineEnum200ResponseCategoryEnum from test_project.models.inline_request_body_request_content import InlineRequestBodyRequestContent from test_project.models.my_enum import MyEnum from test_project.models.named_one_of import NamedOneOf from test_project.models.named_one_of_union import NamedOneOfUnion +from test_project.models.some_object import SomeObject ", "test_project/api/__init__.py": "# flake8: noqa @@ -18143,6 +18288,7 @@ try: except ImportError: from typing_extensions import Annotated +from test_project.models.additional_properties_response import AdditionalPropertiesResponse from test_project.models.array_of_one_ofs import ArrayOfOneOfs from test_project.models.inline_enum200_response import InlineEnum200Response from test_project.models.inline_request_body_request_content import InlineRequestBodyRequestContent @@ -18769,6 +18915,241 @@ class DefaultApi: + @validate_call + def dictionary( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> AdditionalPropertiesResponse: + """dictionary + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._dictionary_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AdditionalPropertiesResponse" + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def dictionary_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[AdditionalPropertiesResponse]: + """dictionary + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._dictionary_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AdditionalPropertiesResponse" + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def dictionary_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """dictionary + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._dictionary_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AdditionalPropertiesResponse" + } + + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _dictionary_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header \`Accept\` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/additional-properties', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def inline_enum( self, @@ -19783,6 +20164,7 @@ T = TypeVar('T') class OperationConfig(Generic[T]): array_of_one_ofs: T array_request_parameters: T + dictionary: T inline_enum: T inline_request_body: T named_one_of: T @@ -19801,6 +20183,11 @@ OperationLookup = { "method": "GET", "contentTypes": ["application/json"] }, + "dictionary": { + "path": "/additional-properties", + "method": "POST", + "contentTypes": ["application/json"] + }, "inline_enum": { "path": "/inline-enum", "method": "GET", @@ -20199,7 +20586,122 @@ def array_request_parameters_handler(_handler: ArrayRequestParametersHandlerFunc body = {} interceptor_context = { - "operationId": "array_request_parameters", + "operationId": "array_request_parameters", + } + + chain = _build_handler_chain(all_interceptors, handler) + response = chain.next(ApiRequest( + request_parameters, + body, + event, + context, + interceptor_context, + ), **kwargs) + + response_headers = {** (response.headers or {}), **response_headers_for_status_code(response.status_code)} + response_body = '' + if response.body is None: + pass + elif response.status_code == 200: + response_body = response.body + + return { + 'statusCode': response.status_code, + 'headers': response_headers, + 'multiValueHeaders': response.multi_value_headers or {}, + 'body': response_body, + } + return wrapper + + # Support use as a decorator with no arguments, or with interceptor arguments + if callable(_handler): + return _handler_wrapper(_handler) + elif _handler is None: + return _handler_wrapper + else: + raise Exception("Positional arguments are not supported by array_request_parameters_handler.") + +class DictionaryRequestParameters(BaseModel): + """ + Query, path and header parameters for the Dictionary operation + """ + + class Config: + """Pydantic configuration""" + populate_by_name = True + validate_assignment = True + + def to_json(self) -> str: + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> DictionaryRequestParameters: + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + return self.model_dump(exclude={}, exclude_none=True) + + @classmethod + def from_dict(cls, obj: dict) -> DictionaryRequestParameters: + if obj is None: + return None + return DictionaryRequestParameters.model_validate(obj) + + +# Request body type (default to Any when no body parameters exist, or leave unchanged as str if it's a primitive type) +DictionaryRequestBody = Any + +Dictionary200OperationResponse = ApiResponse[Literal[200], AdditionalPropertiesResponse] + +DictionaryOperationResponses = Union[Dictionary200OperationResponse, ] + +# Request type for dictionary +DictionaryRequest = ApiRequest[DictionaryRequestParameters, DictionaryRequestBody] +DictionaryChainedRequest = ChainedApiRequest[DictionaryRequestParameters, DictionaryRequestBody] + +class DictionaryHandlerFunction(Protocol): + def __call__(self, input: DictionaryRequest, **kwargs) -> DictionaryOperationResponses: + ... + +DictionaryInterceptor = Callable[[DictionaryChainedRequest], DictionaryOperationResponses] + +def dictionary_handler(_handler: DictionaryHandlerFunction = None, interceptors: List[DictionaryInterceptor] = []): + """ + Decorator for an api handler for the dictionary operation, providing a typed interface for inputs and outputs + """ + def _handler_wrapper(handler: DictionaryHandlerFunction): + @wraps(handler) + def wrapper(event, context, additional_interceptors = [], **kwargs): + all_interceptors = additional_interceptors + interceptors + + raw_string_parameters = decode_request_parameters({ + **(event.get('pathParameters', {}) or {}), + **(event.get('queryStringParameters', {}) or {}), + **(event.get('headers', {}) or {}), + }) + raw_string_array_parameters = decode_request_parameters({ + **(event.get('multiValueQueryStringParameters', {}) or {}), + **(event.get('multiValueHeaders', {}) or {}), + }) + + def response_headers_for_status_code(status_code): + headers_for_status = {} + return headers_for_status + + request_parameters = None + try: + request_parameters = DictionaryRequestParameters.from_dict({ + }) + except Exception as e: + return { + 'statusCode': 400, + 'headers': {**response_headers_for_status_code(400), **extract_response_headers_from_interceptors(all_interceptors)}, + 'body': '{"message": "' + str(e) + '"}', + } + + body = {} + interceptor_context = { + "operationId": "dictionary", } chain = _build_handler_chain(all_interceptors, handler) @@ -20216,7 +20718,7 @@ def array_request_parameters_handler(_handler: ArrayRequestParametersHandlerFunc if response.body is None: pass elif response.status_code == 200: - response_body = response.body + response_body = response.body.to_json() return { 'statusCode': response.status_code, @@ -20232,7 +20734,7 @@ def array_request_parameters_handler(_handler: ArrayRequestParametersHandlerFunc elif _handler is None: return _handler_wrapper else: - raise Exception("Positional arguments are not supported by array_request_parameters_handler.") + raise Exception("Positional arguments are not supported by dictionary_handler.") class InlineEnumRequestParameters(BaseModel): """ @@ -20712,6 +21214,7 @@ OperationIdByMethodAndPath = { concat_method_and_path(method_and_path["method"], class HandlerRouterHandlers: array_of_one_ofs: Callable[[Dict, Any], Dict] array_request_parameters: Callable[[Dict, Any], Dict] + dictionary: Callable[[Dict, Any], Dict] inline_enum: Callable[[Dict, Any], Dict] inline_request_body: Callable[[Dict, Any], Dict] named_one_of: Callable[[Dict, Any], Dict] @@ -22284,14 +22787,112 @@ def try_catch_interceptor(request: ChainedApiRequest) -> ApiResponse: """ # noqa: E501 # import models into model package +from test_project.models.additional_properties_response import AdditionalPropertiesResponse from test_project.models.another_named_one_of import AnotherNamedOneOf from test_project.models.array_of_one_ofs import ArrayOfOneOfs +from test_project.models.dictionary import Dictionary from test_project.models.inline_enum200_response import InlineEnum200Response from test_project.models.inline_enum200_response_category_enum import InlineEnum200ResponseCategoryEnum from test_project.models.inline_request_body_request_content import InlineRequestBodyRequestContent from test_project.models.my_enum import MyEnum from test_project.models.named_one_of import NamedOneOf from test_project.models.named_one_of_union import NamedOneOfUnion +from test_project.models.some_object import SomeObject +", + "test_project/models/additional_properties_response.py": "# coding: utf-8 + +""" + Edge Cases + + No description provided + + The version of the OpenAPI document: 1.0.0 + + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +from test_project.models.dictionary import Dictionary +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class AdditionalPropertiesResponse(BaseModel): + """ + AdditionalPropertiesResponse + """ # noqa: E501 + dictionary_of_objects: Optional[Dictionary] = Field(default=None, alias="dictionaryOfObjects") + dictionary_of_primitives: Optional[Dict[str, StrictStr]] = Field(default=None, alias="dictionaryOfPrimitives") + __properties: ClassVar[List[str]] = ["dictionaryOfObjects", "dictionaryOfPrimitives"] + + + model_config = { + "populate_by_name": True, + "validate_assignment": True + } + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AdditionalPropertiesResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + \`self.model_dump(by_alias=True)\`: + + * \`None\` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value \`None\` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling \`to_dict()\` of dictionary_of_objects + if self.dictionary_of_objects: + _dict['dictionaryOfObjects'] = self.dictionary_of_objects.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of AdditionalPropertiesResponse from a dict""" + + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "dictionaryOfObjects": Dictionary.from_dict(obj.get("dictionaryOfObjects")) if obj.get("dictionaryOfObjects") is not None else None, + "dictionaryOfPrimitives": obj.get("dictionaryOfPrimitives") + }) + return _obj + ", "test_project/models/another_named_one_of.py": "# coding: utf-8 @@ -22474,6 +23075,106 @@ class ArrayOfOneOfs(BaseModel): }) return _obj +", + "test_project/models/dictionary.py": "# coding: utf-8 + +""" + Edge Cases + + No description provided + + The version of the OpenAPI document: 1.0.0 + + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class Dictionary(BaseModel): + """ + Dictionary + """ # noqa: E501 + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = [] + + + model_config = { + "populate_by_name": True, + "validate_assignment": True + } + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Dictionary from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + \`self.model_dump(by_alias=True)\`: + + * \`None\` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value \`None\` + are ignored. + * Fields in \`self.additional_properties\` are added to the output dict. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + "additional_properties", + }, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Dictionary from a dict""" + + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + ", "test_project/models/inline_enum200_response.py": "# coding: utf-8 @@ -22982,6 +23683,95 @@ class NamedOneOfUnion(BaseModel): """Returns the string representation of the actual instance""" return pprint.pformat(self.model_dump()) +", + "test_project/models/some_object.py": "# coding: utf-8 + +""" + Edge Cases + + No description provided + + The version of the OpenAPI document: 1.0.0 + + NOTE: This class is auto generated. + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from enum import Enum +from datetime import date, datetime +from typing import Any, List, Union, ClassVar, Dict, Optional, TYPE_CHECKING +from pydantic import Field, StrictStr, ValidationError, field_validator, BaseModel, SecretStr, StrictFloat, StrictInt, StrictBytes, StrictBool +from decimal import Decimal +from typing_extensions import Annotated, Literal +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class SomeObject(BaseModel): + """ + SomeObject + """ # noqa: E501 + a: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["a"] + + + model_config = { + "populate_by_name": True, + "validate_assignment": True + } + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of SomeObject from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + \`self.model_dump(by_alias=True)\`: + + * \`None\` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value \`None\` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of SomeObject from a dict""" + + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "a": obj.get("a") + }) + return _obj + ", "test_project/py.typed": "", "test_project/response.py": "from typing import TypeVar, Generic, Dict, List diff --git a/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript.test.ts.snap b/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript.test.ts.snap index d08e86eb8..a9e4306ae 100644 --- a/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript.test.ts.snap +++ b/packages/type-safe-api/test/scripts/generators/__snapshots__/typescript.test.ts.snap @@ -8237,14 +8237,17 @@ src/apis/DefaultApi.ts src/apis/index.ts src/models/index.ts src/models/model-utils.ts +src/models/AdditionalPropertiesResponse.ts src/models/AnotherNamedOneOf.ts src/models/ArrayOfOneOfs.ts +src/models/Dictionary.ts src/models/InlineEnum200Response.ts src/models/InlineEnum200ResponseCategoryEnum.ts src/models/InlineRequestBodyRequestContent.ts src/models/MyEnum.ts src/models/NamedOneOf.ts -src/models/NamedOneOfUnion.ts", +src/models/NamedOneOfUnion.ts +src/models/SomeObject.ts", "src/apis/DefaultApi.ts": "/* tslint:disable */ /* eslint-disable */ /** @@ -8260,6 +8263,7 @@ src/models/NamedOneOfUnion.ts", import * as runtime from '../runtime'; import type { + AdditionalPropertiesResponse, ArrayOfOneOfs, InlineEnum200Response, InlineRequestBodyRequestContent, @@ -8267,6 +8271,8 @@ import type { NamedOneOfUnion, } from '../models'; import { + AdditionalPropertiesResponseFromJSON, + AdditionalPropertiesResponseToJSON, ArrayOfOneOfsFromJSON, ArrayOfOneOfsToJSON, InlineEnum200ResponseFromJSON, @@ -8293,6 +8299,7 @@ export interface ArrayRequestParametersRequest { } + export interface InlineRequestBodyRequest { inlineRequestBodyRequestContent?: InlineRequestBodyRequestContent; } @@ -8401,6 +8408,35 @@ export class DefaultApi extends runtime.BaseAPI { await this.arrayRequestParametersRaw(requestParameters, initOverrides); } + /** + * + */ + async dictionaryRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + + const headerParameters: runtime.HTTPHeaders = {}; + + + + const response = await this.request({ + path: \`/additional-properties\`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => AdditionalPropertiesResponseFromJSON(jsonValue)); + } + + /** + * + */ + async dictionary(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.dictionaryRaw(initOverrides); + return await response.value(); + } + /** * */ @@ -8534,12 +8570,18 @@ export class DefaultApi extends runtime.BaseAPI { ", "src/apis/DefaultApi/OperationConfig.ts": "// Import models import { + AdditionalPropertiesResponse, + AdditionalPropertiesResponseFromJSON, + AdditionalPropertiesResponseToJSON, AnotherNamedOneOf, AnotherNamedOneOfFromJSON, AnotherNamedOneOfToJSON, ArrayOfOneOfs, ArrayOfOneOfsFromJSON, ArrayOfOneOfsToJSON, + Dictionary, + DictionaryFromJSON, + DictionaryToJSON, InlineEnum200Response, InlineEnum200ResponseFromJSON, InlineEnum200ResponseToJSON, @@ -8558,6 +8600,9 @@ import { NamedOneOfUnion, NamedOneOfUnionFromJSON, NamedOneOfUnionToJSON, + SomeObject, + SomeObjectFromJSON, + SomeObjectToJSON, } from '../../models'; // Import request parameter interfaces import { @@ -8573,6 +8618,7 @@ import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from "aws-lambda export interface OperationConfig { arrayOfOneOfs: T; arrayRequestParameters: T; + dictionary: T; inlineEnum: T; inlineRequestBody: T; namedOneOf: T; @@ -8591,6 +8637,11 @@ export const OperationLookup = { method: 'GET', contentTypes: ['application/json'], }, + dictionary: { + path: '/additional-properties', + method: 'POST', + contentTypes: ['application/json'], + }, inlineEnum: { path: '/inline-enum', method: 'GET', @@ -8727,7 +8778,7 @@ const extractResponseHeadersFromInterceptors = (interceptors: any[]): { [key: st }), {} as { [key: string]: string }); }; -export type OperationIds = | 'arrayOfOneOfs' | 'arrayRequestParameters' | 'inlineEnum' | 'inlineRequestBody' | 'namedOneOf' | 'reservedKeywords'; +export type OperationIds = | 'arrayOfOneOfs' | 'arrayRequestParameters' | 'dictionary' | 'inlineEnum' | 'inlineRequestBody' | 'namedOneOf' | 'reservedKeywords'; export type OperationApiGatewayProxyResult = APIGatewayProxyResult & { __operationId?: T }; // Api gateway lambda handler type @@ -9038,6 +9089,115 @@ export const arrayRequestParametersHandler = ( body: response.body ? marshal(response.statusCode, response.body) : '', }; }; +/** + * Path, Query and Header parameters for Dictionary + */ +export interface DictionaryRequestParameters { +} + +/** + * Request body parameter for Dictionary + */ +export type DictionaryRequestBody = never; + +export type Dictionary200OperationResponse = OperationResponse<200, AdditionalPropertiesResponse>; + +export type DictionaryOperationResponses = | Dictionary200OperationResponse ; + +// Type that the handler function provided to the wrapper must conform to +export type DictionaryHandlerFunction = LambdaHandlerFunction; +export type DictionaryChainedHandlerFunction = ChainedLambdaHandlerFunction; +export type DictionaryChainedRequestInput = ChainedRequestInput; + +/** + * Lambda handler wrapper to provide typed interface for the implementation of dictionary + */ +export const dictionaryHandler = ( + ...handlers: [DictionaryChainedHandlerFunction, ...DictionaryChainedHandlerFunction[]] +): OperationApiGatewayLambdaHandler<'dictionary'> => async (event: any, context: any, _callback?: any, additionalInterceptors: DictionaryChainedHandlerFunction[] = []): Promise => { + const operationId = "dictionary"; + + const rawSingleValueParameters = decodeRequestParameters({ + ...(event.pathParameters || {}), + ...(event.queryStringParameters || {}), + ...(event.headers || {}), + }) as { [key: string]: string | undefined }; + const rawMultiValueParameters = decodeRequestParameters({ + ...(event.multiValueQueryStringParameters || {}), + ...(event.multiValueHeaders || {}), + }) as { [key: string]: string[] | undefined }; + + const marshal = (statusCode: number, responseBody: any): string => { + let marshalledBody = responseBody; + switch(statusCode) { + case 200: + marshalledBody = JSON.stringify(AdditionalPropertiesResponseToJSON(marshalledBody)); + break; + default: + break; + } + + return marshalledBody; + }; + + const errorHeaders = (statusCode: number): { [key: string]: string } => { + let headers = {}; + + switch(statusCode) { + default: + break; + } + + return headers; + }; + + let requestParameters: DictionaryRequestParameters | undefined = undefined; + + try { + requestParameters = { + + }; + } catch (e: any) { + const res = { + statusCode: 400, + body: { message: e.message }, + headers: extractResponseHeadersFromInterceptors(handlers), + }; + return { + ...res, + headers: { + ...errorHeaders(res.statusCode), + ...res.headers, + }, + body: res.body ? marshal(res.statusCode, res.body) : '', + }; + } + + const demarshal = (bodyString: string): any => { + return {}; + }; + const body = parseBody(event.body, demarshal, ['application/json']) as DictionaryRequestBody; + + const chain = buildHandlerChain(...additionalInterceptors, ...handlers); + const response = await chain.next({ + input: { + requestParameters, + body, + }, + event, + context, + interceptorContext: { operationId }, + }); + + return { + ...response, + headers: { + ...errorHeaders(response.statusCode), + ...response.headers, + }, + body: response.body ? marshal(response.statusCode, response.body) : '', + }; +}; /** * Path, Query and Header parameters for InlineEnum */ @@ -9482,15 +9642,16 @@ export const reservedKeywordsHandler = ( export interface HandlerRouterHandlers { readonly arrayOfOneOfs: OperationApiGatewayLambdaHandler<'arrayOfOneOfs'>; readonly arrayRequestParameters: OperationApiGatewayLambdaHandler<'arrayRequestParameters'>; + readonly dictionary: OperationApiGatewayLambdaHandler<'dictionary'>; readonly inlineEnum: OperationApiGatewayLambdaHandler<'inlineEnum'>; readonly inlineRequestBody: OperationApiGatewayLambdaHandler<'inlineRequestBody'>; readonly namedOneOf: OperationApiGatewayLambdaHandler<'namedOneOf'>; readonly reservedKeywords: OperationApiGatewayLambdaHandler<'reservedKeywords'>; } -export type AnyOperationRequestParameters = | ArrayOfOneOfsRequestParameters| ArrayRequestParametersRequestParameters| InlineEnumRequestParameters| InlineRequestBodyRequestParameters| NamedOneOfRequestParameters| ReservedKeywordsRequestParameters; -export type AnyOperationRequestBodies = | ArrayOfOneOfsRequestBody| ArrayRequestParametersRequestBody| InlineEnumRequestBody| InlineRequestBodyRequestBody| NamedOneOfRequestBody| ReservedKeywordsRequestBody; -export type AnyOperationResponses = | ArrayOfOneOfsOperationResponses| ArrayRequestParametersOperationResponses| InlineEnumOperationResponses| InlineRequestBodyOperationResponses| NamedOneOfOperationResponses| ReservedKeywordsOperationResponses; +export type AnyOperationRequestParameters = | ArrayOfOneOfsRequestParameters| ArrayRequestParametersRequestParameters| DictionaryRequestParameters| InlineEnumRequestParameters| InlineRequestBodyRequestParameters| NamedOneOfRequestParameters| ReservedKeywordsRequestParameters; +export type AnyOperationRequestBodies = | ArrayOfOneOfsRequestBody| ArrayRequestParametersRequestBody| DictionaryRequestBody| InlineEnumRequestBody| InlineRequestBodyRequestBody| NamedOneOfRequestBody| ReservedKeywordsRequestBody; +export type AnyOperationResponses = | ArrayOfOneOfsOperationResponses| ArrayRequestParametersOperationResponses| DictionaryOperationResponses| InlineEnumOperationResponses| InlineRequestBodyOperationResponses| NamedOneOfOperationResponses| ReservedKeywordsOperationResponses; export interface HandlerRouterProps< RequestParameters, @@ -9834,6 +9995,86 @@ export const buildTryCatchInterceptor = ; +} + + +/** + * Check if a given object implements the Dictionary interface. + */ +export function instanceOfDictionary(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function DictionaryFromJSON(json: any): Dictionary { + return DictionaryFromJSONTyped(json, false); +} + +export function DictionaryFromJSONTyped(json: any, ignoreDiscriminator: boolean): Dictionary { + return json; +} + +export function DictionaryToJSON(value?: Dictionary | null): any { + return value; +} + ", "src/models/InlineEnum200Response.ts": "/* tslint:disable */ /* eslint-disable */ @@ -10323,17 +10616,85 @@ export function NamedOneOfUnionToJSON(value?: NamedOneOfUnion | null): any { }; } +", + "src/models/SomeObject.ts": "/* tslint:disable */ +/* eslint-disable */ +/** + * Edge Cases + * + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated. + * Do not edit the class manually. + */ +import { exists, mapValues } from './model-utils'; + +/** + * + * @export + * @interface SomeObject + */ +export interface SomeObject { + /** + * + * @type {string} + * @memberof SomeObject + */ + a?: string; +} + + +/** + * Check if a given object implements the SomeObject interface. + */ +export function instanceOfSomeObject(value: object): boolean { + let isInstance = true; + return isInstance; +} + +export function SomeObjectFromJSON(json: any): SomeObject { + return SomeObjectFromJSONTyped(json, false); +} + +export function SomeObjectFromJSONTyped(json: any, ignoreDiscriminator: boolean): SomeObject { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'a': !exists(json, 'a') ? undefined : json['a'], + }; +} + +export function SomeObjectToJSON(value?: SomeObject | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'a': value.a, + }; +} + ", "src/models/index.ts": "/* tslint:disable */ /* eslint-disable */ +export * from './AdditionalPropertiesResponse'; export * from './AnotherNamedOneOf'; export * from './ArrayOfOneOfs'; +export * from './Dictionary'; export * from './InlineEnum200Response'; export * from './InlineEnum200ResponseCategoryEnum'; export * from './InlineRequestBodyRequestContent'; export * from './MyEnum'; export * from './NamedOneOf'; export * from './NamedOneOfUnion'; +export * from './SomeObject'; ", "src/models/model-utils.ts": "/* tslint:disable */ /* eslint-disable */