From 48e05ce16283f59ce6889543e3aac47ce1f1a2ad Mon Sep 17 00:00:00 2001 From: bflamand <33287817+bflamand@users.noreply.github.com> Date: Wed, 23 Jun 2021 12:07:17 -0400 Subject: [PATCH] [Typescript Fetch] New optional mode with redux saga & immutablejs (saga & records) (#8578) * first commit: add cli option for saga and records. Added dummy sagas.mustache test file. * More progress with default values. First prototype for isEntity and isUniqueId. * record generation complete * record generation complete * progress with saga generation * progress with saga generation * first fully working saga generation * merge with latest master * removed unneeded "items" properties. * moved global CodegenModel modifications into subclass ExtendedCodegenModel used exclusively by TypescriptFetchClient. Adding missing samples files. * moved global CodegenOperation modifications into subclass ExtendedCodegenOperation used exclusively by TypescriptFetchClient. * moved global CodegenProperty modifications into subclass ExtendedCodegenProperty used exclusively by TypescriptFetchClient. * moved global CodegenParameter modifications into subclass ExtendedCodegenParameter used exclusively by TypescriptFetchClient. * added the missing "allSagas" export. * renamed & reworked "meta data response" flags to a more useful general concept of "operation return passthrough" * added vendor flag keepAsJSObject as escape hatch to support circular dependencies in models and other special cases. Also fixed issues with default values for some records properties. * added autodetection for passthrough to simplify standardised specs. * fix small issue with passthrough void * fix small issues with passthrough void and missing passthrough imports in some cases. Fix issues with enum default values. * fix small issues with passthrough void and missing passthrough imports in some cases. Fix issues with enum default values. * Added "reservedRecordField" feature to support remapping fields names that cannot be used in Records. Added missing export to record: toApi(). * added uniqueId inference. Fix small generation when uniqueId property is an array. * removed feature "reservedRecordField" and replaced it with existing built-in "reserved words" feature. Fix minor issues with typings in generated files. * Changed api recType names to make them less likely to cause name conflicts. Added generated ApiEntities (record, reducer & selector) files. * Moved location of ApiEntities related files and fix issues with exports. * - merge latest master - renamed fake test apis to better fit the "pet theme" - added mode for "SourceOnlyLibrary" (same as used in codegen typescript jquery) * - missing ganarate sampless * - Modified way to export apiEntitiesSelectpr to reduce typescript analysis time for consuming project. Removed tab characters in mustache files. Reformat code for TypeScriptFetchClientCodegen to try to remove false positive for tabs vs spaces. * - added markErrorsAsHandled property to api sagas. Increased typescript version to address some typing errors on library build. * - fix bug in saga interfaces. Upgraded to typescript "strict" mode to ensure proper typechecking info is generated. * - added optional id for apiEntity selectors. Added toInlined() support to convert an entity to an inlined model recursively. * - minor tweak for apiEntitySelector to accept null id * - minor tweak for apiEntitySelector * - runned ensure up to date. * Revert "- runned ensure up to date." This reverts commit ea9b4aed * - runned ensure up to date. * - runned ensure up to date. Co-authored-by: Bruno Flamand --- .../typescript-fetch-sagas-and-records.yaml | 16 + docs/generators/typescript-fetch.md | 1 + .../openapitools/codegen/DefaultCodegen.java | 18 +- .../TypeScriptFetchClientCodegen.java | 1106 +++++++++++++++- .../ApiEntitiesRecord.mustache | 26 + .../ApiEntitiesReducer.mustache | 21 + .../ApiEntitiesSelectors.mustache | 5 + .../typescript-fetch/allSagas.mustache | 19 + .../typescript-fetch/apis.index.mustache | 7 + .../resources/typescript-fetch/index.mustache | 6 + .../typescript-fetch/models.index.mustache | 8 +- .../typescript-fetch/package.mustache | 17 +- .../typescript-fetch/recordGeneric.mustache | 271 ++++ .../typescript-fetch/records.mustache | 15 + .../runtimeSagasAndRecords.mustache | 120 ++ .../typescript-fetch/sagaApiManager.mustache | 36 + .../resources/typescript-fetch/sagas.mustache | 239 ++++ .../sourceLibraryIndex.mustache | 1 + .../typescript-fetch/tsconfig.mustache | 3 + .../TypeScriptFetchClientOptionsProvider.java | 2 + .../TypeScriptFetchClientOptionsTest.java | 1 + ...s-models-for-testing-saga-and-records.yaml | 1175 +++++++++++++++++ .../builds/sagas-and-records/.gitignore | 4 + .../builds/sagas-and-records/.npmignore | 1 + .../.openapi-generator-ignore | 23 + .../.openapi-generator/FILES | 71 + .../.openapi-generator/VERSION | 1 + .../builds/sagas-and-records/README.md | 45 + .../builds/sagas-and-records/package.json | 21 + .../src/ApiEntitiesRecord.ts | 22 + .../src/ApiEntitiesReducer.ts | 21 + .../src/ApiEntitiesSelectors.ts | 5 + .../sagas-and-records/src/apis/BehaviorApi.ts | 99 ++ .../src/apis/BehaviorApiSagas.ts | 131 ++ .../sagas-and-records/src/apis/PetApi.ts | 560 ++++++++ .../sagas-and-records/src/apis/PetApiSagas.ts | 565 ++++++++ .../sagas-and-records/src/apis/PetPartApi.ts | 136 ++ .../src/apis/PetPartApiSagas.ts | 156 +++ .../src/apis/SagaApiManager.ts | 36 + .../sagas-and-records/src/apis/StoreApi.ts | 168 +++ .../src/apis/StoreApiSagas.ts | 225 ++++ .../sagas-and-records/src/apis/UserApi.ts | 326 +++++ .../src/apis/UserApiSagas.ts | 395 ++++++ .../sagas-and-records/src/apis/allSagas.ts | 19 + .../sagas-and-records/src/apis/index.ts | 12 + .../builds/sagas-and-records/src/index.ts | 7 + .../src/models/BehaviorType.ts | 37 + .../src/models/BehaviorTypeRecord.ts | 1 + .../sagas-and-records/src/models/Category.ts | 65 + .../src/models/CategoryRecord.ts | 104 ++ .../src/models/DefaultMetaOnlyResponse.ts | 64 + .../models/DefaultMetaOnlyResponseRecord.ts | 62 + .../src/models/DeploymentRequestStatus.ts | 46 + .../models/DeploymentRequestStatusRecord.ts | 1 + .../sagas-and-records/src/models/ErrorCode.ts | 52 + .../src/models/ErrorCodeRecord.ts | 1 + .../src/models/FindPetsByStatusResponse.ts | 76 ++ .../models/FindPetsByStatusResponseRecord.ts | 83 ++ .../src/models/FindPetsByUserResponse.ts | 76 ++ .../models/FindPetsByUserResponseRecord.ts | 83 ++ .../models/GetBehaviorPermissionsResponse.ts | 72 + .../GetBehaviorPermissionsResponseRecord.ts | 72 + .../src/models/GetBehaviorTypeResponse.ts | 76 ++ .../models/GetBehaviorTypeResponseRecord.ts | 75 ++ .../src/models/GetMatchingPartsResponse.ts | 76 ++ .../models/GetMatchingPartsResponseRecord.ts | 83 ++ .../src/models/GetPetPartTypeResponse.ts | 76 ++ .../models/GetPetPartTypeResponseRecord.ts | 75 ++ .../sagas-and-records/src/models/ItemId.ts | 65 + .../src/models/ItemIdRecord.ts | 54 + .../src/models/MatchingParts.ts | 72 + .../src/models/MatchingPartsRecord.ts | 65 + .../src/models/ModelApiResponse.ts | 73 + .../src/models/ModelApiResponseRecord.ts | 55 + .../src/models/ModelError.ts | 88 ++ .../src/models/ModelErrorRecord.ts | 65 + .../sagas-and-records/src/models/Order.ts | 107 ++ .../src/models/OrderRecord.ts | 109 ++ .../sagas-and-records/src/models/Part.ts | 65 + .../src/models/PartRecord.ts | 56 + .../sagas-and-records/src/models/Pet.ts | 238 ++++ .../src/models/PetPartType.ts | 37 + .../src/models/PetPartTypeRecord.ts | 1 + .../sagas-and-records/src/models/PetRecord.ts | 177 +++ .../src/models/ResponseMeta.ts | 134 ++ .../src/models/ResponseMetaRecord.ts | 62 + .../sagas-and-records/src/models/Tag.ts | 65 + .../sagas-and-records/src/models/TagRecord.ts | 104 ++ .../sagas-and-records/src/models/User.ts | 129 ++ .../src/models/UserRecord.ts | 112 ++ .../src/models/WarningCode.ts | 37 + .../src/models/WarningCodeRecord.ts | 1 + .../sagas-and-records/src/models/index.ts | 41 + .../builds/sagas-and-records/src/runtime.ts | 319 +++++ .../src/runtimeSagasAndRecords.ts | 120 ++ .../builds/sagas-and-records/tsconfig.json | 17 + .../builds/typescript-three-plus/package.json | 2 +- .../src/models/Category.ts | 65 + .../src/models/ModelApiResponse.ts | 73 + .../src/models/Order.ts | 107 ++ .../without-runtime-checks/src/models/Pet.ts | 118 ++ .../without-runtime-checks/src/models/Tag.ts | 65 + .../without-runtime-checks/src/models/User.ts | 113 ++ .../src/models/index.ts | 6 - 104 files changed, 10473 insertions(+), 62 deletions(-) create mode 100644 bin/configs/typescript-fetch-sagas-and-records.yaml create mode 100644 modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesRecord.mustache create mode 100644 modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesReducer.mustache create mode 100644 modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesSelectors.mustache create mode 100644 modules/openapi-generator/src/main/resources/typescript-fetch/allSagas.mustache create mode 100644 modules/openapi-generator/src/main/resources/typescript-fetch/recordGeneric.mustache create mode 100644 modules/openapi-generator/src/main/resources/typescript-fetch/records.mustache create mode 100644 modules/openapi-generator/src/main/resources/typescript-fetch/runtimeSagasAndRecords.mustache create mode 100644 modules/openapi-generator/src/main/resources/typescript-fetch/sagaApiManager.mustache create mode 100644 modules/openapi-generator/src/main/resources/typescript-fetch/sagas.mustache create mode 100644 modules/openapi-generator/src/main/resources/typescript-fetch/sourceLibraryIndex.mustache create mode 100644 modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-saga-and-records.yaml create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/.gitignore create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/.npmignore create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator-ignore create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/FILES create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/VERSION create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/README.md create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/package.json create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesReducer.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesSelectors.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApi.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApiSagas.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApi.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApiSagas.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApi.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApiSagas.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/SagaApiManager.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApi.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApiSagas.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApi.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApiSagas.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/allSagas.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/index.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/index.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorType.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorTypeRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Category.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/CategoryRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponse.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponseRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatus.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatusRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCode.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCodeRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponse.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponseRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponse.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponseRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponse.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponseRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponse.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponseRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponse.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponseRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponse.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponseRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemId.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemIdRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingParts.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingPartsRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponse.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponseRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelError.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelErrorRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Order.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/OrderRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Part.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PartRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Pet.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartType.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartTypeRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMeta.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMetaRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Tag.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/TagRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/User.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/UserRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCode.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCodeRecord.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/index.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtimeSagasAndRecords.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/sagas-and-records/tsconfig.json create mode 100644 samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Category.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/ModelApiResponse.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Order.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Pet.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Tag.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/User.ts diff --git a/bin/configs/typescript-fetch-sagas-and-records.yaml b/bin/configs/typescript-fetch-sagas-and-records.yaml new file mode 100644 index 00000000000..a9fbe6136c7 --- /dev/null +++ b/bin/configs/typescript-fetch-sagas-and-records.yaml @@ -0,0 +1,16 @@ +generatorName: typescript-fetch +outputDir: samples/client/petstore/typescript-fetch/builds/sagas-and-records +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-saga-and-records.yaml +additionalProperties: + npmVersion: 1.0.0 + npmName: '@openapitools/typescript-fetch-petstore' + npmRepository: https://skimdb.npmjs.com/registry + useSingleRequestParameter: false + supportsES6: true + typescriptThreePlus: true + sagasAndRecords: true + detectPassthroughModelsWithSuffixAndField: 'Response.data' + inferUniqueIdFromNameSuffix: true + inferEntityFromUniqueIdWithName: id + packageAsSourceOnlyLibrary: false + snapshot: false \ No newline at end of file diff --git a/docs/generators/typescript-fetch.md b/docs/generators/typescript-fetch.md index d197da526a5..f8e9cd2328a 100644 --- a/docs/generators/typescript-fetch.md +++ b/docs/generators/typescript-fetch.md @@ -21,6 +21,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |paramNaming|Naming convention for parameters: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| |prefixParameterInterfaces|Setting this property to true will generate parameter interface declarations prefixed with API class name to avoid name conflicts.| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|sagasAndRecords|Setting this property to true will generate additional files for use with redux-saga and immutablejs.| |false| |snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 1f4fecb0395..1d6f244e9cc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -5531,13 +5531,9 @@ public class DefaultCodegen implements CodegenConfig { // handle default value for enum, e.g. available => StatusEnum.AVAILABLE if (var.defaultValue != null) { + final String enumDefaultValue = getEnumDefaultValue(var.defaultValue, dataType); + String enumName = null; - final String enumDefaultValue; - if (isDataTypeString(dataType)) { - enumDefaultValue = toEnumValue(var.defaultValue, dataType); - } else { - enumDefaultValue = var.defaultValue; - } for (Map enumVar : enumVars) { if (enumDefaultValue.equals(enumVar.get("value"))) { enumName = (String) enumVar.get("name"); @@ -5550,6 +5546,16 @@ public class DefaultCodegen implements CodegenConfig { } } + protected String getEnumDefaultValue(String defaultValue, String dataType) { + final String enumDefaultValue; + if (isDataTypeString(dataType)) { + enumDefaultValue = toEnumValue(defaultValue, dataType); + } else { + enumDefaultValue = defaultValue; + } + return enumDefaultValue; + } + protected List> buildEnumVars(List values, String dataType) { List> enumVars = new ArrayList<>(); int truncateIdx = 0; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java index d182ffb6e0e..c32bdcbb6cc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java @@ -19,7 +19,12 @@ package org.openapitools.codegen.languages; import com.google.common.collect.ImmutableMap; import com.samskivert.mustache.Mustache; +import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.parameters.RequestBody; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.servers.Server; import io.swagger.v3.parser.util.SchemaTypeUtil; import org.openapitools.codegen.*; import org.openapitools.codegen.meta.features.DocumentationFeature; @@ -27,12 +32,9 @@ import org.openapitools.codegen.templating.mustache.IndentedLambda; import org.openapitools.codegen.utils.ModelUtils; import java.io.File; -import java.util.TreeSet; -import java.util.List; -import java.util.Map; +import java.util.*; public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodegen { - public static final String NPM_REPOSITORY = "npmRepository"; public static final String WITH_INTERFACES = "withInterfaces"; public static final String USE_SINGLE_REQUEST_PARAMETER = "useSingleRequestParameter"; @@ -48,6 +50,24 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege protected boolean typescriptThreePlus = false; protected boolean withoutRuntimeChecks = false; + // "Saga and Record" mode. + public static final String SAGAS_AND_RECORDS = "sagasAndRecords"; + public static final String DETECT_PASSTHROUGH_MODELS_WITH_SUFFIX_AND_FIELD = "detectPassthroughModelsWithSuffixAndField"; + public static final String INFER_UNIQUE_ID_FROM_NAME_SUFFIX = "inferUniqueIdFromNameSuffix"; + public static final String INFER_ENTITY_FROM_UNIQUE_ID_WITH_NAME = "inferEntityFromUniqueIdWithName"; + public static final String PACKAGE_AS_SOURCE_ONLY_LIBRARY = "packageAsSourceOnlyLibrary"; + + private static final String X_IS_UNIQUE_ID = "x-isUniqueId"; + private static final String X_ENTITY_ID = "x-entityId"; + private static final String X_OPERATION_RETURN_PASSTHROUGH = "x-operationReturnPassthrough"; + private static final String X_KEEP_AS_JS_OBJECT = "x-keepAsJSObject"; + + protected boolean sagasAndRecords = false; + protected String detectPassthroughModelsWithSuffixAndField = null; // Ex: "Response;data" + protected boolean inferUniqueIdFromNameSuffix = false; + protected String inferEntityFromUniqueIdWithName = null; + protected boolean packageAsSourceOnlyLibrary = false; + public TypeScriptFetchClientCodegen() { super(); @@ -75,6 +95,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege this.cliOptions.add(new CliOption(PREFIX_PARAMETER_INTERFACES, "Setting this property to true will generate parameter interface declarations prefixed with API class name to avoid name conflicts.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); this.cliOptions.add(new CliOption(TYPESCRIPT_THREE_PLUS, "Setting this property to true will generate TypeScript 3.6+ compatible code.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); this.cliOptions.add(new CliOption(WITHOUT_RUNTIME_CHECKS, "Setting this property to true will remove any runtime checks on the request and response payloads. Payloads will be casted to their expected types.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(SAGAS_AND_RECORDS, "Setting this property to true will generate additional files for use with redux-saga and immutablejs.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); } @Override @@ -103,14 +124,72 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege this.typescriptThreePlus = typescriptThreePlus; } - public Boolean getWithoutRuntimeChecks(){ + public Boolean getWithoutRuntimeChecks() { return withoutRuntimeChecks; } - public void setWithoutRuntimeChecks(Boolean withoutRuntimeChecks){ + public void setWithoutRuntimeChecks(Boolean withoutRuntimeChecks) { this.withoutRuntimeChecks = withoutRuntimeChecks; } + public Boolean getSagasAndRecords() { + return sagasAndRecords; + } + + public void setSagasAndRecords(Boolean sagasAndRecords) { + this.sagasAndRecords = sagasAndRecords; + } + + public String getPassthroughSuffix() { + return detectPassthroughModelsWithSuffixAndField != null ? detectPassthroughModelsWithSuffixAndField.split("\\.")[0] : null; + } + + public String getPassthroughField() { + return detectPassthroughModelsWithSuffixAndField != null ? detectPassthroughModelsWithSuffixAndField.split("\\.")[1] : null; + } + + public String getDetectPassthroughModelsWithSuffixAndField() { + return detectPassthroughModelsWithSuffixAndField; + } + + public void setDetectPassthroughModelsWithSuffixAndField(String detectPassthroughModelsWithSuffixAndField) { + this.detectPassthroughModelsWithSuffixAndField = detectPassthroughModelsWithSuffixAndField; + } + + public boolean getInferUniqueIdFromNameSuffix() { + return inferUniqueIdFromNameSuffix; + } + + public void setInferUniqueIdFromNameSuffix(boolean inferUniqueIdFromNameSuffix) { + this.inferUniqueIdFromNameSuffix = inferUniqueIdFromNameSuffix; + } + + public String getInferEntityFromUniqueIdWithName() { + return inferEntityFromUniqueIdWithName; + } + + public void setInferEntityFromUniqueIdWithName(String inferEntityFromUniqueIdWithName) { + this.inferEntityFromUniqueIdWithName = inferEntityFromUniqueIdWithName; + } + + public boolean getPackageAsSourceOnlyLibrary() { + return packageAsSourceOnlyLibrary; + } + + public void setPackageAsSourceOnlyLibrary(boolean packageAsSourceOnlyLibrary) { + this.packageAsSourceOnlyLibrary = packageAsSourceOnlyLibrary; + } + + public boolean isUniqueIdAccordingToNameSuffix(String name) { + if (name == null) { + return false; + } + return "id".equals(name) || + "ids".equals(name) || + (name.length() >= 3 && name.substring(name.length() - 2).equals("Id")) || + (name.length() >= 4 && name.substring(name.length() - 3).equals("Ids")); + } + @Override public void processOpts() { super.processOpts(); @@ -150,11 +229,59 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege this.setWithoutRuntimeChecks(convertPropertyToBoolean(WITHOUT_RUNTIME_CHECKS)); } - if(!withoutRuntimeChecks){ + if (!withoutRuntimeChecks) { this.modelTemplateFiles.put("models.mustache", ".ts"); } + + if (additionalProperties.containsKey(SAGAS_AND_RECORDS)) { + this.setSagasAndRecords(convertPropertyToBoolean(SAGAS_AND_RECORDS)); + if (this.getSagasAndRecords()) { + apiTemplateFiles.put("sagas.mustache", "Sagas.ts"); + modelTemplateFiles.put("records.mustache", "Record.ts"); + supportingFiles.add(new SupportingFile("runtimeSagasAndRecords.mustache", sourceDir, "runtimeSagasAndRecords.ts")); + supportingFiles.add(new SupportingFile("ApiEntitiesRecord.mustache", sourceDir, "ApiEntitiesRecord.ts")); + supportingFiles.add(new SupportingFile("ApiEntitiesReducer.mustache", sourceDir, "ApiEntitiesReducer.ts")); + supportingFiles.add(new SupportingFile("ApiEntitiesSelectors.mustache", sourceDir, "ApiEntitiesSelectors.ts")); + + if (additionalProperties.containsKey(DETECT_PASSTHROUGH_MODELS_WITH_SUFFIX_AND_FIELD)) { + this.setDetectPassthroughModelsWithSuffixAndField((String) additionalProperties.get(DETECT_PASSTHROUGH_MODELS_WITH_SUFFIX_AND_FIELD)); + } + if (additionalProperties.containsKey(INFER_UNIQUE_ID_FROM_NAME_SUFFIX)) { + this.setInferUniqueIdFromNameSuffix(convertPropertyToBoolean(INFER_UNIQUE_ID_FROM_NAME_SUFFIX)); + } + if (additionalProperties.containsKey(INFER_ENTITY_FROM_UNIQUE_ID_WITH_NAME)) { + this.setInferEntityFromUniqueIdWithName((String) additionalProperties.get(INFER_ENTITY_FROM_UNIQUE_ID_WITH_NAME)); + } + if (additionalProperties.containsKey(PACKAGE_AS_SOURCE_ONLY_LIBRARY)) { + this.setPackageAsSourceOnlyLibrary(convertPropertyToBoolean(PACKAGE_AS_SOURCE_ONLY_LIBRARY)); + } + + this.addExtraReservedWordsForSagasAndRecords(); + + if (this.getPackageAsSourceOnlyLibrary()) { + supportingFiles.add(new SupportingFile("sourceLibraryIndex.mustache", "", "index.ts")); + } + } + } } + @Override + public String toEnumDefaultValue(String value, String datatype) { + if (this.getSagasAndRecords()) { + return datatype + "." + value; + } + return super.toEnumDefaultValue(value, datatype); + } + + @Override + protected String getEnumDefaultValue(String defaultValue, String dataType) { + if (this.getSagasAndRecords()) { + return defaultValue; + } + return super.getEnumDefaultValue(defaultValue, dataType); + } + + @Override protected ImmutableMap.Builder addMustacheLambdas() { ImmutableMap.Builder lambdas = super.addMustacheLambdas(); @@ -183,36 +310,12 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege public Map postProcessModels(Map objs) { List models = (List) postProcessModelsEnum(objs).get("models"); - // process enum in models + // process enum and custom properties in models for (Object _mo : models) { Map mo = (Map) _mo; - CodegenModel cm = (CodegenModel) mo.get("model"); + ExtendedCodegenModel cm = (ExtendedCodegenModel) mo.get("model"); cm.imports = new TreeSet(cm.imports); - // name enum with model name, e.g. StatusEnum => Pet.StatusEnum - for (CodegenProperty var : cm.vars) { - if (Boolean.TRUE.equals(var.isEnum)) { - // behaviour for enum names is specific for Typescript Fetch, not using namespaces - var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, cm.classname + var.enumName); - } - } - if (cm.parent != null) { - for (CodegenProperty var : cm.allVars) { - if (Boolean.TRUE.equals(var.isEnum)) { - var.datatypeWithEnum = var.datatypeWithEnum - .replace(var.enumName, cm.classname + var.enumName); - } - } - } - if (!cm.oneOf.isEmpty()) { - // For oneOfs only import $refs within the oneOf - TreeSet oneOfRefs = new TreeSet<>(); - for (String im : cm.imports) { - if (cm.oneOf.contains(im)) { - oneOfRefs.add(im); - } - } - cm.imports = oneOfRefs; - } + this.processCodeGenModel(cm); } return objs; @@ -228,18 +331,71 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege @Override public Map postProcessAllModels(Map objs) { + List allModels = new ArrayList(); + List entityModelClassnames = new ArrayList(); + Map result = super.postProcessAllModels(objs); for (Map.Entry entry : result.entrySet()) { Map inner = (Map) entry.getValue(); List> models = (List>) inner.get("models"); for (Map model : models) { - CodegenModel codegenModel = (CodegenModel) model.get("model"); + ExtendedCodegenModel codegenModel = (ExtendedCodegenModel) model.get("model"); model.put("hasImports", codegenModel.imports.size() > 0); + + allModels.add(codegenModel); + if (codegenModel.isEntity) { + entityModelClassnames.add(codegenModel.classname); + } + } + } + + for (ExtendedCodegenModel rootModel : allModels) { + for (String curImport : rootModel.imports) { + boolean isModelImport = false; + for (ExtendedCodegenModel model : allModels) { + if (model.classname.equals(curImport) && !model.isEnum) { + isModelImport = true; + break; + } + } + if (isModelImport) { + rootModel.modelImports.add(curImport); + } + } + + for (CodegenProperty cpVar : rootModel.vars) { + ExtendedCodegenProperty var = (ExtendedCodegenProperty) cpVar; + if (var.isModel && entityModelClassnames.indexOf(var.dataType) != -1) { + var.isEntity = true; + } else if (var.isArray && var.items.isModel && entityModelClassnames.indexOf(var.items.dataType) != -1) { + ((ExtendedCodegenProperty) var.items).isEntity = true; + } } } return result; } + private void autoSetDefaultValueForProperty(ExtendedCodegenProperty var) { + if (var.isArray || var.isModel) { + var.defaultValue = var.dataTypeAlternate + "()"; + } else if (var.isUniqueId) { + var.defaultValue = "\"-1\""; + } else if (var.isEnum) { + var.defaultValue = "'" + var._enum.get(0) + "'"; + updateCodegenPropertyEnum(var); + } else if (var.dataType.equalsIgnoreCase("string")) { + var.defaultValue = "\"\""; + } else if (var.dataType.equalsIgnoreCase("number")) { + var.defaultValue = "0"; + } else if (var.dataType.equalsIgnoreCase("boolean")) { + var.defaultValue = "false"; + } else { + if (var.allowableValues != null && var.allowableValues.get("enumVars") instanceof ArrayList && ((ArrayList) var.allowableValues.get("enumVars")).get(0) instanceof HashMap) { + var.defaultValue = var.dataTypeAlternate + "." + ((HashMap) ((ArrayList) var.allowableValues.get("enumVars")).get(0)).get("name"); + } + } + } + private void addNpmPackageGeneration() { if (additionalProperties.containsKey(NPM_REPOSITORY)) { @@ -254,12 +410,160 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); } + @Override + public List fromRequestBodyToFormParameters(RequestBody body, Set imports) { + List superParams = super.fromRequestBodyToFormParameters(body, imports); + List extendedParams = new ArrayList(); + for (CodegenParameter cp : superParams) { + extendedParams.add(new ExtendedCodegenParameter(cp)); + } + return extendedParams; + } + + @Override + public ExtendedCodegenParameter fromParameter(Parameter parameter, Set imports) { + CodegenParameter cp = super.fromParameter(parameter, imports); + return new ExtendedCodegenParameter(cp); + } + + @Override + public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set imports) { + CodegenParameter cp = super.fromFormProperty(name, propertySchema, imports); + return new ExtendedCodegenParameter(cp); + } + + @Override + public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { + CodegenParameter cp = super.fromRequestBody(body, imports, bodyParameterName); + return new ExtendedCodegenParameter(cp); + } + + @Override + public ExtendedCodegenProperty fromProperty(String name, Schema p) { + CodegenProperty cp = super.fromProperty(name, p); + return new ExtendedCodegenProperty(cp); + } + + @Override + public ExtendedCodegenModel fromModel(String name, Schema model) { + CodegenModel cm = super.fromModel(name, model); + return new ExtendedCodegenModel(cm); + } + + @Override + public ExtendedCodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) { + CodegenOperation superOp = super.fromOperation(path, httpMethod, operation, servers); + ExtendedCodegenOperation op = new ExtendedCodegenOperation(superOp); + + if (this.getSagasAndRecords()) { + ApiResponse methodResponse = findMethodResponse(operation.getResponses()); + if (methodResponse != null) { + Map schemas = ModelUtils.getSchemas(this.openAPI); + Schema schema = null; + if (schemas != null) { + schema = schemas.get(op.returnBaseType); + } + + ExtendedCodegenModel cm = null; + if (schema != null) { + cm = fromModel(op.returnBaseType, schema); + + Object returnPassthrough = cm.vendorExtensions.get(X_OPERATION_RETURN_PASSTHROUGH); + if (returnPassthrough instanceof String) { + if (((String) returnPassthrough).isEmpty()) { + op.hasReturnPassthroughVoid = true; + op.returnPassthrough = null; + } else { + boolean foundMatch = false; + for (CodegenProperty var : cm.vars) { + if (var.name.equals(returnPassthrough)) { + foundMatch = true; + break; + } + } + if (foundMatch) { + op.returnPassthrough = (String) returnPassthrough; + } else { // no match, treat as if empty. + op.hasReturnPassthroughVoid = true; + op.returnPassthrough = null; + } + } + } else if (this.getDetectPassthroughModelsWithSuffixAndField() != null && op.returnBaseType.length() > this.getPassthroughSuffix().length() && op.returnBaseType.substring(op.returnBaseType.length() - this.getPassthroughSuffix().length()).equals(this.getPassthroughSuffix())) { + boolean foundMatch = false; + for (CodegenProperty var : cm.vars) { + if (var.name.equals(this.getPassthroughField())) { + foundMatch = true; + break; + } + } + if (foundMatch) { + op.returnPassthrough = this.getPassthroughField(); + } else { // no match, treat as if empty. + op.hasReturnPassthroughVoid = true; + op.returnPassthrough = null; + } + } + } + + if (!op.hasReturnPassthroughVoid) { + Schema responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(methodResponse), importMapping); + ExtendedCodegenProperty cp = null; + if (op.returnPassthrough instanceof String && cm != null) { + cp = (ExtendedCodegenProperty) this.processCodeGenModel(cm).vars.get(1); + } else if (responseSchema != null) { + cp = fromProperty("response", responseSchema); + this.processCodegenProperty(cp, "", null); + } + + op.returnBaseTypeAlternate = null; + if (cp != null) { + op.returnTypeAlternate = cp.dataTypeAlternate; + op.returnTypeIsModel = cp.isModel; + op.returnTypeIsArray = cp.isArray; + if (cp.isArray) { + if (cp.items.isModel) { + op.returnTypeSupportsEntities = true; + op.returnBaseTypeAlternate = cp.items.dataType + "Record"; + } else if (cp.items.allowableValues != null) { + op.returnBaseTypeAlternate = cp.items.dataType; + } + } else if (cp.isModel) { + op.returnTypeSupportsEntities = true; + op.returnBaseTypeAlternate = cp.dataTypeAlternate; + } else if (cp.allowableValues != null) { + op.returnBaseTypeAlternate = cp.dataTypeAlternate; + } + + } + } + } + } + + return op; + } + + @Override + public String escapeReservedWord(String name) { + if (this.getSagasAndRecords()) { + if (this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; + } else { + return super.escapeReservedWord(name); + } + } + @Override public Map postProcessOperationsWithModels(Map operations, List allModels) { // Add supporting file only if we plan to generate files in /apis if (operations.size() > 0 && !addedApiIndex) { addedApiIndex = true; supportingFiles.add(new SupportingFile("apis.index.mustache", apiPackage().replace('.', File.separatorChar), "index.ts")); + if (this.getSagasAndRecords()) { + supportingFiles.add(new SupportingFile("sagaApiManager.mustache", apiPackage().replace('.', File.separatorChar), "SagaApiManager.ts")); + supportingFiles.add(new SupportingFile("allSagas.mustache", apiPackage().replace('.', File.separatorChar), "allSagas.ts")); + } } // Add supporting file only if we plan to generate files in /models @@ -269,17 +573,169 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege } this.addOperationModelImportInfomation(operations); - this.updateOperationParameterEnumInformation(operations); + this.updateOperationParameterForEnum(operations); + if (this.getSagasAndRecords()) { + this.updateOperationParameterForSagaAndRecords(operations); + } this.addOperationObjectResponseInformation(operations); this.addOperationPrefixParameterInterfacesInformation(operations); this.escapeOperationIds(operations); return operations; } + @Override + public Map postProcessSupportingFileData(Map objs) { + Map parentObjs = super.postProcessSupportingFileData(objs); + + parentObjs.put("useSagaAndRecords", this.getSagasAndRecords()); + + return parentObjs; + } + + private ExtendedCodegenModel processCodeGenModel(ExtendedCodegenModel cm) { + if (this.getSagasAndRecords()) { + Object xEntityId = cm.vendorExtensions.get(X_ENTITY_ID); + if (xEntityId == null && this.getInferEntityFromUniqueIdWithName() != null) { + xEntityId = this.getInferEntityFromUniqueIdWithName(); + } + Object vendorKeepAsJSObject = cm.vendorExtensions.get(X_KEEP_AS_JS_OBJECT); + String[] propertiesToKeepAsJSObject = null; + if (vendorKeepAsJSObject instanceof String) { + propertiesToKeepAsJSObject = ((String) vendorKeepAsJSObject).split(","); + } + + for (CodegenProperty cpVar : cm.vars) { + ExtendedCodegenProperty var = (ExtendedCodegenProperty) cpVar; + if (propertiesToKeepAsJSObject != null && Arrays.asList(propertiesToKeepAsJSObject).contains(var.name)) { + var.keepAsJSObject = true; + } + boolean parentIsEntity = this.processCodegenProperty(var, cm.classname, xEntityId); + if (parentIsEntity) { + cm.isEntity = true; + } + } + + Object returnPassthrough = cm.vendorExtensions.get(X_OPERATION_RETURN_PASSTHROUGH); + if (returnPassthrough instanceof String) { + if (((String) returnPassthrough).isEmpty()) { + cm.hasReturnPassthroughVoid = true; + cm.returnPassthrough = null; + } else { + boolean foundMatch = false; + for (CodegenProperty var : cm.vars) { + if (var.name.equals(returnPassthrough)) { + foundMatch = true; + break; + } + } + if (foundMatch) { + cm.returnPassthrough = (String) returnPassthrough; + } else { // no match, treat as if empty. + cm.hasReturnPassthroughVoid = true; + cm.returnPassthrough = null; + } + } + } else if (this.getDetectPassthroughModelsWithSuffixAndField() != null && cm.name.length() > this.getPassthroughSuffix().length() && cm.name.substring(cm.name.length() - this.getPassthroughSuffix().length()).equals(this.getPassthroughSuffix())) { + boolean foundMatch = false; + for (CodegenProperty var : cm.vars) { + if (var.name.equals(this.getPassthroughField())) { + foundMatch = true; + break; + } + } + if (foundMatch) { + cm.returnPassthrough = this.getPassthroughField(); + } else { // no match, treat as if empty. + cm.hasReturnPassthroughVoid = true; + cm.returnPassthrough = null; + } + } + } else { + for (CodegenProperty cpVar : cm.vars) { + ExtendedCodegenProperty var = (ExtendedCodegenProperty) cpVar; + this.processCodegenProperty(var, cm.classname, null); + } + } + + if (cm.parent != null) { + for (CodegenProperty cpVar : cm.allVars) { + ExtendedCodegenProperty var = (ExtendedCodegenProperty) cpVar; + + if (Boolean.TRUE.equals(var.isEnum)) { + var.datatypeWithEnum = var.datatypeWithEnum + .replace(var.enumName, cm.classname + var.enumName); + } + } + } + if (!cm.oneOf.isEmpty()) { + // For oneOfs only import $refs within the oneOf + TreeSet oneOfRefs = new TreeSet<>(); + for (String im : cm.imports) { + if (cm.oneOf.contains(im)) { + oneOfRefs.add(im); + } + } + cm.imports = oneOfRefs; + } + return cm; + } + + private boolean processCodegenProperty(ExtendedCodegenProperty var, String parentClassName, Object xEntityId) { + // name enum with model name, e.g. StatusEnum => PetStatusEnum + if (Boolean.TRUE.equals(var.isEnum)) { + // behaviour for enum names is specific for Typescript Fetch, not using namespaces + var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, parentClassName + var.enumName); + + // need to post-process defaultValue, was computed with previous var.datatypeWithEnum + if (var.defaultValue != null && !var.defaultValue.equals("undefined")) { + int dotPos = var.defaultValue.indexOf("."); + if (dotPos != -1) { + var.defaultValue = var.datatypeWithEnum + var.defaultValue.substring(dotPos); + } + } + } + + boolean parentIsEntity = false; + if (this.getSagasAndRecords()) { + if (var.vendorExtensions.get(X_IS_UNIQUE_ID) instanceof Boolean) { + var.isUniqueId = Boolean.TRUE.equals(var.vendorExtensions.get(X_IS_UNIQUE_ID)); + } else if (this.getInferUniqueIdFromNameSuffix() && (var.isArray && "number".equals(var.items.dataType)) || ("number".equals(var.dataType))) { + var.isUniqueId = this.isUniqueIdAccordingToNameSuffix(var.name); + } + if (var.isUniqueId && xEntityId != null && xEntityId.equals(var.name)) { + parentIsEntity = true; + } + + var.dataTypeAlternate = var.dataType; + if (var.isArray) { + var.dataTypeAlternate = var.dataType.replace("Array<", "List<"); + if (var.items.isModel) { + String itemsDataType = var.items.dataType + "Record"; + var.dataTypeAlternate = var.dataTypeAlternate.replace(var.items.dataType, itemsDataType); + } else if (var.items.isEnum) { + var.dataTypeAlternate = var.dataTypeAlternate.replace(var.items.dataType, var.items.datatypeWithEnum); + } + if (var.isUniqueId) { + var.dataTypeAlternate = var.dataTypeAlternate.replace("number", "string"); + } + } else if (var.isEnum) { + var.dataTypeAlternate = var.datatypeWithEnum; + } else if (var.isModel) { + var.dataTypeAlternate = var.dataType + "Record"; + } else if (var.isUniqueId) { + var.dataTypeAlternate = "string"; + } + if (var.defaultValue == null || var.defaultValue.equals("undefined")) { + this.autoSetDefaultValueForProperty(var); + } + } + return parentIsEntity; + } + private void escapeOperationIds(Map operations) { Map _operations = (Map) operations.get("operations"); - List operationList = (List) _operations.get("operation"); - for (CodegenOperation op : operationList) { + List operationList = (List) _operations.get("operation"); + for (ExtendedCodegenOperation op : operationList) { String param = op.operationIdCamelCase + "Request"; if (op.imports.contains(param)) { // we import a model with the same name as the generated operation, escape it @@ -295,19 +751,44 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege // The api template uses this infomation to import all the required // models for a given operation. List> imports = (List>) operations.get("imports"); + List existingRecordClassNames = new ArrayList(); + List existingClassNames = new ArrayList(); for (Map im : imports) { - im.put("className", im.get("import").toString().replace(modelPackage() + ".", "")); + String className = im.get("import").toString().replace(modelPackage() + ".", ""); + existingClassNames.add(className); + existingRecordClassNames.add(className + "Record"); + im.put("className", className); + } + + if (this.getSagasAndRecords()) { + Map _operations = (Map) operations.get("operations"); + List operationList = (List) _operations.get("operation"); + Set additionalPassthroughImports = new TreeSet(); + for (ExtendedCodegenOperation op : operationList) { + if (op.returnPassthrough != null && op.returnBaseTypeAlternate instanceof String) { + if (op.returnTypeSupportsEntities && !existingRecordClassNames.contains(op.returnBaseTypeAlternate)) { + additionalPassthroughImports.add(op.returnBaseTypeAlternate); + } else if (!op.returnTypeSupportsEntities && !existingClassNames.contains(op.returnBaseTypeAlternate)) { + additionalPassthroughImports.add(op.returnBaseTypeAlternate); + } + } + } + operations.put("passthroughImports", additionalPassthroughImports); + operations.put("hasPassthroughImports", additionalPassthroughImports.size() > 0); } } - private void updateOperationParameterEnumInformation(Map operations) { + private void updateOperationParameterForEnum(Map operations) { // This method will add extra infomation as to whether or not we have enums and // update their names with the operation.id prefixed. + // It will also set the uniqueId status if provided. Map _operations = (Map) operations.get("operations"); - List operationList = (List) _operations.get("operation"); + List operationList = (List) _operations.get("operation"); boolean hasEnum = false; - for (CodegenOperation op : operationList) { - for (CodegenParameter param : op.allParams) { + for (ExtendedCodegenOperation op : operationList) { + for (CodegenParameter cpParam : op.allParams) { + ExtendedCodegenParameter param = (ExtendedCodegenParameter) cpParam; + if (Boolean.TRUE.equals(param.isEnum)) { hasEnum = true; param.datatypeWithEnum = param.datatypeWithEnum @@ -319,14 +800,55 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege operations.put("hasEnums", hasEnum); } + private void updateOperationParameterForSagaAndRecords(Map operations) { + // This method will add extra infomation as to whether or not we have enums and + // update their names with the operation.id prefixed. + // It will also set the uniqueId status if provided. + Map _operations = (Map) operations.get("operations"); + List operationList = (List) _operations.get("operation"); + for (ExtendedCodegenOperation op : operationList) { + for (CodegenParameter cpParam : op.allParams) { + ExtendedCodegenParameter param = (ExtendedCodegenParameter) cpParam; + + if (param.vendorExtensions.get(X_IS_UNIQUE_ID) instanceof Boolean) { + param.isUniqueId = Boolean.TRUE.equals(param.vendorExtensions.get(X_IS_UNIQUE_ID)); + } else if (this.getInferUniqueIdFromNameSuffix() && (param.isArray && "number".equals(param.items.dataType)) || ("number".equals(param.dataType))) { + param.isUniqueId = this.isUniqueIdAccordingToNameSuffix(param.paramName); + } + + param.dataTypeAlternate = param.dataType; + if (param.isArray) { + if (param.items.isModel) { + String itemsDataType = param.items.dataType + "Record"; + param.dataTypeAlternate = param.dataType.replace("Array<", "List<"); + param.dataTypeAlternate = param.dataTypeAlternate.replace(param.items.dataType, itemsDataType); + } else if (param.items.isEnum) { + param.dataTypeAlternate = param.datatypeWithEnum.replace("Array<", "List<"); + } else { + param.dataTypeAlternate = param.dataType.replace("Array<", "List<"); + } + if (param.isUniqueId) { + param.dataTypeAlternate = param.dataTypeAlternate.replace("number", "string"); + } + } else if (param.isEnum) { + param.dataTypeAlternate = param.datatypeWithEnum; + } else if (param.isModel) { + param.dataTypeAlternate = param.dataType + "Record"; + } else if (param.isUniqueId) { + param.dataTypeAlternate = "string"; + } + } + } + } + private void addOperationObjectResponseInformation(Map operations) { // This method will modify the infomation on the operations' return type. // The api template uses this infomation to know when to return a text // response for a given simple response operation. Map _operations = (Map) operations.get("operations"); - List operationList = (List) _operations.get("operation"); - for (CodegenOperation op : operationList) { - if("object".equals(op.returnType)) { + List operationList = (List) _operations.get("operation"); + for (ExtendedCodegenOperation op : operationList) { + if ("object".equals(op.returnType)) { op.isMap = true; op.returnSimpleType = false; } @@ -369,6 +891,11 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege this.reservedWords.add("Index"); } + private void addExtraReservedWordsForSagasAndRecords() { + // immutablejs Records have potentially many reserved words. Adding only strict minimum for now. + this.reservedWords.add("entries"); + } + private boolean getUseSingleRequestParameter() { return useSingleRequestParameter; } @@ -384,4 +911,491 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege private void setPrefixParameterInterfaces(boolean prefixParameterInterfaces) { this.prefixParameterInterfaces = prefixParameterInterfaces; } + + class ExtendedCodegenParameter extends CodegenParameter { + public String dataTypeAlternate; + public boolean isUniqueId; // this parameter represents a unique id (x-isUniqueId: true) + + public ExtendedCodegenParameter(CodegenParameter cp) { + super(); + + this.isFormParam = cp.isFormParam; + this.isQueryParam = cp.isQueryParam; + this.isPathParam = cp.isPathParam; + this.isHeaderParam = cp.isHeaderParam; + this.isCookieParam = cp.isCookieParam; + this.isBodyParam = cp.isBodyParam; + this.isContainer = cp.isContainer; + this.isCollectionFormatMulti = cp.isCollectionFormatMulti; + this.isPrimitiveType = cp.isPrimitiveType; + this.isModel = cp.isModel; + this.isExplode = cp.isExplode; + this.baseName = cp.baseName; + this.paramName = cp.paramName; + this.dataType = cp.dataType; + this.datatypeWithEnum = cp.datatypeWithEnum; + this.dataFormat = cp.dataFormat; + this.contentType = cp.contentType; + this.collectionFormat = cp.collectionFormat; + this.description = cp.description; + this.unescapedDescription = cp.unescapedDescription; + this.baseType = cp.baseType; + this.defaultValue = cp.defaultValue; + this.enumName = cp.enumName; + this.style = cp.style; + this.nameInLowerCase = cp.nameInLowerCase; + this.example = cp.example; + this.jsonSchema = cp.jsonSchema; + this.isString = cp.isString; + this.isNumeric = cp.isNumeric; + this.isInteger = cp.isInteger; + this.isLong = cp.isLong; + this.isNumber = cp.isNumber; + this.isFloat = cp.isFloat; + this.isDouble = cp.isDouble; + this.isDecimal = cp.isDecimal; + this.isByteArray = cp.isByteArray; + this.isBinary = cp.isBinary; + this.isBoolean = cp.isBoolean; + this.isDate = cp.isDate; + this.isDateTime = cp.isDateTime; + this.isUuid = cp.isUuid; + this.isUri = cp.isUri; + this.isEmail = cp.isEmail; + this.isFreeFormObject = cp.isFreeFormObject; + this.isAnyType = cp.isAnyType; + this.isArray = cp.isArray; + this.isMap = cp.isMap; + this.isFile = cp.isFile; + this.isEnum = cp.isEnum; + this._enum = cp._enum; + this.allowableValues = cp.allowableValues; + this.items = cp.items; + this.additionalProperties = cp.additionalProperties; + this.vars = cp.vars; + this.requiredVars = cp.requiredVars; + this.mostInnerItems = cp.mostInnerItems; + this.vendorExtensions = cp.vendorExtensions; + this.hasValidation = cp.hasValidation; + this.isNullable = cp.isNullable; + this.required = cp.required; + this.maximum = cp.maximum; + this.exclusiveMaximum = cp.exclusiveMaximum; + this.minimum = cp.minimum; + this.exclusiveMinimum = cp.exclusiveMinimum; + this.maxLength = cp.maxLength; + this.minLength = cp.minLength; + this.pattern = cp.pattern; + this.maxItems = cp.maxItems; + this.minItems = cp.minItems; + this.uniqueItems = cp.uniqueItems; + this.multipleOf = cp.multipleOf; + this.setMaxProperties(cp.getMaxProperties()); + this.setMinProperties(cp.getMinProperties()); + } + + @Override + public ExtendedCodegenParameter copy() { + CodegenParameter superCopy = super.copy(); + ExtendedCodegenParameter output = new ExtendedCodegenParameter(superCopy); + output.dataTypeAlternate = this.dataTypeAlternate; + output.isUniqueId = this.isUniqueId; + return output; + } + + @Override + public boolean equals(Object o) { + boolean result = super.equals(o); + ExtendedCodegenParameter that = (ExtendedCodegenParameter) o; + return result && + isUniqueId == that.isUniqueId && + Objects.equals(dataTypeAlternate, that.dataTypeAlternate); + } + + @Override + public int hashCode() { + int superHash = super.hashCode(); + return Objects.hash(superHash, dataTypeAlternate, isUniqueId); + } + + @Override + public String toString() { + String superString = super.toString(); + final StringBuilder sb = new StringBuilder(superString); + sb.append(", isUniqueId=").append(isUniqueId); + sb.append(", dataTypeAlternate='").append(dataTypeAlternate).append('\''); + return sb.toString(); + } + } + + class ExtendedCodegenProperty extends CodegenProperty { + public String dataTypeAlternate; + public boolean isEntity; //Is a model containing an "id" property marked as isUniqueId and which matches the 'x-entityId' value. + public boolean isUniqueId; // The property represents a unique id (x-isUniqueId: true) + public boolean keepAsJSObject; + public boolean isReservedRecordField; + + public ExtendedCodegenProperty(CodegenProperty cp) { + super(); + + this.openApiType = openApiType; + this.baseName = cp.baseName; + this.complexType = cp.complexType; + this.getter = cp.getter; + this.setter = cp.setter; + this.description = cp.description; + this.dataType = cp.dataType; + this.datatypeWithEnum = cp.datatypeWithEnum; + this.dataFormat = cp.dataFormat; + this.name = cp.name; + this.min = cp.min; + this.max = cp.max; + this.defaultValue = cp.defaultValue; + this.defaultValueWithParam = cp.defaultValueWithParam; + this.baseType = cp.baseType; + this.containerType = cp.containerType; + this.title = cp.title; + this.unescapedDescription = cp.unescapedDescription; + this.maxLength = cp.maxLength; + this.minLength = cp.minLength; + this.pattern = cp.pattern; + this.example = cp.example; + this.jsonSchema = cp.jsonSchema; + this.minimum = cp.minimum; + this.maximum = cp.maximum; + this.multipleOf = cp.multipleOf; + this.exclusiveMinimum = cp.exclusiveMinimum; + this.exclusiveMaximum = cp.exclusiveMaximum; + this.required = cp.required; + this.deprecated = cp.deprecated; + this.hasMoreNonReadOnly = cp.hasMoreNonReadOnly; + this.isPrimitiveType = cp.isPrimitiveType; + this.isModel = cp.isModel; + this.isContainer = cp.isContainer; + this.isString = cp.isString; + this.isNumeric = cp.isNumeric; + this.isInteger = cp.isInteger; + this.isLong = cp.isLong; + this.isNumber = cp.isNumber; + this.isFloat = cp.isFloat; + this.isDouble = cp.isDouble; + this.isDecimal = cp.isDecimal; + this.isByteArray = cp.isByteArray; + this.isBinary = cp.isBinary; + this.isFile = cp.isFile; + this.isBoolean = cp.isBoolean; + this.isDate = cp.isDate; // full-date notation as defined by RFC 3339, section 5.6, for example, 2017-07-21 + this.isDateTime = cp.isDateTime; // the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z + this.isUuid = cp.isUuid; + this.isUri = cp.isUri; + this.isEmail = cp.isEmail; + this.isFreeFormObject = cp.isFreeFormObject; + this.isAnyType = cp.isAnyType; + this.isArray = cp.isArray; + this.isMap = cp.isMap; + this.isEnum = cp.isEnum; + this.isReadOnly = cp.isReadOnly; + this.isWriteOnly = cp.isWriteOnly; + this.isNullable = cp.isNullable; + this.isSelfReference = cp.isSelfReference; + this.isCircularReference = cp.isCircularReference; + this.isDiscriminator = cp.isDiscriminator; + this._enum = cp._enum; + this.allowableValues = cp.allowableValues; + this.items = cp.items; + this.additionalProperties = cp.additionalProperties; + this.vars = cp.vars; + this.requiredVars = cp.requiredVars; + this.mostInnerItems = cp.mostInnerItems; + this.vendorExtensions = cp.vendorExtensions; + this.hasValidation = cp.hasValidation; + this.isInherited = cp.isInherited; + this.discriminatorValue = cp.discriminatorValue; + this.nameInLowerCase = cp.nameInLowerCase; + this.nameInCamelCase = cp.nameInCamelCase; + this.nameInSnakeCase = cp.nameInSnakeCase; + this.enumName = cp.enumName; + this.maxItems = cp.maxItems; + this.minItems = cp.minItems; + this.setMaxProperties(cp.getMaxProperties()); + this.setMinProperties(cp.getMinProperties()); + this.setUniqueItems(cp.getUniqueItems()); + this.isXmlAttribute = cp.isXmlAttribute; + this.xmlPrefix = cp.xmlPrefix; + this.xmlName = cp.xmlName; + this.xmlNamespace = cp.xmlNamespace; + this.isXmlWrapped = cp.isXmlWrapped; + } + + @Override + public boolean equals(Object o) { + boolean result = super.equals(o); + ExtendedCodegenProperty that = (ExtendedCodegenProperty) o; + return result && + isEntity == that.isEntity && + isUniqueId == that.isUniqueId && + keepAsJSObject == that.keepAsJSObject && + isReservedRecordField == that.isReservedRecordField && + Objects.equals(dataTypeAlternate, that.dataTypeAlternate); + } + + @Override + public int hashCode() { + int superHash = super.hashCode(); + return Objects.hash(superHash, dataTypeAlternate, isEntity, isUniqueId, keepAsJSObject, isReservedRecordField); + } + + @Override + public String toString() { + String superString = super.toString(); + final StringBuilder sb = new StringBuilder(superString); + sb.append(", dataTypeAlternate='").append(dataTypeAlternate).append('\''); + sb.append(", isEntity=").append(isEntity); + sb.append(", isUniqueId=").append(isUniqueId); + sb.append(", keepAsJSObject=").append(keepAsJSObject); + sb.append(", isReservedRecordField=").append(isReservedRecordField); + return sb.toString(); + } + } + + class ExtendedCodegenOperation extends CodegenOperation { + boolean hasReturnPassthroughVoid, returnTypeSupportsEntities, returnTypeIsModel, returnTypeIsArray; + String returnTypeAlternate, returnBaseTypeAlternate, returnPassthrough; + + public ExtendedCodegenOperation(CodegenOperation o) { + super(); + + this.responseHeaders.addAll(o.responseHeaders); + this.hasAuthMethods = o.hasAuthMethods; + this.hasConsumes = o.hasConsumes; + this.hasProduces = o.hasProduces; + this.hasParams = o.hasParams; + this.hasOptionalParams = o.hasOptionalParams; + this.hasRequiredParams = o.hasRequiredParams; + this.returnTypeIsPrimitive = o.returnTypeIsPrimitive; + this.returnSimpleType = o.returnSimpleType; + this.subresourceOperation = o.subresourceOperation; + this.isMap = o.isMap; + this.isArray = o.isArray; + this.isMultipart = o.isMultipart; + this.isResponseBinary = o.isResponseBinary; + this.isResponseFile = o.isResponseFile; + this.hasReference = o.hasReference; + this.isRestfulIndex = o.isRestfulIndex; + this.isRestfulShow = o.isRestfulShow; + this.isRestfulCreate = o.isRestfulCreate; + this.isRestfulUpdate = o.isRestfulUpdate; + this.isRestfulDestroy = o.isRestfulDestroy; + this.isRestful = o.isRestful; + this.isDeprecated = o.isDeprecated; + this.isCallbackRequest = o.isCallbackRequest; + this.uniqueItems = o.uniqueItems; + this.path = o.path; + this.operationId = o.operationId; + this.returnType = o.returnType; + this.returnFormat = o.returnFormat; + this.httpMethod = o.httpMethod; + this.returnBaseType = o.returnBaseType; + this.returnContainer = o.returnContainer; + this.summary = o.summary; + this.unescapedNotes = o.unescapedNotes; + this.notes = o.notes; + this.baseName = o.baseName; + this.defaultResponse = o.defaultResponse; + this.discriminator = o.discriminator; + this.consumes = o.consumes; + this.produces = o.produces; + this.prioritizedContentTypes = o.prioritizedContentTypes; + this.servers = o.servers; + this.bodyParam = o.bodyParam; + this.allParams = o.allParams; + this.bodyParams = o.bodyParams; + this.pathParams = o.pathParams; + this.queryParams = o.queryParams; + this.headerParams = o.headerParams; + this.formParams = o.formParams; + this.cookieParams = o.cookieParams; + this.requiredParams = o.requiredParams; + this.optionalParams = o.optionalParams; + this.authMethods = o.authMethods; + this.tags = o.tags; + this.responses = o.responses; + this.callbacks = o.callbacks; + this.imports = o.imports; + this.examples = o.examples; + this.requestBodyExamples = o.requestBodyExamples; + this.externalDocs = o.externalDocs; + this.vendorExtensions = o.vendorExtensions; + this.nickname = o.nickname; + this.operationIdOriginal = o.operationIdOriginal; + this.operationIdLowerCase = o.operationIdLowerCase; + this.operationIdCamelCase = o.operationIdCamelCase; + this.operationIdSnakeCase = o.operationIdSnakeCase; + } + + @Override + public boolean equals(Object o) { + boolean result = super.equals(o); + ExtendedCodegenOperation that = (ExtendedCodegenOperation) o; + return result && + hasReturnPassthroughVoid == that.hasReturnPassthroughVoid && + returnTypeSupportsEntities == that.returnTypeSupportsEntities && + returnTypeIsArray == that.returnTypeIsArray && + returnTypeIsModel == that.returnTypeIsModel && + Objects.equals(returnTypeAlternate, that.returnTypeAlternate) && + Objects.equals(returnBaseTypeAlternate, that.returnBaseTypeAlternate) && + Objects.equals(returnPassthrough, that.returnPassthrough); + } + + @Override + public int hashCode() { + int superHash = super.hashCode(); + return Objects.hash(superHash, returnPassthrough, hasReturnPassthroughVoid, returnTypeSupportsEntities, returnTypeIsArray, returnTypeIsModel, returnTypeAlternate, returnBaseTypeAlternate); + } + + @Override + public String toString() { + String superString = super.toString(); + final StringBuilder sb = new StringBuilder(superString); + sb.append(", hasReturnPassthroughVoid=").append(hasReturnPassthroughVoid); + sb.append(", returnTypeSupportsEntities=").append(returnTypeSupportsEntities); + sb.append(", returnTypeIsArray=").append(returnTypeIsArray); + sb.append(", returnTypeIsModel=").append(returnTypeIsModel); + sb.append(", returnTypeAlternate='").append(returnTypeAlternate).append('\''); + sb.append(", returnBaseTypeAlternate='").append(returnBaseTypeAlternate).append('\''); + sb.append(", returnPassthrough='").append(returnPassthrough).append('\''); + return sb.toString(); + } + } + + class ExtendedCodegenModel extends CodegenModel { + public Set modelImports = new TreeSet(); + public boolean isEntity; // Is a model containing an "id" property marked as isUniqueId + public String returnPassthrough; + public boolean hasReturnPassthroughVoid; + + public ExtendedCodegenModel(CodegenModel cm) { + super(); + + this.parent = cm.parent; + this.parentSchema = cm.parentSchema; + this.interfaces = cm.interfaces; + this.allParents = cm.allParents; + this.parentModel = cm.parentModel; + this.interfaceModels = cm.interfaceModels; + this.children = cm.children; + this.anyOf = cm.anyOf; + this.oneOf = cm.oneOf; + this.allOf = cm.allOf; + this.name = cm.name; + this.classname = cm.classname; + this.title = cm.title; + this.description = cm.description; + this.classVarName = cm.classVarName; + this.modelJson = cm.modelJson; + this.dataType = cm.dataType; + this.xmlPrefix = cm.xmlPrefix; + this.xmlNamespace = cm.xmlNamespace; + this.xmlName = cm.xmlName; + this.classFilename = cm.classFilename; + this.unescapedDescription = cm.unescapedDescription; + this.discriminator = cm.discriminator; + this.defaultValue = cm.defaultValue; + this.arrayModelType = cm.arrayModelType; + this.isAlias = cm.isAlias; + this.isString = cm.isString; + this.isInteger = cm.isInteger; + this.isLong = cm.isLong; + this.isNumber = cm.isNumber; + this.isNumeric = cm.isNumeric; + this.isFloat = cm.isFloat; + this.isDouble = cm.isDouble; + this.isDate = cm.isDate; + this.isDateTime = cm.isDateTime; + this.vars = cm.vars; + this.allVars = cm.allVars; + this.requiredVars = cm.requiredVars; + this.optionalVars = cm.optionalVars; + this.readOnlyVars = cm.readOnlyVars; + this.readWriteVars = cm.readWriteVars; + this.parentVars = cm.parentVars; + this.allowableValues = cm.allowableValues; + this.mandatory = cm.mandatory; + this.allMandatory = cm.allMandatory; + this.imports = cm.imports; + this.hasVars = cm.hasVars; + this.emptyVars = cm.emptyVars; + this.hasMoreModels = cm.hasMoreModels; + this.hasEnums = cm.hasEnums; + this.isEnum = cm.isEnum; + this.isNullable = cm.isNullable; + this.hasRequired = cm.hasRequired; + this.hasOptional = cm.hasOptional; + this.isArray = cm.isArray; + this.hasChildren = cm.hasChildren; + this.isMap = cm.isMap; + this.isDeprecated = cm.isDeprecated; + this.hasOnlyReadOnly = cm.hasOnlyReadOnly; + this.externalDocumentation = cm.externalDocumentation; + + this.vendorExtensions = cm.vendorExtensions; + this.additionalPropertiesType = cm.additionalPropertiesType; + this.isAdditionalPropertiesTrue = cm.isAdditionalPropertiesTrue; + this.setMaxProperties(cm.getMaxProperties()); + this.setMinProperties(cm.getMinProperties()); + this.setUniqueItems(cm.getUniqueItems()); + this.setMaxItems(cm.getMaxItems()); + this.setMinItems(cm.getMinItems()); + this.setMaxLength(cm.getMaxLength()); + this.setMinLength(cm.getMinLength()); + this.setExclusiveMinimum(cm.getExclusiveMinimum()); + this.setExclusiveMaximum(cm.getExclusiveMaximum()); + this.setMinimum(cm.getMinimum()); + this.setMaximum(cm.getMaximum()); + this.setPattern(cm.getPattern()); + this.setMultipleOf(cm.getMultipleOf()); + this.setItems(cm.getItems()); + this.setAdditionalProperties(cm.getAdditionalProperties()); + this.setIsModel(cm.getIsModel()); + } + + public Set getModelImports() { + return modelImports; + } + + public void setModelImports(Set modelImports) { + this.modelImports = modelImports; + } + + @Override + public boolean equals(Object o) { + boolean result = super.equals(o); + ExtendedCodegenModel that = (ExtendedCodegenModel) o; + return result && + isEntity == that.isEntity && + hasReturnPassthroughVoid == that.hasReturnPassthroughVoid && + Objects.equals(returnPassthrough, that.returnPassthrough) && + Objects.equals(modelImports, that.modelImports); + + } + + @Override + public int hashCode() { + int superHash = super.hashCode(); + return Objects.hash(superHash, isEntity, returnPassthrough, hasReturnPassthroughVoid, getModelImports()); + } + + @Override + public String toString() { + String superString = super.toString(); + final StringBuilder sb = new StringBuilder(superString); + sb.append(", modelImports=").append(modelImports); + sb.append(", isEntity=").append(isEntity); + sb.append(", returnPassthrough='").append(returnPassthrough).append('\''); + sb.append(", hasReturnPassthroughVoid=").append(hasReturnPassthroughVoid); + return sb.toString(); + } + + } + } diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesRecord.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesRecord.mustache new file mode 100644 index 00000000000..5860cc04b37 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesRecord.mustache @@ -0,0 +1,26 @@ +import {Map, Record, RecordOf} from 'immutable'; + +import { +{{#models}} +{{#model}} +{{#isEntity}} + {{classname}}RecordEntity, +{{/isEntity}} +{{/model}} +{{/models}} +} from "./models" + +export const ApiEntitiesRecordProps = { + recType: "ApiEntitiesRecord" as "ApiEntitiesRecord", +{{#models}} +{{#model}} +{{#isEntity}} + {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}: ({{classname}}RecordEntity(), Map()), +{{/isEntity}} +{{/model}} +{{/models}} +}; + +export type ApiEntitiesRecordPropsType = typeof ApiEntitiesRecordProps; +export const ApiEntitiesRecord = Record(ApiEntitiesRecordProps, ApiEntitiesRecordProps.recType); +export type ApiEntitiesRecord = RecordOf; \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesReducer.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesReducer.mustache new file mode 100644 index 00000000000..9f607ac090f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesReducer.mustache @@ -0,0 +1,21 @@ +import {ApiEntitiesRecord} from "./ApiEntitiesRecord"; +import {ReducerBuilder} from "redux-ts-simple"; +import {normalizedEntities} from "./runtimeSagasAndRecords"; + +export const ApiEntitiesReducer = new ReducerBuilder(ApiEntitiesRecord()) + .on(normalizedEntities, (state, action): ApiEntitiesRecord => { + const {entities} = action.payload; + return state.withMutations(mutableState => { + for (const entityKey in entities) { + const entityMap = entities[entityKey]; + const currentEntityMap = mutableState.get(entityKey as any); + if (currentEntityMap) { + let mergedEntityMap = currentEntityMap.mergeDeep(entityMap); + if (!mergedEntityMap.equals(currentEntityMap)) { + mutableState.set(entityKey as any, mergedEntityMap); + } + } + } + }); + }) + .build(); \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesSelectors.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesSelectors.mustache new file mode 100644 index 00000000000..9eaffec0dfe --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesSelectors.mustache @@ -0,0 +1,5 @@ +export let getApiEntitiesState: (state: any) => any = (state: any) => state.app.apiEntities; + +export function setApiEntitiesStateGetter(getter: (state: any) => any) { // Use this to customize the location where you have placed your ApiEntitiesRecord in your project. + getApiEntitiesState = getter; +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/allSagas.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/allSagas.mustache new file mode 100644 index 00000000000..018140fc886 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/allSagas.mustache @@ -0,0 +1,19 @@ +import {all, fork} from "redux-saga/effects"; + +import { +{{#apiInfo}} +{{#apis}} + {{#lambda.camelcase}}{{classFilename}}{{/lambda.camelcase}}AllSagas, +{{/apis}} +{{/apiInfo}} +} from "./"; + +export function *allApiSagas() { + yield all([ +{{#apiInfo}} +{{#apis}} + fork({{#lambda.camelcase}}{{classFilename}}{{/lambda.camelcase}}AllSagas), +{{/apis}} +{{/apiInfo}} + ]); +} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/apis.index.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/apis.index.mustache index 6286332d7bc..44f8c989936 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/apis.index.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/apis.index.mustache @@ -1,7 +1,14 @@ +{{#useSagaAndRecords}} +export * from './SagaApiManager' +export * from './allSagas' +{{/useSagaAndRecords}} {{#apiInfo}} {{#apis}} {{#operations}} export * from './{{ classFilename }}'; +{{#useSagaAndRecords}} +export * from './{{{ classFilename }}}Sagas'; +{{/useSagaAndRecords}} {{/operations}} {{/apis}} {{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/index.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/index.mustache index e548c9df6b2..ede27a38747 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/index.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/index.mustache @@ -1,4 +1,10 @@ export * from './runtime'; +{{#useSagaAndRecords}} +export * from './runtimeSagasAndRecords'; +export * from './ApiEntitiesRecord'; +export * from './ApiEntitiesReducer'; +export * from './ApiEntitiesSelectors'; +{{/useSagaAndRecords}} {{#apiInfo}} {{#apis.0}} export * from './apis'; diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/models.index.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/models.index.mustache index 7331df67ca9..1be5a347b38 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/models.index.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/models.index.mustache @@ -2,7 +2,13 @@ {{#model}} {{^withoutRuntimeChecks}} export * from './{{{ classFilename }}}'; -{{/withoutRuntimeChecks}}{{#withoutRuntimeChecks}} +{{#useSagaAndRecords}} +{{^isEnum}} +export * from './{{{ classFilename }}}Record'; +{{/isEnum}} +{{/useSagaAndRecords}} +{{/withoutRuntimeChecks}} +{{#withoutRuntimeChecks}} {{#isEnum}} {{>modelEnumInterfaces}} {{/isEnum}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/package.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/package.mustache index b7c3d544af1..c082bbf3982 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/package.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/package.mustache @@ -3,14 +3,27 @@ "version": "{{npmVersion}}", "description": "OpenAPI client for {{npmName}}", "author": "OpenAPI-Generator", +{{#packageAsSourceOnlyLibrary}} + "main": "./index.ts", +{{/packageAsSourceOnlyLibrary}} +{{^packageAsSourceOnlyLibrary}} "main": "./dist/index.js", "typings": "./dist/index.d.ts", "scripts": { - "build": "tsc", + "build": "tsc"{{^sagasAndRecords}}, "prepare": "npm run build" +{{/sagasAndRecords}} }, +{{/packageAsSourceOnlyLibrary}} "devDependencies": { - "typescript": "^{{#typescriptThreePlus}}3.6{{/typescriptThreePlus}}{{^typescriptThreePlus}}2.4{{/typescriptThreePlus}}" +{{#sagasAndRecords}} + "immutable": "^4.0.0-rc.12", + "normalizr": "^3.6.1", + "redux-saga": "^1.1.3", + "redux-ts-simple": "^3.2.0", + "reselect": "^4.0.0", +{{/sagasAndRecords}} + "typescript": "^{{#typescriptThreePlus}}3.9.5{{/typescriptThreePlus}}{{^typescriptThreePlus}}2.4{{/typescriptThreePlus}}" }{{#npmRepository}},{{/npmRepository}} {{#npmRepository}} "publishConfig": { diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/recordGeneric.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/recordGeneric.mustache new file mode 100644 index 00000000000..b418276e452 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/recordGeneric.mustache @@ -0,0 +1,271 @@ +import {ApiRecordUtils, knownRecordFactories{{#returnPassthrough}}, appFromJS, NormalizedRecordEntities{{/returnPassthrough}}} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + {{classname}}, +{{#vars}} +{{#isEnum}} + {{classname}}{{enumName}}, +{{/isEnum}} +{{/vars}} +} from './{{classname}}'; + +{{#imports}} +import { + {{{.}}}, +} from './{{{.}}}'; +{{/imports}} + +{{#modelImports}} +import { + {{{.}}}Record, + {{#lambda.camelcase}}{{.}}{{/lambda.camelcase}}RecordUtils +} from './{{{.}}}Record'; +{{/modelImports}} + +export const {{classname}}RecordProps = { + recType: "{{classname}}ApiRecord" as "{{classname}}ApiRecord", +{{#vars}} + {{#isArray}} + {{#items.isModel}} + {{#keepAsJSObject}} + {{name}}: {{#required}}new {{{dataType}}}(){{/required}}{{^required}}null as {{{dataType}}} | null{{/required}}, + {{/keepAsJSObject}} + {{^keepAsJSObject}} + {{name}}: ({{{items.dataType}}}Record(), {{#required}}{{{defaultValue}}}{{/required}}{{^required}}null as {{{dataTypeAlternate}}} | null{{/required}}), + {{/keepAsJSObject}} + {{/items.isModel}} + {{^items.isModel}} + {{name}}: {{#required}}{{{defaultValue}}}{{/required}}{{^required}}null as {{{dataTypeAlternate}}} | null{{/required}}, + {{/items.isModel}} + {{/isArray}} + {{#isModel}} + {{#keepAsJSObject}} + {{name}}: {{#required}}{} as any as {{{dataType}}}{{/required}}{{^required}}null as {{{dataType}}} | null{{/required}}, + {{/keepAsJSObject}} + {{^keepAsJSObject}} + {{name}}: {{#required}}{{{defaultValue}}}{{/required}}{{^required}}({{{defaultValue}}}, null as {{{dataTypeAlternate}}} | null){{/required}}, + {{/keepAsJSObject}} + {{/isModel}} + {{^isArray}} + {{^isModel}} + {{name}}: {{#required}}{{{defaultValue}}}{{/required}}{{^required}}null as {{{dataTypeAlternate}}} | null{{/required}}, + {{/isModel}} + {{/isArray}} +{{/vars}} +}; + +export type {{classname}}RecordPropsType = typeof {{classname}}RecordProps; +export const {{classname}}Record = Record({{classname}}RecordProps, {{classname}}RecordProps.recType); +export type {{classname}}Record = RecordOf<{{classname}}RecordPropsType>; + +knownRecordFactories.set({{classname}}RecordProps.recType, {{classname}}Record); + +{{#isEntity}} +export const {{classname}}RecordEntityProps = { + ...{{classname}}RecordProps, + recType: "{{classname}}ApiRecordEntity" as "{{classname}}ApiRecordEntity", +{{#vars}} + {{#isEntity}} + {{^keepAsJSObject}} + {{name}}: {{#required}}"-1"{{/required}}{{^required}}null as string | null{{/required}}, + {{/keepAsJSObject}} + {{/isEntity}} + {{#isArray}} + {{#items.isEntity}} + {{^keepAsJSObject}} + {{name}}: {{#required}}List(){{/required}}{{^required}}null as List | null{{/required}}, + {{/keepAsJSObject}} + {{/items.isEntity}} + {{/isArray}} +{{/vars}} +}; + +export type {{classname}}RecordEntityPropsType = typeof {{classname}}RecordEntityProps; +export const {{classname}}RecordEntity = Record({{classname}}RecordEntityProps, {{classname}}RecordEntityProps.recType); +export type {{classname}}RecordEntity = RecordOf<{{classname}}RecordEntityPropsType>; + +knownRecordFactories.set({{classname}}RecordEntityProps.recType, {{classname}}RecordEntity); +{{/isEntity}} + +class {{classname}}RecordUtils extends ApiRecordUtils<{{classname}}, {{classname}}Record> { + public normalize(apiObject: {{classname}}, asEntity?: boolean): {{classname}} { + (apiObject as any).recType = {{#isEntity}}asEntity ? {{classname}}RecordEntityProps.recType : {{/isEntity}}{{classname}}RecordProps.recType; +{{#vars}} + {{#isUniqueId}} + {{^required}}if (apiObject.{{name}}) { {{/required}}(apiObject as any).{{name}} = apiObject.{{name}}.{{#isArray}}map(item => item.{{/isArray}}toString(){{#isArray}}){{/isArray}};{{^required}} } {{/required}} + {{/isUniqueId}} + {{^keepAsJSObject}} + {{#isModel}} + {{^required}}if (apiObject.{{name}}) { {{/required}}{{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.normalize(apiObject.{{name}});{{^required}} } {{/required}} + {{/isModel}} + {{#isArray}} + {{#items.isModel}} + {{^required}}if (apiObject.{{name}}) { {{/required}}{{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.normalizeArray(apiObject.{{name}});{{^required}} } {{/required}} + {{/items.isModel}} + {{/isArray}} + {{/keepAsJSObject}} +{{/vars}} + return apiObject; + } +{{#isEntity}} + + public getSchema(): Schema { + return new schema.Entity("{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}", { +{{#vars}} + {{#isEntity}} + {{^keepAsJSObject}} + {{name}}: {{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.getSchema(), + {{/keepAsJSObject}} + {{/isEntity}} + {{#isArray}} + {{#items.isEntity}} + {{^keepAsJSObject}} + {{name}}: [{{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.getSchema()], + {{/keepAsJSObject}} + {{/items.isEntity}} + {{/isArray}} +{{/vars}} + }); + } + + public *toInlined(entityId?: string | null) { + if (!entityId) {return undefined; } + const entity = yield select(apiEntity{{classname}}Selector, {id: entityId}); + if (!entity) {return undefined; } + + const { + recType, +{{#vars}} +{{#isEntity}} +{{^keepAsJSObject}} + {{name}}: {{name}}_original, +{{/keepAsJSObject}} +{{/isEntity}} +{{#isArray}} +{{#items.isEntity}} +{{^keepAsJSObject}} + {{name}}: {{name}}_original, +{{/keepAsJSObject}} +{{/items.isEntity}} +{{/isArray}} +{{/vars}} + ...unchangedProperties + } = entity; + + const entityProperties = { +{{#vars}} +{{#isEntity}} +{{^keepAsJSObject}} + {{name}}: {{^required}}entity.{{name}} ? {{/required}}yield call({{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.toInlined, entity.{{name}}){{^required}} : null{{/required}}, +{{/keepAsJSObject}} +{{/isEntity}} +{{#isArray}} +{{#items.isEntity}} +{{^keepAsJSObject}} + {{name}}: {{^required}}entity.{{name}} ? {{/required}}yield call({{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.toInlinedArray, entity.{{name}}){{^required}} : null{{/required}}, +{{/keepAsJSObject}} +{{/items.isEntity}} +{{/isArray}} +{{/vars}} + } + + return {{classname}}Record({ + ...unchangedProperties, + ...entityProperties + }); + } + + public *toInlinedArray(entityIds: List | null) { + if (!entityIds) {return null; } + let entities = List<{{classname}}Record>(); + for (let entityIndex = 0; entityIndex < entityIds.count(); entityIndex++) { + const entity = yield call(this.toInlined, entityIds.get(entityIndex)); + if (entity) { + entities.push(entity); + } + } + return entities; + } +{{/isEntity}} + + public toApi(record: {{classname}}Record): {{classname}} { + const apiObject = super.toApi(record); +{{#vars}} + {{#isUniqueId}} + {{^required}}if (record.{{name}}) { {{/required}}apiObject.{{name}} = {{#isArray}}record.{{name}}.map(item => parseFloat(item)).toArray(){{/isArray}}{{^isArray}}parseFloat(record.{{name}}){{/isArray}};{{^required}} } {{/required}} + {{/isUniqueId}} + {{^keepAsJSObject}} + {{#isModel}} + {{^required}}if (record.{{name}}) { {{/required}}apiObject.{{name}} = {{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.toApi(record.{{name}});{{^required}} } {{/required}} + {{/isModel}} + {{#isArray}} + {{#items.isModel}} + {{^required}}if (record.{{name}}) { {{/required}}apiObject.{{name}} = {{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.toApiArray(record.{{name}});{{^required}} } {{/required}} + {{/items.isModel}} + {{/isArray}} + {{/keepAsJSObject}} +{{/vars}} + return apiObject; + } +{{#returnPassthrough}} +{{#vars.1}} + + public fromApiPassthrough(apiObject: {{classname}}): {{{dataTypeAlternate}}} { + {{#isModel}} + if (!apiObject.{{{returnPassthrough}}}) {return {{{defaultValue}}}; } + const normalizedApiObject = {{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.normalize(apiObject.{{{returnPassthrough}}}); + return appFromJS(normalizedApiObject); + {{/isModel}} + {{#isArray}} + {{#items.isModel}} + if (!apiObject.{{{returnPassthrough}}}) {return {{{defaultValue}}}; } + const normalizedApiObject = {{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.normalizeArray(apiObject.{{{returnPassthrough}}}); + return appFromJS(normalizedApiObject); + {{/items.isModel}} + {{^items.isModel}} + return appFromJS(apiObject.{{{returnPassthrough}}}); + {{/items.isModel}} + {{/isArray}} + {{^isModel}} + {{^isArray}} + return apiObject.{{{returnPassthrough}}}!; + {{/isArray}} + {{/isModel}} + } + + public fromApiPassthroughAsEntities(apiObject: {{classname}}): NormalizedRecordEntities { + {{#isEntity}} + if (!apiObject.{{{returnPassthrough}}}) {return {entities: {}, result: List()}; } + return ApiRecordUtils.toNormalizedRecordEntities({{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.normalizeArrayAsEntities([apiObject.{{{returnPassthrough}}}]), true); + {{/isEntity}} + {{#isArray}} + {{#items.isEntity}} + if (!apiObject.{{{returnPassthrough}}}) {return {entities: {}, result: List()}; } + return ApiRecordUtils.toNormalizedRecordEntities({{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.normalizeArrayAsEntities(apiObject.{{{returnPassthrough}}}), true); + {{/items.isEntity}} + {{^items.isEntity}} + console.log("entities revival not supported on this response"); + return {entities: {}, result: List()}; + {{/items.isEntity}} + {{/isArray}} + {{^isEntity}} + {{^isArray}} + console.log("entities revival not supported on this response"); + return {entities: {}, result: List()}; + {{/isArray}} + {{/isEntity}} + } +{{/vars.1}} +{{/returnPassthrough}} +} + +export const {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}RecordUtils = new {{classname}}RecordUtils(); + +{{#isEntity}} +export const apiEntities{{classname}}Selector = (state: any) => getApiEntitiesState(state).{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} as Map; +export const apiEntity{{classname}}Selector = (state: any, {id}: {id?: string | null}) => id ? apiEntities{{classname}}Selector(state).get(id) : undefined; +{{/isEntity}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/records.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/records.mustache new file mode 100644 index 00000000000..5c8a0ad348a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/records.mustache @@ -0,0 +1,15 @@ +{{#models}} +{{#model}} +{{#isEnum}} +// This file is not needed and was generated only because of how codegen is built... Enums do not need to be converted to Records and can be used directly. +{{/isEnum}} +{{^isEnum}} +{{^oneOf}} +/* tslint:disable */ +/* eslint-disable */ +{{>licenseInfo}} +{{>recordGeneric}} +{{/oneOf}} +{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/runtimeSagasAndRecords.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/runtimeSagasAndRecords.mustache new file mode 100644 index 00000000000..e182521fac3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/runtimeSagasAndRecords.mustache @@ -0,0 +1,120 @@ +/* tslint:disable */ +/* eslint-disable */ + +import {fromJS as originalFromJS, isIndexed, List, Map as ImmMap, RecordOf} from 'immutable'; +import {normalize, NormalizedSchema, schema, Schema} from "normalizr"; +import {ActionDefinition, createAction} from "redux-ts-simple"; + +export const knownRecordFactories = new Map(); +export const knownIndexedSetByKey: (string | number)[] = []; + +export function appFromJS(any: any): any { + return originalFromJS(any, (key, value) => { + if (isIndexed(value)) { + return knownIndexedSetByKey.indexOf(key) !== -1 ? value.toSet() : value.toList(); + } // we're reviving an array -> it's a List + const MatchingType = knownRecordFactories.get(value.get('recType')) as { new(input?: any): any }; // check if we know a Record with this type + if (MatchingType) { + return new MatchingType(value); + } + return value.toMap(); // no matching Record type found -> it's a plain old Map + }); +} + +export type NormalizedRecordEntity = NormalizedSchema<{ [key: string]: Map> }, string>; +export type NormalizedRecordEntities = NormalizedSchema<{ [key: string]: Map> }, List>; + +export abstract class ApiRecordUtils> { + public abstract normalize(apiObject: TAPI, asEntity?: boolean): any; + + public getSchema(): Schema { + console.log("Entity mode not supported on this record."); + return new schema.Entity("entityNotSupported"); + } + + public normalizeArray(apiObjectArray: TAPI[], asEntity?: boolean): TAPI[] { + apiObjectArray.forEach(apiObject => this.normalize(apiObject, asEntity)); + return apiObjectArray; + } + + public normalizeAsEntities(apiObject: TAPI): NormalizedSchema { + const normalized = this.normalize(apiObject, true); + return normalize(normalized, this.getSchema()); + } + + public normalizeArrayAsEntities(apiObject: TAPI[]): NormalizedSchema { + const normalized = this.normalizeArray(apiObject, true); + return normalize(normalized, new schema.Array(this.getSchema())); + } + + public fromApi(apiObject: TAPI): TREC { + return appFromJS(this.normalize(apiObject)); + } + + public fromApiArray(apiObjectArray: TAPI[]): List { + this.normalizeArray(apiObjectArray); + return appFromJS(apiObjectArray); + } + + public fromApiAsEntities(apiObject: TAPI): NormalizedRecordEntity { + return ApiRecordUtils.toNormalizedRecordEntities(this.normalizeAsEntities(apiObject), false); + } + + public fromApiArrayAsEntities(apiObject: TAPI[]): NormalizedRecordEntities { + return ApiRecordUtils.toNormalizedRecordEntities(this.normalizeArrayAsEntities(apiObject), true); + } + + public toApi(record: TREC): TAPI { + const apiObject = record.toJS(); + delete apiObject.recType; + return apiObject; + } + + public toApiArray(records: List): TAPI[] { + return records.map(record => this.toApi(record)).toArray(); + } + + public static toNormalizedRecordEntities(normalizedAsEntities: any, forArray: boolean) { + const entities = normalizedAsEntities.entities; + for (const entityKey of Object.keys(entities)) { + entities[entityKey] = appFromJS(entities[entityKey]); + } + normalizedAsEntities.result = appFromJS(normalizedAsEntities.result || (forArray ? "" : [])); + return normalizedAsEntities; + } +} + +export const allApiActionFailures: SagaActionDefinition[] = []; + +export interface BaseEntitySupportPayloadApiAction { + toInlined?: boolean; + toEntities?: boolean; + markErrorsAsHandled?: boolean; +} + +export interface BasePayloadApiAction { + markErrorsAsHandled?: boolean; +} + +export interface SagaActionDefinition extends ActionDefinition { + toString: () => string; +} + +export function createSagaAction(type: string, options?: { doNotAutoRegisterFailure?: boolean, namespace?: string }): SagaActionDefinition { + const {doNotAutoRegisterFailure, namespace} = options || {} as any; + let actionDefinition = createAction(namespace ? `${namespace}-${type}` : type); + (actionDefinition as any).toString = () => actionDefinition.type; + if (type.endsWith("Failure") && !doNotAutoRegisterFailure) { + allApiActionFailures.push(actionDefinition); + } + return actionDefinition; +} + +export let apiCall: any>(context: Ctx, fn: Fn, ...args: Parameters) => Generator; + +export function setApiCall(apiCallFc: any>(context: Ctx, fn: Fn, ...args: Parameters) => Generator) { + console.log("init apiCall"); + apiCall = apiCallFc; +} + +export const normalizedEntities = createSagaAction("normalizedEntities"); \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/sagaApiManager.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/sagaApiManager.mustache new file mode 100644 index 00000000000..af6fa7fdd71 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/sagaApiManager.mustache @@ -0,0 +1,36 @@ +import { + Configuration, + ConfigurationParameters, +} from "../"; + +import { +{{#apiInfo}} +{{#apis}} + {{classFilename}}, +{{/apis}} +{{/apiInfo}} +} from "./"; + +export class Api { +{{#apiInfo}} +{{#apis}} + public static {{#lambda.camelcase}}{{classFilename}}{{/lambda.camelcase}}: {{classFilename}}; +{{/apis}} +{{/apiInfo}} + + public static init(apiBasePath: string) { + const apiBaseConfig: ConfigurationParameters = { + basePath: apiBasePath, + credentials: "include", + headers: { + 'Cache-Control': 'no-cache, no-store' // this is needed to prevent stalling issues in Chrome. Also it is a good behavior for api calls. + } + }; + +{{#apiInfo}} +{{#apis}} + Api.{{#lambda.camelcase}}{{classFilename}}{{/lambda.camelcase}} = new {{classFilename}}(new Configuration(apiBaseConfig)); +{{/apis}} +{{/apiInfo}} + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/sagas.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/sagas.mustache new file mode 100644 index 00000000000..ac5581582d8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/sagas.mustache @@ -0,0 +1,239 @@ +/* tslint:disable */ +/* eslint-disable */ +{{>licenseInfo}} + +import {Api} from './'; +import {List} from 'immutable'; +import {all, fork, put, takeLatest} from "redux-saga/effects"; +import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords"; +import {Action} from "redux-ts-simple"; + +{{#imports.0}} +import { + {{#imports}} + {{className}}, + {{className}}Record, + {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}RecordUtils, + {{/imports}} + {{#passthroughImports}} + {{.}}, + {{/passthroughImports}} +} from '../models'; +{{/imports.0}} +{{#hasEnums}} +{{#operations}} +{{#operation}} +{{#allParams}} +{{#isEnum}} + +import { + {{operationIdCamelCase}}{{enumName}}, +} from './{{classname}}'; +{{/isEnum}} +{{/allParams}} +{{/operation}} +{{/operations}} +{{/hasEnums}} + +const createSagaAction = (type: string) => originalCreateSagaAction(type, {namespace: "api_{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}"}); + +export const {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}SagaMap = new Map Generator>([ +{{#operations}} + {{#operation}} + ["{{nickname}}", {{nickname}}Saga], + {{/operation}} +{{/operations}} + ] +); + +export function *{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}AllSagas() { + yield all([...{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}SagaMap.values()].map(actionSaga => fork(actionSaga))); +} + +{{#operations}} +{{#operation}} +//region {{nickname}} + +{{#returnTypeSupportsEntities}} +export interface Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}} extends {{#allParams.0}}Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}}Request, {{/allParams.0}}BaseEntitySupportPayloadApiAction { +} +{{/returnTypeSupportsEntities}} +{{^returnTypeSupportsEntities}} +export interface Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}} extends {{#allParams.0}}Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}}Request, {{/allParams.0}}BasePayloadApiAction { +} +{{/returnTypeSupportsEntities}} + +{{#allParams.0}} +export interface Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}}Request { +{{#allParams}} + {{paramName}}{{^required}}?{{/required}}: {{{dataTypeAlternate}}}; +{{/allParams}} +} +{{/allParams.0}} + +export const {{nickname}}Request = createSagaAction<{{#allParams.0}}Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}}Request{{/allParams.0}}{{^allParams.0}}void{{/allParams.0}}>("{{nickname}}Request"); +{{#returnType}} +export const {{nickname}}Success = createSagaAction<{{#hasReturnPassthroughVoid}}void{{/hasReturnPassthroughVoid}}{{^hasReturnPassthroughVoid}}{{{returnTypeAlternate}}}{{/hasReturnPassthroughVoid}}>("{{nickname}}Success"); +{{#returnTypeSupportsEntities}} +export const {{nickname}}Success_Entities = createSagaAction("{{nickname}}Success_Entities"); +{{/returnTypeSupportsEntities}} +{{/returnType}} +{{^returnType}} +export const {{nickname}}Success = createSagaAction("{{nickname}}Success"); +{{/returnType}} +export const {{nickname}}Failure = createSagaAction<{error: any, requestPayload: Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}}}>("{{nickname}}Failure"); + +export const {{nickname}} = createSagaAction("{{nickname}}"); + +export function *{{nickname}}Saga() { + yield takeLatest({{nickname}}, {{nickname}}SagaImp); +} + +export function *{{nickname}}SagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { +{{#returnTypeSupportsEntities}} + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; +{{/returnTypeSupportsEntities}} +{{#allParams.0}} + const { +{{#allParams}} + {{paramName}}, +{{/allParams}} + } = _payloadRest_; +{{/allParams.0}} + + yield put({{nickname}}Request({{#allParams.0}}{{#returnTypeSupportsEntities}}requestPayload{{/returnTypeSupportsEntities}}{{^returnTypeSupportsEntities}}_action_.payload{{/returnTypeSupportsEntities}}{{/allParams.0}})); + + const response{{#returnType}}: Required<{{{returnType}}}>{{/returnType}} = yield apiCall(Api.{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}, Api.{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.{{nickname}}, +{{#allParams.0}} +{{#allParams}} +{{#isUniqueId}} +{{#isArray}} + {{^required}}{{paramName}} ? {{/required}}{{paramName}}.map(p => parseFloat(p)).toArray(){{^required}} : undefined{{/required}}, +{{/isArray}} +{{^isArray}} + {{^required}}{{paramName}} ? {{/required}}parseFloat({{paramName}}){{^required}} : undefined{{/required}}, +{{/isArray}} +{{/isUniqueId}} +{{^isUniqueId}} +{{#isArray}} +{{#items.isModel}} + {{^required}}{{paramName}} ? {{/required}}{{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.toApiArray({{paramName}}){{^required}} : undefined{{/required}}, +{{/items.isModel}} +{{^items.isModel}} + {{^required}}{{paramName}} ? {{/required}}{{paramName}}.toJS(){{^required}} : undefined{{/required}}, +{{/items.isModel}} +{{/isArray}} +{{#isModel}} + {{^required}}{{paramName}} ? {{/required}}{{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.toApi({{paramName}}){{^required}} : undefined{{/required}}, +{{/isModel}} +{{^isArray}} +{{^isModel}} + {{paramName}}, +{{/isModel}} +{{/isArray}} +{{/isUniqueId}} +{{/allParams}} +{{/allParams.0}} + ); + +{{#returnType}} +{{^hasReturnPassthroughVoid}} + let successReturnValue: any = undefined; +{{/hasReturnPassthroughVoid}} +{{/returnType}} +{{#returnTypeSupportsEntities}} + if (toEntities) { +{{#returnPassthrough}} + successReturnValue = {{#lambda.camelcase}}{{{returnType}}}{{/lambda.camelcase}}RecordUtils.fromApiPassthroughAsEntities(response); +{{/returnPassthrough}} +{{^hasReturnPassthroughVoid}} +{{^returnPassthrough}} +{{#returnTypeIsArray}} +{{#returnTypeAlternate}} + successReturnValue = {{#lambda.camelcase}}{{returnBaseTypeAlternate}}{{/lambda.camelcase}}Utils.fromApiArrayAsEntities(response); +{{/returnTypeAlternate}} +{{/returnTypeIsArray}} +{{#returnTypeIsModel}} + successReturnValue = {{#lambda.camelcase}}{{returnTypeAlternate}}{{/lambda.camelcase}}Utils.fromApiArrayAsEntities([response]); +{{/returnTypeIsModel}} +{{/returnPassthrough}} +{{/hasReturnPassthroughVoid}} + yield put(normalizedEntities(successReturnValue)); + yield put({{nickname}}Success_Entities(successReturnValue)); + } + if (toInlined) { +{{/returnTypeSupportsEntities}} +{{#returnType}} +{{#returnPassthrough}} + successReturnValue = {{#lambda.camelcase}}{{{returnType}}}{{/lambda.camelcase}}RecordUtils.fromApiPassthrough(response); + yield put({{nickname}}Success(successReturnValue)); +{{/returnPassthrough}} +{{#hasReturnPassthroughVoid}} + yield put({{nickname}}Success()); +{{/hasReturnPassthroughVoid}} +{{^hasReturnPassthroughVoid}} +{{^returnPassthrough}} +{{#returnTypeIsArray}} +{{#returnTypeAlternate}} + successReturnValue = {{#lambda.camelcase}}{{returnBaseTypeAlternate}}{{/lambda.camelcase}}Utils.fromApiArray(response); + yield put({{nickname}}Success(successReturnValue)); +{{/returnTypeAlternate}} +{{/returnTypeIsArray}} +{{#returnTypeIsModel}} + successReturnValue = {{#lambda.camelcase}}{{returnTypeAlternate}}{{/lambda.camelcase}}Utils.fromApi(response); + yield put({{nickname}}Success(successReturnValue)); +{{/returnTypeIsModel}} +{{^returnTypeIsArray}} +{{^returnTypeIsModel}} + yield put({{nickname}}Success(response)); +{{/returnTypeIsModel}} +{{/returnTypeIsArray}} +{{/returnPassthrough}} +{{/hasReturnPassthroughVoid}} +{{/returnType}} +{{^returnType}} + yield put({{nickname}}Success()); +{{/returnType}} +{{#returnTypeSupportsEntities}} + } +{{/returnTypeSupportsEntities}} + +{{#returnType}} +{{#returnPassthrough}} + return successReturnValue; +{{/returnPassthrough}} +{{#hasReturnPassthroughVoid}} + return undefined; +{{/hasReturnPassthroughVoid}} +{{^hasReturnPassthroughVoid}} +{{^returnPassthrough}} +{{#returnTypeIsArray}} +{{#returnTypeAlternate}} + return successReturnValue; +{{/returnTypeAlternate}} +{{/returnTypeIsArray}} +{{#returnTypeIsModel}} + return successReturnValue; +{{/returnTypeIsModel}} +{{^returnTypeIsArray}} +{{^returnTypeIsModel}} + return response; +{{/returnTypeIsModel}} +{{/returnTypeIsArray}} +{{/returnPassthrough}} +{{/hasReturnPassthroughVoid}} +{{/returnType}} +{{^returnType}} + return undefined; +{{/returnType}} + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put({{nickname}}Failure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +{{/operation}} +{{/operations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/sourceLibraryIndex.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/sourceLibraryIndex.mustache new file mode 100644 index 00000000000..8879d7a13f3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/sourceLibraryIndex.mustache @@ -0,0 +1 @@ +export * from './src'; \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/tsconfig.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/tsconfig.mustache index 420c3a44f88..a8778b09659 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/tsconfig.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/tsconfig.mustache @@ -2,6 +2,9 @@ "compilerOptions": { "declaration": true, "target": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}es5{{/supportsES6}}", +{{#sagasAndRecords}} + "strict": true, +{{/sagasAndRecords}} "module": "commonjs", "moduleResolution": "node", "outDir": "dist", diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java index d4aecd9852e..f33f1c437d6 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java @@ -41,6 +41,7 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; public static final String TYPESCRIPT_THREE_PLUS = "true"; public static final String WITHOUT_RUNTIME_CHECKS = "true"; + public static final String SAGAS_AND_RECORDS = "false"; @Override public String getLanguage() { @@ -68,6 +69,7 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { .put(TypeScriptFetchClientCodegen.PREFIX_PARAMETER_INTERFACES, Boolean.FALSE.toString()) .put(TypeScriptFetchClientCodegen.TYPESCRIPT_THREE_PLUS, TYPESCRIPT_THREE_PLUS) .put(TypeScriptFetchClientCodegen.WITHOUT_RUNTIME_CHECKS, WITHOUT_RUNTIME_CHECKS) + .put(TypeScriptFetchClientCodegen.SAGAS_AND_RECORDS, SAGAS_AND_RECORDS) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) .put(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "true") diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java index 33ef4b99bd4..7b29653b31a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java @@ -47,5 +47,6 @@ public class TypeScriptFetchClientOptionsTest extends AbstractOptionsTest { verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); verify(clientCodegen).setTypescriptThreePlus(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.TYPESCRIPT_THREE_PLUS)); verify(clientCodegen).setWithoutRuntimeChecks(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.WITHOUT_RUNTIME_CHECKS)); + verify(clientCodegen).setSagasAndRecords(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.SAGAS_AND_RECORDS)); } } diff --git a/modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-saga-and-records.yaml b/modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-saga-and-records.yaml new file mode 100644 index 00000000000..81124e9578e --- /dev/null +++ b/modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-saga-and-records.yaml @@ -0,0 +1,1175 @@ +swagger: '2.0' +info: + description: 'This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.' + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +host: petstore.swagger.io +basePath: /v2 +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +schemes: + - http +parameters: + fake_petPart-id: + in: path + name: fake_petPart-id + required: true + type: integer + format: int64 +paths: + /fake_behavior/{behavior-id}/type: + get: + tags: + - Behavior + summary: Get the type of behavior + operationId: getBehaviorType + parameters: + - in: path + name: behavior-id + required: true + type: integer + format: int64 + responses: + 200: + description: OK + schema: + $ref: "#/definitions/GetBehaviorTypeResponse" + /fake_behavior/{behavior-id}/permissions: + get: + tags: + - Behavior + summary: Get permissions for the behavior + operationId: getBehaviorPermissions + parameters: + - in: path + name: behavior-id + required: true + type: integer + format: int64 + responses: + 200: + description: OK + schema: + $ref: "#/definitions/GetBehaviorPermissionsResponse" + + /fake_petParts/{fake_petPart-id}/part-type: + get: + tags: + - PetPart + summary: Returns single pet part type for the petPart id. + operationId: getFakePetPartType + parameters: + - $ref: "#/definitions/fake_petPart-id" + responses: + 200: + description: OK + schema: + $ref: "#/definitions/GetPetPartTypeResponse" + /fake_petParts/{fake_petPart-id}/matching-parts: + get: + tags: + - PetPart + summary: Get the matching parts for the given pet part. + operationId: getMatchingParts + parameters: + - $ref: "#/parameters/fake_petPart-id" + - in: query + name: long + required: true + type: boolean + - in: query + name: smooth + required: true + type: boolean + - in: query + name: name + required: false + type: string + - in: query + name: connected-part + required: false + type: string + - in: query + name: short + required: true + type: boolean + responses: + 200: + description: OK + schema: + $ref: "#/definitions/GetMatchingPartsResponse" + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + consumes: + - application/json + - application/xml + produces: + - application/xml + - application/json + parameters: + - in: body + name: dummyCat + description: dummy category for testing + required: true + schema: + $ref: "#/definitions/Category" + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + consumes: + - application/json + - application/xml + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Pet object that needs to be updated in the store + required: true + schema: + $ref: '#/definitions/Pet' + responses: + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + produces: + - application/xml + - application/json + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + $ref: "#/definitions/FindPetsByStatusResponse" + '400': + description: Invalid status value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByUserIds: + get: + tags: + - pet + summary: Finds Pets by user ids + description: 'Multiple ids can be provided with comma separated strings.' + operationId: findPetsByUserIds + produces: + - application/xml + - application/json + parameters: + - name: ids + in: query + description: Ids to filter by + required: true + type: array + items: + type: number + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + $ref: "#/definitions/FindPetsByUserResponse" + '400': + description: Invalid status value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + deprecated: true + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: 'Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.' + operationId: findPetsByTags + produces: + - application/xml + - application/json + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + type: array + items: + type: string + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + type: array + items: + $ref: '#/definitions/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + deprecated: true + /pet/findByIds: + get: + tags: + - pet + summary: Finds Pets by ids + description: 'Multiple ids can be provided with comma separated strings.' + operationId: findPetsByIds + produces: + - application/xml + - application/json + parameters: + - name: ids + in: query + description: Ids to filter by + required: true + type: array + items: + type: number + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + type: array + items: + $ref: '#/definitions/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + produces: + - application/xml + - application/json + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + type: integer + format: int64 + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + consumes: + - application/x-www-form-urlencoded + produces: + - application/xml + - application/json + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + type: integer + format: int64 + - name: name + in: formData + description: Updated name of the pet + required: false + type: string + - name: status + in: formData + description: Updated status of the pet + required: false + type: string + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + produces: + - application/xml + - application/json + parameters: + - name: api_key + in: header + required: false + type: string + - name: petId + in: path + description: Pet id to delete + required: true + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + consumes: + - multipart/form-data + produces: + - application/json + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + type: integer + format: int64 + - name: additionalMetadata + in: formData + description: Additional data to pass to server + required: false + type: string + - name: file + in: formData + description: file to upload + required: false + type: file + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + produces: + - application/json + parameters: [] + responses: + '200': + description: successful operation + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: order placed for purchasing the pet + required: true + schema: + $ref: '#/definitions/Order' + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Order' + '400': + description: Invalid Order + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: 'For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions' + operationId: getOrderById + produces: + - application/xml + - application/json + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + type: integer + maximum: 5 + minimum: 1 + format: int64 + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + operationId: deleteOrder + produces: + - application/xml + - application/json + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Created user object + required: true + schema: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: List of user object + required: true + schema: + type: array + items: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: List of user object + required: true + schema: + type: array + items: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: query + description: The user name for login + required: true + type: string + - name: password + in: query + description: The password for login in clear text + required: true + type: string + responses: + '200': + description: successful operation + schema: + type: string + headers: + X-Rate-Limit: + type: integer + format: int32 + description: calls per hour allowed by the user + X-Expires-After: + type: string + format: date-time + description: date in UTC when toekn expires + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + produces: + - application/xml + - application/json + parameters: [] + responses: + default: + description: successful operation + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: 'The name that needs to be fetched. Use user1 for testing.' + required: true + type: string + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + type: string + - in: body + name: body + description: Updated user object + required: true + schema: + $ref: '#/definitions/User' + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/DefaultMetaOnlyResponse' + '400': + description: Invalid user supplied + '404': + description: User not found + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found +securityDefinitions: + petstore_auth: + type: oauth2 + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + flow: implicit + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header +definitions: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + x-isUniqueId: false + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + default: approved + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + x-keepAsJSObject: "subUser,subUser2" + required: + - id + - subUser2 + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + subUser: + $ref: '#/definitions/User' + subUser2: + $ref: '#/definitions/User' + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - id + - category + - name + - photoUrls + - tags + - status + - alternateStatus + - otherDepStatuses + - friendAge + - age + - isHappy + - isTall + - warningStatus + - otherFriendIds + properties: + id: + type: integer + format: int64 + friendId: + type: integer + format: int64 + otherFriendIds: + type: array + items: + type: integer + format: int64 + friendAge: + type: integer + format: int64 + age: + type: integer + format: int64 + default: 2 + isHappy: + type: boolean + default: true + isTall: + type: boolean + category: + $ref: '#/definitions/Category' + optionalCategory: + $ref: '#/definitions/Category' + name: + type: string + example: doggie + entries: + type: array + items: + $ref: "#/definitions/Category" + surname: + type: string + example: woofy + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + warningStatus: + $ref: "#/definitions/WarningCode" + depStatus: + $ref: "#/definitions/DeploymentRequestStatus" + alternateStatus: + $ref: "#/definitions/DeploymentRequestStatus" + otherDepStatuses: + type: array + items: + $ref: "#/definitions/DeploymentRequestStatus" + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/definitions/Tag' + optionalTags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/definitions/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + default: pending + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + WarningCode: + type: string + description: "Warning code returned when a potential problem is detected" + enum: + - Reduce_Volume_Range_To_Avoid_Large_Steps + - Raise_Amplifier_Volume + - No_Volume_Range_Specified + DeploymentRequestStatus: + type: string + enum: + - New + - Prepared + - Printed + - Tested + - Completed + - Cancelled + - Promoted + - Assigned + - Ready + - Packaged + - Pairing + - Paired + description: "Status of the deployment request" + example: New +################ Responses ################ + ResponseMeta: + type: object + description: "Mandatory part of each response given by our API" + x-keepAsJSObject: "errors" + required: + - code + properties: + code: + type: string + description: "Code returned by the function" + default: Ok + enum: + - Ok + - Generic_Exception + - Field_Error_Exception + - Image_Validation_Exception + - Invalid_Container_Creation_With_No_Default_Asset_Exception + - Invalid_Override_Mode_Exception + - Invalid_Tag_Exception + - Item_Use_Exception + - Missing_Platform_For_Software_Exception + - Missing_Software_For_Platform_Exception + - Platform_Not_Supported_Exception + - Refresh_Data_Exception + - Role_Assignment_Exception + - Task_Already_Running_Exception + - Logged_Out_Exception + - Authorization_Exception + - Unauthorized_Action_For_Current_User_Exception + - User_Already_Exists_But_Is_Not_Authenticated_Exception + - User_Already_Has_Active_Or_Closed_Galaxie_Api_Product_Exception + - User_Already_Has_Multiple_Galaxie_Api_Products_Exception + - Recurly_Api_Exception + - Recurly_Transaction_Error_Exception + - Galaxie_Api_Exception + example: Ok + detail: + type: string + description: "Explanation of what went wrong" + example: "this is some detail about the error or the success" + exception: + type: string + description: "Message of the exception that will help developer to debug this problem if needed" + example: "IOException + stack trace" + type: + type: string + description: "Type of error" + example: "Invalid Token" + errorCode: + $ref: "#/definitions/ErrorCode" + errors: + type: array + description: "An array of all the specific error encountered during the request" + items: + $ref: "#/definitions/Error" + Error: + type: object + description: "This represent an error normally linked to a specific item from a previous request" + required: + - type + properties: + type: + type: string + description: "Usually contains the simple name of the exception" + default: "GenericException" + example: "GenericException" + itemInfo: + $ref: "#/definitions/ItemId" + details: + type: string + description: "Simple explanation of the error" + example: "Could not update that field" + exception: + type: string + description: "Message of the exception that will help developer to debug this problem if needed" + example: "DBException + stack trace" + ErrorCode: + type: string + description: "Error code returned when an error occurs" + enum: + - Volume_Range_At_Lowest_Value + - Music_Volume_Blocks_Volume_Range_Decrease + - Volume_Range_At_Highest_Value + - Maximum_Volume_Blocks_Volume_Range_Increase + - Music_Volume_Blocks_Maximum_Volume_Decrease + - Maximum_Volume_At_Lowest_Value + - Volume_Range_Blocks_Maximum_Volume_Decrease + - Maximum_Volume_At_Highest_Value + - Message_Gain_Blocks_Maximum_Volume_Increase + - Music_Volume_Blocks_Maximum_Volume_Increase + - Maximum_Volume_Blocks_Message_Gain_Decrease + - Message_Gain_At_Highest_Value + - Music_Volume_Blocks_Message_Gain + - Maximum_Message_Gain_Lower_Than_Minimum + - Maximum_Message_Gain_Higher_Than_Maximum + - Maximum_Message_Gain_Lower_Than_Message_Gain + - Minimum_Volume_Blocks_Music_Volume_Decrease + - Maximum_Volume_Blocks_Music_Volume_Increase + ItemId: + type: object + description: "Simplified identifier of an item" + required: + - id + - type + properties: + id: + type: string + description: "Unique identifier of the item" + example: "45" + type: + type: string + description: "playlist" + example: "5667" + DefaultMetaOnlyResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + FindPetsByStatusResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + data: + type: array + items: + $ref: "#/definitions/Pet" + FindPetsByUserResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + data: + type: array + items: + $ref: "#/definitions/User" + GetBehaviorTypeResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + data: + $ref: "#/definitions/BehaviorType" + BehaviorType: + type: string + enum: + - Voluntary + - Involuntary + - Overt + description: "Behavior type of a pet" + example: Published + GetBehaviorPermissionsResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + data: + $ref: "#/definitions/StringBooleanMap" + GetPetPartTypeResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + data: + $ref: "#/definitions/PetPartType" + + PetPartType: + type: string + enum: + - Curved + - Smooth + - Long + description: "Type of pet part" + example: Linear + GetMatchingPartsResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + data: + $ref: "#/definitions/MatchingParts" + MatchingParts: + type: object + description: "Contains all the matching parts" + required: + - connected + - related + properties: + connected: + type: array + items: + $ref: "#/definitions/Part" + description: "List of all the connected parts" + related: + type: array + items: + $ref: "#/definitions/Part" + description: "List of all the related parts" + Part: + type: object + description: "Contains all the info about a pet part" + x-entityId: "" + required: + - id + - name + properties: + id: + type: integer + format: int64 + description: "Unique identifier from the database" + example: 1 + name: + type: string + description: "Name of the part" + example: "head" + StringBooleanMap: + additionalProperties: + type: boolean diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.gitignore b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.gitignore new file mode 100644 index 00000000000..149b5765472 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.npmignore b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.npmignore new file mode 100644 index 00000000000..42061c01a1c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.npmignore @@ -0,0 +1 @@ +README.md \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator-ignore b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/FILES b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/FILES new file mode 100644 index 00000000000..354b10210e0 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/FILES @@ -0,0 +1,71 @@ +.gitignore +.npmignore +README.md +package.json +src/ApiEntitiesRecord.ts +src/ApiEntitiesReducer.ts +src/ApiEntitiesSelectors.ts +src/apis/BehaviorApi.ts +src/apis/BehaviorApiSagas.ts +src/apis/PetApi.ts +src/apis/PetApiSagas.ts +src/apis/PetPartApi.ts +src/apis/PetPartApiSagas.ts +src/apis/SagaApiManager.ts +src/apis/StoreApi.ts +src/apis/StoreApiSagas.ts +src/apis/UserApi.ts +src/apis/UserApiSagas.ts +src/apis/allSagas.ts +src/apis/index.ts +src/index.ts +src/models/BehaviorType.ts +src/models/BehaviorTypeRecord.ts +src/models/Category.ts +src/models/CategoryRecord.ts +src/models/DefaultMetaOnlyResponse.ts +src/models/DefaultMetaOnlyResponseRecord.ts +src/models/DeploymentRequestStatus.ts +src/models/DeploymentRequestStatusRecord.ts +src/models/ErrorCode.ts +src/models/ErrorCodeRecord.ts +src/models/FindPetsByStatusResponse.ts +src/models/FindPetsByStatusResponseRecord.ts +src/models/FindPetsByUserResponse.ts +src/models/FindPetsByUserResponseRecord.ts +src/models/GetBehaviorPermissionsResponse.ts +src/models/GetBehaviorPermissionsResponseRecord.ts +src/models/GetBehaviorTypeResponse.ts +src/models/GetBehaviorTypeResponseRecord.ts +src/models/GetMatchingPartsResponse.ts +src/models/GetMatchingPartsResponseRecord.ts +src/models/GetPetPartTypeResponse.ts +src/models/GetPetPartTypeResponseRecord.ts +src/models/ItemId.ts +src/models/ItemIdRecord.ts +src/models/MatchingParts.ts +src/models/MatchingPartsRecord.ts +src/models/ModelApiResponse.ts +src/models/ModelApiResponseRecord.ts +src/models/ModelError.ts +src/models/ModelErrorRecord.ts +src/models/Order.ts +src/models/OrderRecord.ts +src/models/Part.ts +src/models/PartRecord.ts +src/models/Pet.ts +src/models/PetPartType.ts +src/models/PetPartTypeRecord.ts +src/models/PetRecord.ts +src/models/ResponseMeta.ts +src/models/ResponseMetaRecord.ts +src/models/Tag.ts +src/models/TagRecord.ts +src/models/User.ts +src/models/UserRecord.ts +src/models/WarningCode.ts +src/models/WarningCodeRecord.ts +src/models/index.ts +src/runtime.ts +src/runtimeSagasAndRecords.ts +tsconfig.json diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/VERSION new file mode 100644 index 00000000000..d509cc92aa8 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.1.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/README.md b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/README.md new file mode 100644 index 00000000000..8c188be0ead --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/README.md @@ -0,0 +1,45 @@ +## @openapitools/typescript-fetch-petstore@1.0.0 + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Building + +To build and compile the typescript sources to javascript use: +``` +npm install +npm run build +``` + +### Publishing + +First build the package then run ```npm publish``` + +### Consuming + +navigate to the folder of your consuming project and run one of the following commands. + +_published:_ + +``` +npm install @openapitools/typescript-fetch-petstore@1.0.0 --save +``` + +_unPublished (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE --save diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/package.json b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/package.json new file mode 100644 index 00000000000..3b5c84b1eee --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/package.json @@ -0,0 +1,21 @@ +{ + "name": "@openapitools/typescript-fetch-petstore", + "version": "1.0.0", + "description": "OpenAPI client for @openapitools/typescript-fetch-petstore", + "author": "OpenAPI-Generator", + "main": "./dist/index.js", + "typings": "./dist/index.d.ts", + "scripts": { + "build": "tsc" }, + "devDependencies": { + "immutable": "^4.0.0-rc.12", + "normalizr": "^3.6.1", + "redux-saga": "^1.1.3", + "redux-ts-simple": "^3.2.0", + "reselect": "^4.0.0", + "typescript": "^3.9.5" + }, + "publishConfig": { + "registry": "https://skimdb.npmjs.com/registry" + } +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesRecord.ts new file mode 100644 index 00000000000..edf89903eec --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesRecord.ts @@ -0,0 +1,22 @@ +import {Map, Record, RecordOf} from 'immutable'; + +import { + CategoryRecordEntity, + OrderRecordEntity, + PetRecordEntity, + TagRecordEntity, + UserRecordEntity, +} from "./models" + +export const ApiEntitiesRecordProps = { + recType: "ApiEntitiesRecord" as "ApiEntitiesRecord", + category: (CategoryRecordEntity(), Map()), + order: (OrderRecordEntity(), Map()), + pet: (PetRecordEntity(), Map()), + tag: (TagRecordEntity(), Map()), + user: (UserRecordEntity(), Map()), +}; + +export type ApiEntitiesRecordPropsType = typeof ApiEntitiesRecordProps; +export const ApiEntitiesRecord = Record(ApiEntitiesRecordProps, ApiEntitiesRecordProps.recType); +export type ApiEntitiesRecord = RecordOf; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesReducer.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesReducer.ts new file mode 100644 index 00000000000..9f607ac090f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesReducer.ts @@ -0,0 +1,21 @@ +import {ApiEntitiesRecord} from "./ApiEntitiesRecord"; +import {ReducerBuilder} from "redux-ts-simple"; +import {normalizedEntities} from "./runtimeSagasAndRecords"; + +export const ApiEntitiesReducer = new ReducerBuilder(ApiEntitiesRecord()) + .on(normalizedEntities, (state, action): ApiEntitiesRecord => { + const {entities} = action.payload; + return state.withMutations(mutableState => { + for (const entityKey in entities) { + const entityMap = entities[entityKey]; + const currentEntityMap = mutableState.get(entityKey as any); + if (currentEntityMap) { + let mergedEntityMap = currentEntityMap.mergeDeep(entityMap); + if (!mergedEntityMap.equals(currentEntityMap)) { + mutableState.set(entityKey as any, mergedEntityMap); + } + } + } + }); + }) + .build(); \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesSelectors.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesSelectors.ts new file mode 100644 index 00000000000..9eaffec0dfe --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesSelectors.ts @@ -0,0 +1,5 @@ +export let getApiEntitiesState: (state: any) => any = (state: any) => state.app.apiEntities; + +export function setApiEntitiesStateGetter(getter: (state: any) => any) { // Use this to customize the location where you have placed your ApiEntitiesRecord in your project. + getApiEntitiesState = getter; +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApi.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApi.ts new file mode 100644 index 00000000000..82adc068a8a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApi.ts @@ -0,0 +1,99 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import * as runtime from '../runtime'; +import { + GetBehaviorPermissionsResponse, + GetBehaviorPermissionsResponseFromJSON, + GetBehaviorPermissionsResponseToJSON, + GetBehaviorTypeResponse, + GetBehaviorTypeResponseFromJSON, + GetBehaviorTypeResponseToJSON, +} from '../models'; + +export interface GetBehaviorPermissionsRequest { + behaviorId: number; +} + +export interface GetBehaviorTypeRequest { + behaviorId: number; +} + +/** + * + */ +export class BehaviorApi extends runtime.BaseAPI { + + /** + * Get permissions for the behavior + */ + async getBehaviorPermissionsRaw(requestParameters: GetBehaviorPermissionsRequest): Promise> { + if (requestParameters.behaviorId === null || requestParameters.behaviorId === undefined) { + throw new runtime.RequiredError('behaviorId','Required parameter requestParameters.behaviorId was null or undefined when calling getBehaviorPermissions.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/fake_behavior/{behavior-id}/permissions`.replace(`{${"behavior-id"}}`, encodeURIComponent(String(requestParameters.behaviorId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => GetBehaviorPermissionsResponseFromJSON(jsonValue)); + } + + /** + * Get permissions for the behavior + */ + async getBehaviorPermissions(behaviorId: number): Promise { + const response = await this.getBehaviorPermissionsRaw({ behaviorId: behaviorId }); + return await response.value(); + } + + /** + * Get the type of behavior + */ + async getBehaviorTypeRaw(requestParameters: GetBehaviorTypeRequest): Promise> { + if (requestParameters.behaviorId === null || requestParameters.behaviorId === undefined) { + throw new runtime.RequiredError('behaviorId','Required parameter requestParameters.behaviorId was null or undefined when calling getBehaviorType.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/fake_behavior/{behavior-id}/type`.replace(`{${"behavior-id"}}`, encodeURIComponent(String(requestParameters.behaviorId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => GetBehaviorTypeResponseFromJSON(jsonValue)); + } + + /** + * Get the type of behavior + */ + async getBehaviorType(behaviorId: number): Promise { + const response = await this.getBehaviorTypeRaw({ behaviorId: behaviorId }); + return await response.value(); + } + +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApiSagas.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApiSagas.ts new file mode 100644 index 00000000000..5d671f274d3 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApiSagas.ts @@ -0,0 +1,131 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import {Api} from './'; +import {List} from 'immutable'; +import {all, fork, put, takeLatest} from "redux-saga/effects"; +import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords"; +import {Action} from "redux-ts-simple"; + +import { + GetBehaviorPermissionsResponse, + GetBehaviorPermissionsResponseRecord, + getBehaviorPermissionsResponseRecordUtils, + GetBehaviorTypeResponse, + GetBehaviorTypeResponseRecord, + getBehaviorTypeResponseRecordUtils, + BehaviorType, +} from '../models'; + +const createSagaAction = (type: string) => originalCreateSagaAction(type, {namespace: "api_behaviorApi"}); + +export const behaviorApiSagaMap = new Map Generator>([ + ["getBehaviorPermissions", getBehaviorPermissionsSaga], + ["getBehaviorType", getBehaviorTypeSaga], + ] +); + +export function *behaviorApiAllSagas() { + yield all([...behaviorApiSagaMap.values()].map(actionSaga => fork(actionSaga))); +} + +//region getBehaviorPermissions + +export interface PayloadGetBehaviorPermissions extends PayloadGetBehaviorPermissionsRequest, BasePayloadApiAction { +} + +export interface PayloadGetBehaviorPermissionsRequest { + behaviorId: string; +} + +export const getBehaviorPermissionsRequest = createSagaAction("getBehaviorPermissionsRequest"); +export const getBehaviorPermissionsSuccess = createSagaAction<{ [key: string]: boolean; }>("getBehaviorPermissionsSuccess"); +export const getBehaviorPermissionsFailure = createSagaAction<{error: any, requestPayload: PayloadGetBehaviorPermissions}>("getBehaviorPermissionsFailure"); + +export const getBehaviorPermissions = createSagaAction("getBehaviorPermissions"); + +export function *getBehaviorPermissionsSaga() { + yield takeLatest(getBehaviorPermissions, getBehaviorPermissionsSagaImp); +} + +export function *getBehaviorPermissionsSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + behaviorId, + } = _payloadRest_; + + yield put(getBehaviorPermissionsRequest(_action_.payload)); + + const response: Required = yield apiCall(Api.behaviorApi, Api.behaviorApi.getBehaviorPermissions, + parseFloat(behaviorId), + ); + + let successReturnValue: any = undefined; + successReturnValue = getBehaviorPermissionsResponseRecordUtils.fromApiPassthrough(response); + yield put(getBehaviorPermissionsSuccess(successReturnValue)); + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getBehaviorPermissionsFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region getBehaviorType + +export interface PayloadGetBehaviorType extends PayloadGetBehaviorTypeRequest, BasePayloadApiAction { +} + +export interface PayloadGetBehaviorTypeRequest { + behaviorId: string; +} + +export const getBehaviorTypeRequest = createSagaAction("getBehaviorTypeRequest"); +export const getBehaviorTypeSuccess = createSagaAction("getBehaviorTypeSuccess"); +export const getBehaviorTypeFailure = createSagaAction<{error: any, requestPayload: PayloadGetBehaviorType}>("getBehaviorTypeFailure"); + +export const getBehaviorType = createSagaAction("getBehaviorType"); + +export function *getBehaviorTypeSaga() { + yield takeLatest(getBehaviorType, getBehaviorTypeSagaImp); +} + +export function *getBehaviorTypeSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + behaviorId, + } = _payloadRest_; + + yield put(getBehaviorTypeRequest(_action_.payload)); + + const response: Required = yield apiCall(Api.behaviorApi, Api.behaviorApi.getBehaviorType, + parseFloat(behaviorId), + ); + + let successReturnValue: any = undefined; + successReturnValue = getBehaviorTypeResponseRecordUtils.fromApiPassthrough(response); + yield put(getBehaviorTypeSuccess(successReturnValue)); + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getBehaviorTypeFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApi.ts new file mode 100644 index 00000000000..7726dae7530 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApi.ts @@ -0,0 +1,560 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import * as runtime from '../runtime'; +import { + Category, + CategoryFromJSON, + CategoryToJSON, + FindPetsByStatusResponse, + FindPetsByStatusResponseFromJSON, + FindPetsByStatusResponseToJSON, + FindPetsByUserResponse, + FindPetsByUserResponseFromJSON, + FindPetsByUserResponseToJSON, + ModelApiResponse, + ModelApiResponseFromJSON, + ModelApiResponseToJSON, + Pet, + PetFromJSON, + PetToJSON, +} from '../models'; + +export interface AddPetRequest { + dummyCat: Category; +} + +export interface DeletePetRequest { + petId: number; + apiKey?: string; +} + +export interface FindPetsByIdsRequest { + ids: Array; +} + +export interface FindPetsByStatusRequest { + status: Array; +} + +export interface FindPetsByTagsRequest { + tags: Array; +} + +export interface FindPetsByUserIdsRequest { + ids: Array; +} + +export interface GetPetByIdRequest { + petId: number; +} + +export interface UpdatePetRequest { + body: Pet; +} + +export interface UpdatePetWithFormRequest { + petId: number; + name?: string; + status?: string; +} + +export interface UploadFileRequest { + petId: number; + additionalMetadata?: string; + file?: Blob; +} + +/** + * + */ +export class PetApi extends runtime.BaseAPI { + + /** + * Add a new pet to the store + */ + async addPetRaw(requestParameters: AddPetRequest): Promise> { + if (requestParameters.dummyCat === null || requestParameters.dummyCat === undefined) { + throw new runtime.RequiredError('dummyCat','Required parameter requestParameters.dummyCat was null or undefined when calling addPet.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const response = await this.request({ + path: `/pet`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: CategoryToJSON(requestParameters.dummyCat), + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Add a new pet to the store + */ + async addPet(dummyCat: Category): Promise { + await this.addPetRaw({ dummyCat: dummyCat }); + } + + /** + * Deletes a pet + */ + async deletePetRaw(requestParameters: DeletePetRequest): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling deletePet.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (requestParameters.apiKey !== undefined && requestParameters.apiKey !== null) { + headerParameters['api_key'] = String(requestParameters.apiKey); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Deletes a pet + */ + async deletePet(petId: number, apiKey?: string): Promise { + await this.deletePetRaw({ petId: petId, apiKey: apiKey }); + } + + /** + * Multiple ids can be provided with comma separated strings. + * Finds Pets by ids + */ + async findPetsByIdsRaw(requestParameters: FindPetsByIdsRequest): Promise>> { + if (requestParameters.ids === null || requestParameters.ids === undefined) { + throw new runtime.RequiredError('ids','Required parameter requestParameters.ids was null or undefined when calling findPetsByIds.'); + } + + const queryParameters: any = {}; + + if (requestParameters.ids) { + queryParameters['ids'] = requestParameters.ids.join(runtime.COLLECTION_FORMATS["csv"]); + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const response = await this.request({ + path: `/pet/findByIds`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(PetFromJSON)); + } + + /** + * Multiple ids can be provided with comma separated strings. + * Finds Pets by ids + */ + async findPetsByIds(ids: Array): Promise> { + const response = await this.findPetsByIdsRaw({ ids: ids }); + return await response.value(); + } + + /** + * Multiple status values can be provided with comma separated strings + * Finds Pets by status + */ + async findPetsByStatusRaw(requestParameters: FindPetsByStatusRequest): Promise> { + if (requestParameters.status === null || requestParameters.status === undefined) { + throw new runtime.RequiredError('status','Required parameter requestParameters.status was null or undefined when calling findPetsByStatus.'); + } + + const queryParameters: any = {}; + + if (requestParameters.status) { + queryParameters['status'] = requestParameters.status.join(runtime.COLLECTION_FORMATS["csv"]); + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const response = await this.request({ + path: `/pet/findByStatus`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => FindPetsByStatusResponseFromJSON(jsonValue)); + } + + /** + * Multiple status values can be provided with comma separated strings + * Finds Pets by status + */ + async findPetsByStatus(status: Array): Promise { + const response = await this.findPetsByStatusRaw({ status: status }); + return await response.value(); + } + + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * Finds Pets by tags + */ + async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest): Promise>> { + if (requestParameters.tags === null || requestParameters.tags === undefined) { + throw new runtime.RequiredError('tags','Required parameter requestParameters.tags was null or undefined when calling findPetsByTags.'); + } + + const queryParameters: any = {}; + + if (requestParameters.tags) { + queryParameters['tags'] = requestParameters.tags.join(runtime.COLLECTION_FORMATS["csv"]); + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const response = await this.request({ + path: `/pet/findByTags`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(PetFromJSON)); + } + + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * Finds Pets by tags + */ + async findPetsByTags(tags: Array): Promise> { + const response = await this.findPetsByTagsRaw({ tags: tags }); + return await response.value(); + } + + /** + * Multiple ids can be provided with comma separated strings. + * Finds Pets by user ids + */ + async findPetsByUserIdsRaw(requestParameters: FindPetsByUserIdsRequest): Promise> { + if (requestParameters.ids === null || requestParameters.ids === undefined) { + throw new runtime.RequiredError('ids','Required parameter requestParameters.ids was null or undefined when calling findPetsByUserIds.'); + } + + const queryParameters: any = {}; + + if (requestParameters.ids) { + queryParameters['ids'] = requestParameters.ids.join(runtime.COLLECTION_FORMATS["csv"]); + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const response = await this.request({ + path: `/pet/findByUserIds`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => FindPetsByUserResponseFromJSON(jsonValue)); + } + + /** + * Multiple ids can be provided with comma separated strings. + * Finds Pets by user ids + */ + async findPetsByUserIds(ids: Array): Promise { + const response = await this.findPetsByUserIdsRaw({ ids: ids }); + return await response.value(); + } + + /** + * Returns a single pet + * Find pet by ID + */ + async getPetByIdRaw(requestParameters: GetPetByIdRequest): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling getPetById.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.apiKey) { + headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => PetFromJSON(jsonValue)); + } + + /** + * Returns a single pet + * Find pet by ID + */ + async getPetById(petId: number): Promise { + const response = await this.getPetByIdRaw({ petId: petId }); + return await response.value(); + } + + /** + * Update an existing pet + */ + async updatePetRaw(requestParameters: UpdatePetRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updatePet.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const response = await this.request({ + path: `/pet`, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + body: PetToJSON(requestParameters.body), + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Update an existing pet + */ + async updatePet(body: Pet): Promise { + await this.updatePetRaw({ body: body }); + } + + /** + * Updates a pet in the store with form data + */ + async updatePetWithFormRaw(requestParameters: UpdatePetWithFormRequest): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling updatePetWithForm.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const consumes: runtime.Consume[] = [ + { contentType: 'application/x-www-form-urlencoded' }, + ]; + // @ts-ignore: canConsumeForm may be unused + const canConsumeForm = runtime.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): any }; + let useForm = false; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new URLSearchParams(); + } + + if (requestParameters.name !== undefined) { + formParams.append('name', requestParameters.name as any); + } + + if (requestParameters.status !== undefined) { + formParams.append('status', requestParameters.status as any); + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: formParams, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Updates a pet in the store with form data + */ + async updatePetWithForm(petId: number, name?: string, status?: string): Promise { + await this.updatePetWithFormRaw({ petId: petId, name: name, status: status }); + } + + /** + * uploads an image + */ + async uploadFileRaw(requestParameters: UploadFileRequest): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFile.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const consumes: runtime.Consume[] = [ + { contentType: 'multipart/form-data' }, + ]; + // @ts-ignore: canConsumeForm may be unused + const canConsumeForm = runtime.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): any }; + let useForm = false; + // use FormData to transmit files using content-type "multipart/form-data" + useForm = canConsumeForm; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new URLSearchParams(); + } + + if (requestParameters.additionalMetadata !== undefined) { + formParams.append('additionalMetadata', requestParameters.additionalMetadata as any); + } + + if (requestParameters.file !== undefined) { + formParams.append('file', requestParameters.file as any); + } + + const response = await this.request({ + path: `/pet/{petId}/uploadImage`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: formParams, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => ModelApiResponseFromJSON(jsonValue)); + } + + /** + * uploads an image + */ + async uploadFile(petId: number, additionalMetadata?: string, file?: Blob): Promise { + const response = await this.uploadFileRaw({ petId: petId, additionalMetadata: additionalMetadata, file: file }); + return await response.value(); + } + +} + +/** + * @export + * @enum {string} + */ +export enum FindPetsByStatusStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApiSagas.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApiSagas.ts new file mode 100644 index 00000000000..202ec780b63 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApiSagas.ts @@ -0,0 +1,565 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import {Api} from './'; +import {List} from 'immutable'; +import {all, fork, put, takeLatest} from "redux-saga/effects"; +import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords"; +import {Action} from "redux-ts-simple"; + +import { + Category, + CategoryRecord, + categoryRecordUtils, + FindPetsByStatusResponse, + FindPetsByStatusResponseRecord, + findPetsByStatusResponseRecordUtils, + FindPetsByUserResponse, + FindPetsByUserResponseRecord, + findPetsByUserResponseRecordUtils, + ModelApiResponse, + ModelApiResponseRecord, + modelApiResponseRecordUtils, + Pet, + PetRecord, + petRecordUtils, + UserRecord, +} from '../models'; + +import { + FindPetsByStatusStatusEnum, +} from './PetApi'; + +const createSagaAction = (type: string) => originalCreateSagaAction(type, {namespace: "api_petApi"}); + +export const petApiSagaMap = new Map Generator>([ + ["addPet", addPetSaga], + ["deletePet", deletePetSaga], + ["findPetsByIds", findPetsByIdsSaga], + ["findPetsByStatus", findPetsByStatusSaga], + ["findPetsByTags", findPetsByTagsSaga], + ["findPetsByUserIds", findPetsByUserIdsSaga], + ["getPetById", getPetByIdSaga], + ["updatePet", updatePetSaga], + ["updatePetWithForm", updatePetWithFormSaga], + ["uploadFile", uploadFileSaga], + ] +); + +export function *petApiAllSagas() { + yield all([...petApiSagaMap.values()].map(actionSaga => fork(actionSaga))); +} + +//region addPet + +export interface PayloadAddPet extends PayloadAddPetRequest, BasePayloadApiAction { +} + +export interface PayloadAddPetRequest { + dummyCat: CategoryRecord; +} + +export const addPetRequest = createSagaAction("addPetRequest"); +export const addPetSuccess = createSagaAction("addPetSuccess"); +export const addPetFailure = createSagaAction<{error: any, requestPayload: PayloadAddPet}>("addPetFailure"); + +export const addPet = createSagaAction("addPet"); + +export function *addPetSaga() { + yield takeLatest(addPet, addPetSagaImp); +} + +export function *addPetSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + dummyCat, + } = _payloadRest_; + + yield put(addPetRequest(_action_.payload)); + + const response = yield apiCall(Api.petApi, Api.petApi.addPet, + categoryRecordUtils.toApi(dummyCat), + ); + + yield put(addPetSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(addPetFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region deletePet + +export interface PayloadDeletePet extends PayloadDeletePetRequest, BasePayloadApiAction { +} + +export interface PayloadDeletePetRequest { + petId: string; + apiKey?: string; +} + +export const deletePetRequest = createSagaAction("deletePetRequest"); +export const deletePetSuccess = createSagaAction("deletePetSuccess"); +export const deletePetFailure = createSagaAction<{error: any, requestPayload: PayloadDeletePet}>("deletePetFailure"); + +export const deletePet = createSagaAction("deletePet"); + +export function *deletePetSaga() { + yield takeLatest(deletePet, deletePetSagaImp); +} + +export function *deletePetSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + petId, + apiKey, + } = _payloadRest_; + + yield put(deletePetRequest(_action_.payload)); + + const response = yield apiCall(Api.petApi, Api.petApi.deletePet, + parseFloat(petId), + apiKey, + ); + + yield put(deletePetSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(deletePetFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region findPetsByIds + +export interface PayloadFindPetsByIds extends PayloadFindPetsByIdsRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadFindPetsByIdsRequest { + ids: List; +} + +export const findPetsByIdsRequest = createSagaAction("findPetsByIdsRequest"); +export const findPetsByIdsSuccess = createSagaAction>("findPetsByIdsSuccess"); +export const findPetsByIdsSuccess_Entities = createSagaAction("findPetsByIdsSuccess_Entities"); +export const findPetsByIdsFailure = createSagaAction<{error: any, requestPayload: PayloadFindPetsByIds}>("findPetsByIdsFailure"); + +export const findPetsByIds = createSagaAction("findPetsByIds"); + +export function *findPetsByIdsSaga() { + yield takeLatest(findPetsByIds, findPetsByIdsSagaImp); +} + +export function *findPetsByIdsSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + ids, + } = _payloadRest_; + + yield put(findPetsByIdsRequest(requestPayload)); + + const response: Required> = yield apiCall(Api.petApi, Api.petApi.findPetsByIds, + ids.map(p => parseFloat(p)).toArray(), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = petRecordUtils.fromApiArrayAsEntities(response); + yield put(normalizedEntities(successReturnValue)); + yield put(findPetsByIdsSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = petRecordUtils.fromApiArray(response); + yield put(findPetsByIdsSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(findPetsByIdsFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region findPetsByStatus + +export interface PayloadFindPetsByStatus extends PayloadFindPetsByStatusRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadFindPetsByStatusRequest { + status: List; +} + +export const findPetsByStatusRequest = createSagaAction("findPetsByStatusRequest"); +export const findPetsByStatusSuccess = createSagaAction>("findPetsByStatusSuccess"); +export const findPetsByStatusSuccess_Entities = createSagaAction("findPetsByStatusSuccess_Entities"); +export const findPetsByStatusFailure = createSagaAction<{error: any, requestPayload: PayloadFindPetsByStatus}>("findPetsByStatusFailure"); + +export const findPetsByStatus = createSagaAction("findPetsByStatus"); + +export function *findPetsByStatusSaga() { + yield takeLatest(findPetsByStatus, findPetsByStatusSagaImp); +} + +export function *findPetsByStatusSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + status, + } = _payloadRest_; + + yield put(findPetsByStatusRequest(requestPayload)); + + const response: Required = yield apiCall(Api.petApi, Api.petApi.findPetsByStatus, + status.toJS(), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = findPetsByStatusResponseRecordUtils.fromApiPassthroughAsEntities(response); + yield put(normalizedEntities(successReturnValue)); + yield put(findPetsByStatusSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = findPetsByStatusResponseRecordUtils.fromApiPassthrough(response); + yield put(findPetsByStatusSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(findPetsByStatusFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region findPetsByTags + +export interface PayloadFindPetsByTags extends PayloadFindPetsByTagsRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadFindPetsByTagsRequest { + tags: List; +} + +export const findPetsByTagsRequest = createSagaAction("findPetsByTagsRequest"); +export const findPetsByTagsSuccess = createSagaAction>("findPetsByTagsSuccess"); +export const findPetsByTagsSuccess_Entities = createSagaAction("findPetsByTagsSuccess_Entities"); +export const findPetsByTagsFailure = createSagaAction<{error: any, requestPayload: PayloadFindPetsByTags}>("findPetsByTagsFailure"); + +export const findPetsByTags = createSagaAction("findPetsByTags"); + +export function *findPetsByTagsSaga() { + yield takeLatest(findPetsByTags, findPetsByTagsSagaImp); +} + +export function *findPetsByTagsSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + tags, + } = _payloadRest_; + + yield put(findPetsByTagsRequest(requestPayload)); + + const response: Required> = yield apiCall(Api.petApi, Api.petApi.findPetsByTags, + tags.toJS(), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = petRecordUtils.fromApiArrayAsEntities(response); + yield put(normalizedEntities(successReturnValue)); + yield put(findPetsByTagsSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = petRecordUtils.fromApiArray(response); + yield put(findPetsByTagsSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(findPetsByTagsFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region findPetsByUserIds + +export interface PayloadFindPetsByUserIds extends PayloadFindPetsByUserIdsRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadFindPetsByUserIdsRequest { + ids: List; +} + +export const findPetsByUserIdsRequest = createSagaAction("findPetsByUserIdsRequest"); +export const findPetsByUserIdsSuccess = createSagaAction>("findPetsByUserIdsSuccess"); +export const findPetsByUserIdsSuccess_Entities = createSagaAction("findPetsByUserIdsSuccess_Entities"); +export const findPetsByUserIdsFailure = createSagaAction<{error: any, requestPayload: PayloadFindPetsByUserIds}>("findPetsByUserIdsFailure"); + +export const findPetsByUserIds = createSagaAction("findPetsByUserIds"); + +export function *findPetsByUserIdsSaga() { + yield takeLatest(findPetsByUserIds, findPetsByUserIdsSagaImp); +} + +export function *findPetsByUserIdsSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + ids, + } = _payloadRest_; + + yield put(findPetsByUserIdsRequest(requestPayload)); + + const response: Required = yield apiCall(Api.petApi, Api.petApi.findPetsByUserIds, + ids.map(p => parseFloat(p)).toArray(), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = findPetsByUserResponseRecordUtils.fromApiPassthroughAsEntities(response); + yield put(normalizedEntities(successReturnValue)); + yield put(findPetsByUserIdsSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = findPetsByUserResponseRecordUtils.fromApiPassthrough(response); + yield put(findPetsByUserIdsSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(findPetsByUserIdsFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region getPetById + +export interface PayloadGetPetById extends PayloadGetPetByIdRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadGetPetByIdRequest { + petId: string; +} + +export const getPetByIdRequest = createSagaAction("getPetByIdRequest"); +export const getPetByIdSuccess = createSagaAction("getPetByIdSuccess"); +export const getPetByIdSuccess_Entities = createSagaAction("getPetByIdSuccess_Entities"); +export const getPetByIdFailure = createSagaAction<{error: any, requestPayload: PayloadGetPetById}>("getPetByIdFailure"); + +export const getPetById = createSagaAction("getPetById"); + +export function *getPetByIdSaga() { + yield takeLatest(getPetById, getPetByIdSagaImp); +} + +export function *getPetByIdSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + petId, + } = _payloadRest_; + + yield put(getPetByIdRequest(requestPayload)); + + const response: Required = yield apiCall(Api.petApi, Api.petApi.getPetById, + parseFloat(petId), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = petRecordUtils.fromApiArrayAsEntities([response]); + yield put(normalizedEntities(successReturnValue)); + yield put(getPetByIdSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = petRecordUtils.fromApi(response); + yield put(getPetByIdSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getPetByIdFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region updatePet + +export interface PayloadUpdatePet extends PayloadUpdatePetRequest, BasePayloadApiAction { +} + +export interface PayloadUpdatePetRequest { + body: PetRecord; +} + +export const updatePetRequest = createSagaAction("updatePetRequest"); +export const updatePetSuccess = createSagaAction("updatePetSuccess"); +export const updatePetFailure = createSagaAction<{error: any, requestPayload: PayloadUpdatePet}>("updatePetFailure"); + +export const updatePet = createSagaAction("updatePet"); + +export function *updatePetSaga() { + yield takeLatest(updatePet, updatePetSagaImp); +} + +export function *updatePetSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + body, + } = _payloadRest_; + + yield put(updatePetRequest(_action_.payload)); + + const response = yield apiCall(Api.petApi, Api.petApi.updatePet, + petRecordUtils.toApi(body), + ); + + yield put(updatePetSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(updatePetFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region updatePetWithForm + +export interface PayloadUpdatePetWithForm extends PayloadUpdatePetWithFormRequest, BasePayloadApiAction { +} + +export interface PayloadUpdatePetWithFormRequest { + petId: string; + name?: string; + status?: string; +} + +export const updatePetWithFormRequest = createSagaAction("updatePetWithFormRequest"); +export const updatePetWithFormSuccess = createSagaAction("updatePetWithFormSuccess"); +export const updatePetWithFormFailure = createSagaAction<{error: any, requestPayload: PayloadUpdatePetWithForm}>("updatePetWithFormFailure"); + +export const updatePetWithForm = createSagaAction("updatePetWithForm"); + +export function *updatePetWithFormSaga() { + yield takeLatest(updatePetWithForm, updatePetWithFormSagaImp); +} + +export function *updatePetWithFormSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + petId, + name, + status, + } = _payloadRest_; + + yield put(updatePetWithFormRequest(_action_.payload)); + + const response = yield apiCall(Api.petApi, Api.petApi.updatePetWithForm, + parseFloat(petId), + name, + status, + ); + + yield put(updatePetWithFormSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(updatePetWithFormFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region uploadFile + +export interface PayloadUploadFile extends PayloadUploadFileRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadUploadFileRequest { + petId: string; + additionalMetadata?: string; + file?: Blob; +} + +export const uploadFileRequest = createSagaAction("uploadFileRequest"); +export const uploadFileSuccess = createSagaAction("uploadFileSuccess"); +export const uploadFileSuccess_Entities = createSagaAction("uploadFileSuccess_Entities"); +export const uploadFileFailure = createSagaAction<{error: any, requestPayload: PayloadUploadFile}>("uploadFileFailure"); + +export const uploadFile = createSagaAction("uploadFile"); + +export function *uploadFileSaga() { + yield takeLatest(uploadFile, uploadFileSagaImp); +} + +export function *uploadFileSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + petId, + additionalMetadata, + file, + } = _payloadRest_; + + yield put(uploadFileRequest(requestPayload)); + + const response: Required = yield apiCall(Api.petApi, Api.petApi.uploadFile, + parseFloat(petId), + additionalMetadata, + file, + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = modelApiResponseRecordUtils.fromApiArrayAsEntities([response]); + yield put(normalizedEntities(successReturnValue)); + yield put(uploadFileSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = modelApiResponseRecordUtils.fromApi(response); + yield put(uploadFileSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(uploadFileFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApi.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApi.ts new file mode 100644 index 00000000000..535059660a0 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApi.ts @@ -0,0 +1,136 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import * as runtime from '../runtime'; +import { + GetMatchingPartsResponse, + GetMatchingPartsResponseFromJSON, + GetMatchingPartsResponseToJSON, + GetPetPartTypeResponse, + GetPetPartTypeResponseFromJSON, + GetPetPartTypeResponseToJSON, +} from '../models'; + +export interface GetFakePetPartTypeRequest { + fakePetPartId: number; +} + +export interface GetMatchingPartsRequest { + fakePetPartId: number; + _long: boolean; + smooth: boolean; + _short: boolean; + name?: string; + connectedPart?: string; +} + +/** + * + */ +export class PetPartApi extends runtime.BaseAPI { + + /** + * Returns single pet part type for the petPart id. + */ + async getFakePetPartTypeRaw(requestParameters: GetFakePetPartTypeRequest): Promise> { + if (requestParameters.fakePetPartId === null || requestParameters.fakePetPartId === undefined) { + throw new runtime.RequiredError('fakePetPartId','Required parameter requestParameters.fakePetPartId was null or undefined when calling getFakePetPartType.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/fake_petParts/{fake_petPart-id}/part-type`.replace(`{${"fake_petPart-id"}}`, encodeURIComponent(String(requestParameters.fakePetPartId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => GetPetPartTypeResponseFromJSON(jsonValue)); + } + + /** + * Returns single pet part type for the petPart id. + */ + async getFakePetPartType(fakePetPartId: number): Promise { + const response = await this.getFakePetPartTypeRaw({ fakePetPartId: fakePetPartId }); + return await response.value(); + } + + /** + * Get the matching parts for the given pet part. + */ + async getMatchingPartsRaw(requestParameters: GetMatchingPartsRequest): Promise> { + if (requestParameters.fakePetPartId === null || requestParameters.fakePetPartId === undefined) { + throw new runtime.RequiredError('fakePetPartId','Required parameter requestParameters.fakePetPartId was null or undefined when calling getMatchingParts.'); + } + + if (requestParameters._long === null || requestParameters._long === undefined) { + throw new runtime.RequiredError('_long','Required parameter requestParameters._long was null or undefined when calling getMatchingParts.'); + } + + if (requestParameters.smooth === null || requestParameters.smooth === undefined) { + throw new runtime.RequiredError('smooth','Required parameter requestParameters.smooth was null or undefined when calling getMatchingParts.'); + } + + if (requestParameters._short === null || requestParameters._short === undefined) { + throw new runtime.RequiredError('_short','Required parameter requestParameters._short was null or undefined when calling getMatchingParts.'); + } + + const queryParameters: any = {}; + + if (requestParameters._long !== undefined) { + queryParameters['long'] = requestParameters._long; + } + + if (requestParameters.smooth !== undefined) { + queryParameters['smooth'] = requestParameters.smooth; + } + + if (requestParameters.name !== undefined) { + queryParameters['name'] = requestParameters.name; + } + + if (requestParameters.connectedPart !== undefined) { + queryParameters['connected-part'] = requestParameters.connectedPart; + } + + if (requestParameters._short !== undefined) { + queryParameters['short'] = requestParameters._short; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/fake_petParts/{fake_petPart-id}/matching-parts`.replace(`{${"fake_petPart-id"}}`, encodeURIComponent(String(requestParameters.fakePetPartId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => GetMatchingPartsResponseFromJSON(jsonValue)); + } + + /** + * Get the matching parts for the given pet part. + */ + async getMatchingParts(fakePetPartId: number, _long: boolean, smooth: boolean, _short: boolean, name?: string, connectedPart?: string): Promise { + const response = await this.getMatchingPartsRaw({ fakePetPartId: fakePetPartId, _long: _long, smooth: smooth, _short: _short, name: name, connectedPart: connectedPart }); + return await response.value(); + } + +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApiSagas.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApiSagas.ts new file mode 100644 index 00000000000..3111c06e17e --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApiSagas.ts @@ -0,0 +1,156 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import {Api} from './'; +import {List} from 'immutable'; +import {all, fork, put, takeLatest} from "redux-saga/effects"; +import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords"; +import {Action} from "redux-ts-simple"; + +import { + GetMatchingPartsResponse, + GetMatchingPartsResponseRecord, + getMatchingPartsResponseRecordUtils, + GetPetPartTypeResponse, + GetPetPartTypeResponseRecord, + getPetPartTypeResponseRecordUtils, + MatchingPartsRecord, + PetPartType, +} from '../models'; + +const createSagaAction = (type: string) => originalCreateSagaAction(type, {namespace: "api_petPartApi"}); + +export const petPartApiSagaMap = new Map Generator>([ + ["getFakePetPartType", getFakePetPartTypeSaga], + ["getMatchingParts", getMatchingPartsSaga], + ] +); + +export function *petPartApiAllSagas() { + yield all([...petPartApiSagaMap.values()].map(actionSaga => fork(actionSaga))); +} + +//region getFakePetPartType + +export interface PayloadGetFakePetPartType extends PayloadGetFakePetPartTypeRequest, BasePayloadApiAction { +} + +export interface PayloadGetFakePetPartTypeRequest { + fakePetPartId: string; +} + +export const getFakePetPartTypeRequest = createSagaAction("getFakePetPartTypeRequest"); +export const getFakePetPartTypeSuccess = createSagaAction("getFakePetPartTypeSuccess"); +export const getFakePetPartTypeFailure = createSagaAction<{error: any, requestPayload: PayloadGetFakePetPartType}>("getFakePetPartTypeFailure"); + +export const getFakePetPartType = createSagaAction("getFakePetPartType"); + +export function *getFakePetPartTypeSaga() { + yield takeLatest(getFakePetPartType, getFakePetPartTypeSagaImp); +} + +export function *getFakePetPartTypeSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + fakePetPartId, + } = _payloadRest_; + + yield put(getFakePetPartTypeRequest(_action_.payload)); + + const response: Required = yield apiCall(Api.petPartApi, Api.petPartApi.getFakePetPartType, + parseFloat(fakePetPartId), + ); + + let successReturnValue: any = undefined; + successReturnValue = getPetPartTypeResponseRecordUtils.fromApiPassthrough(response); + yield put(getFakePetPartTypeSuccess(successReturnValue)); + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getFakePetPartTypeFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region getMatchingParts + +export interface PayloadGetMatchingParts extends PayloadGetMatchingPartsRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadGetMatchingPartsRequest { + fakePetPartId: string; + _long: boolean; + smooth: boolean; + _short: boolean; + name?: string; + connectedPart?: string; +} + +export const getMatchingPartsRequest = createSagaAction("getMatchingPartsRequest"); +export const getMatchingPartsSuccess = createSagaAction("getMatchingPartsSuccess"); +export const getMatchingPartsSuccess_Entities = createSagaAction("getMatchingPartsSuccess_Entities"); +export const getMatchingPartsFailure = createSagaAction<{error: any, requestPayload: PayloadGetMatchingParts}>("getMatchingPartsFailure"); + +export const getMatchingParts = createSagaAction("getMatchingParts"); + +export function *getMatchingPartsSaga() { + yield takeLatest(getMatchingParts, getMatchingPartsSagaImp); +} + +export function *getMatchingPartsSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + fakePetPartId, + _long, + smooth, + _short, + name, + connectedPart, + } = _payloadRest_; + + yield put(getMatchingPartsRequest(requestPayload)); + + const response: Required = yield apiCall(Api.petPartApi, Api.petPartApi.getMatchingParts, + parseFloat(fakePetPartId), + _long, + smooth, + _short, + name, + connectedPart, + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = getMatchingPartsResponseRecordUtils.fromApiPassthroughAsEntities(response); + yield put(normalizedEntities(successReturnValue)); + yield put(getMatchingPartsSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = getMatchingPartsResponseRecordUtils.fromApiPassthrough(response); + yield put(getMatchingPartsSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getMatchingPartsFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/SagaApiManager.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/SagaApiManager.ts new file mode 100644 index 00000000000..21a49677e50 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/SagaApiManager.ts @@ -0,0 +1,36 @@ +import { + Configuration, + ConfigurationParameters, +} from "../"; + +import { + BehaviorApi, + PetApi, + PetPartApi, + StoreApi, + UserApi, +} from "./"; + +export class Api { + public static behaviorApi: BehaviorApi; + public static petApi: PetApi; + public static petPartApi: PetPartApi; + public static storeApi: StoreApi; + public static userApi: UserApi; + + public static init(apiBasePath: string) { + const apiBaseConfig: ConfigurationParameters = { + basePath: apiBasePath, + credentials: "include", + headers: { + 'Cache-Control': 'no-cache, no-store' // this is needed to prevent stalling issues in Chrome. Also it is a good behavior for api calls. + } + }; + + Api.behaviorApi = new BehaviorApi(new Configuration(apiBaseConfig)); + Api.petApi = new PetApi(new Configuration(apiBaseConfig)); + Api.petPartApi = new PetPartApi(new Configuration(apiBaseConfig)); + Api.storeApi = new StoreApi(new Configuration(apiBaseConfig)); + Api.userApi = new UserApi(new Configuration(apiBaseConfig)); + } +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApi.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApi.ts new file mode 100644 index 00000000000..51382e766aa --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApi.ts @@ -0,0 +1,168 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import * as runtime from '../runtime'; +import { + Order, + OrderFromJSON, + OrderToJSON, +} from '../models'; + +export interface DeleteOrderRequest { + orderId: string; +} + +export interface GetOrderByIdRequest { + orderId: number; +} + +export interface PlaceOrderRequest { + body: Order; +} + +/** + * + */ +export class StoreApi extends runtime.BaseAPI { + + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * Delete purchase order by ID + */ + async deleteOrderRaw(requestParameters: DeleteOrderRequest): Promise> { + if (requestParameters.orderId === null || requestParameters.orderId === undefined) { + throw new runtime.RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling deleteOrder.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * Delete purchase order by ID + */ + async deleteOrder(orderId: string): Promise { + await this.deleteOrderRaw({ orderId: orderId }); + } + + /** + * Returns a map of status codes to quantities + * Returns pet inventories by status + */ + async getInventoryRaw(): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.apiKey) { + headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication + } + + const response = await this.request({ + path: `/store/inventory`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response); + } + + /** + * Returns a map of status codes to quantities + * Returns pet inventories by status + */ + async getInventory(): Promise<{ [key: string]: number; }> { + const response = await this.getInventoryRaw(); + return await response.value(); + } + + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * Find purchase order by ID + */ + async getOrderByIdRaw(requestParameters: GetOrderByIdRequest): Promise> { + if (requestParameters.orderId === null || requestParameters.orderId === undefined) { + throw new runtime.RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling getOrderById.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => OrderFromJSON(jsonValue)); + } + + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * Find purchase order by ID + */ + async getOrderById(orderId: number): Promise { + const response = await this.getOrderByIdRaw({ orderId: orderId }); + return await response.value(); + } + + /** + * Place an order for a pet + */ + async placeOrderRaw(requestParameters: PlaceOrderRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling placeOrder.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/store/order`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: OrderToJSON(requestParameters.body), + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => OrderFromJSON(jsonValue)); + } + + /** + * Place an order for a pet + */ + async placeOrder(body: Order): Promise { + const response = await this.placeOrderRaw({ body: body }); + return await response.value(); + } + +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApiSagas.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApiSagas.ts new file mode 100644 index 00000000000..9752a7ea0fb --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApiSagas.ts @@ -0,0 +1,225 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import {Api} from './'; +import {List} from 'immutable'; +import {all, fork, put, takeLatest} from "redux-saga/effects"; +import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords"; +import {Action} from "redux-ts-simple"; + +import { + Order, + OrderRecord, + orderRecordUtils, +} from '../models'; + +const createSagaAction = (type: string) => originalCreateSagaAction(type, {namespace: "api_storeApi"}); + +export const storeApiSagaMap = new Map Generator>([ + ["deleteOrder", deleteOrderSaga], + ["getInventory", getInventorySaga], + ["getOrderById", getOrderByIdSaga], + ["placeOrder", placeOrderSaga], + ] +); + +export function *storeApiAllSagas() { + yield all([...storeApiSagaMap.values()].map(actionSaga => fork(actionSaga))); +} + +//region deleteOrder + +export interface PayloadDeleteOrder extends PayloadDeleteOrderRequest, BasePayloadApiAction { +} + +export interface PayloadDeleteOrderRequest { + orderId: string; +} + +export const deleteOrderRequest = createSagaAction("deleteOrderRequest"); +export const deleteOrderSuccess = createSagaAction("deleteOrderSuccess"); +export const deleteOrderFailure = createSagaAction<{error: any, requestPayload: PayloadDeleteOrder}>("deleteOrderFailure"); + +export const deleteOrder = createSagaAction("deleteOrder"); + +export function *deleteOrderSaga() { + yield takeLatest(deleteOrder, deleteOrderSagaImp); +} + +export function *deleteOrderSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + orderId, + } = _payloadRest_; + + yield put(deleteOrderRequest(_action_.payload)); + + const response = yield apiCall(Api.storeApi, Api.storeApi.deleteOrder, + orderId, + ); + + yield put(deleteOrderSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(deleteOrderFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region getInventory + +export interface PayloadGetInventory extends BasePayloadApiAction { +} + + +export const getInventoryRequest = createSagaAction("getInventoryRequest"); +export const getInventorySuccess = createSagaAction<{ [key: string]: number; }>("getInventorySuccess"); +export const getInventoryFailure = createSagaAction<{error: any, requestPayload: PayloadGetInventory}>("getInventoryFailure"); + +export const getInventory = createSagaAction("getInventory"); + +export function *getInventorySaga() { + yield takeLatest(getInventory, getInventorySagaImp); +} + +export function *getInventorySagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + + yield put(getInventoryRequest()); + + const response: Required<{ [key: string]: number; }> = yield apiCall(Api.storeApi, Api.storeApi.getInventory, + ); + + let successReturnValue: any = undefined; + yield put(getInventorySuccess(response)); + + return response; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getInventoryFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region getOrderById + +export interface PayloadGetOrderById extends PayloadGetOrderByIdRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadGetOrderByIdRequest { + orderId: string; +} + +export const getOrderByIdRequest = createSagaAction("getOrderByIdRequest"); +export const getOrderByIdSuccess = createSagaAction("getOrderByIdSuccess"); +export const getOrderByIdSuccess_Entities = createSagaAction("getOrderByIdSuccess_Entities"); +export const getOrderByIdFailure = createSagaAction<{error: any, requestPayload: PayloadGetOrderById}>("getOrderByIdFailure"); + +export const getOrderById = createSagaAction("getOrderById"); + +export function *getOrderByIdSaga() { + yield takeLatest(getOrderById, getOrderByIdSagaImp); +} + +export function *getOrderByIdSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + orderId, + } = _payloadRest_; + + yield put(getOrderByIdRequest(requestPayload)); + + const response: Required = yield apiCall(Api.storeApi, Api.storeApi.getOrderById, + parseFloat(orderId), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = orderRecordUtils.fromApiArrayAsEntities([response]); + yield put(normalizedEntities(successReturnValue)); + yield put(getOrderByIdSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = orderRecordUtils.fromApi(response); + yield put(getOrderByIdSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getOrderByIdFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region placeOrder + +export interface PayloadPlaceOrder extends PayloadPlaceOrderRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadPlaceOrderRequest { + body: OrderRecord; +} + +export const placeOrderRequest = createSagaAction("placeOrderRequest"); +export const placeOrderSuccess = createSagaAction("placeOrderSuccess"); +export const placeOrderSuccess_Entities = createSagaAction("placeOrderSuccess_Entities"); +export const placeOrderFailure = createSagaAction<{error: any, requestPayload: PayloadPlaceOrder}>("placeOrderFailure"); + +export const placeOrder = createSagaAction("placeOrder"); + +export function *placeOrderSaga() { + yield takeLatest(placeOrder, placeOrderSagaImp); +} + +export function *placeOrderSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + body, + } = _payloadRest_; + + yield put(placeOrderRequest(requestPayload)); + + const response: Required = yield apiCall(Api.storeApi, Api.storeApi.placeOrder, + orderRecordUtils.toApi(body), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = orderRecordUtils.fromApiArrayAsEntities([response]); + yield put(normalizedEntities(successReturnValue)); + yield put(placeOrderSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = orderRecordUtils.fromApi(response); + yield put(placeOrderSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(placeOrderFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApi.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApi.ts new file mode 100644 index 00000000000..1bc763f8066 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApi.ts @@ -0,0 +1,326 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import * as runtime from '../runtime'; +import { + DefaultMetaOnlyResponse, + DefaultMetaOnlyResponseFromJSON, + DefaultMetaOnlyResponseToJSON, + User, + UserFromJSON, + UserToJSON, +} from '../models'; + +export interface CreateUserRequest { + body: User; +} + +export interface CreateUsersWithArrayInputRequest { + body: Array; +} + +export interface CreateUsersWithListInputRequest { + body: Array; +} + +export interface DeleteUserRequest { + username: string; +} + +export interface GetUserByNameRequest { + username: string; +} + +export interface LoginUserRequest { + username: string; + password: string; +} + +export interface UpdateUserRequest { + username: string; + body: User; +} + +/** + * + */ +export class UserApi extends runtime.BaseAPI { + + /** + * This can only be done by the logged in user. + * Create user + */ + async createUserRaw(requestParameters: CreateUserRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUser.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/user`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: UserToJSON(requestParameters.body), + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * This can only be done by the logged in user. + * Create user + */ + async createUser(body: User): Promise { + await this.createUserRaw({ body: body }); + } + + /** + * Creates list of users with given input array + */ + async createUsersWithArrayInputRaw(requestParameters: CreateUsersWithArrayInputRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithArrayInput.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/user/createWithArray`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body.map(UserToJSON), + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Creates list of users with given input array + */ + async createUsersWithArrayInput(body: Array): Promise { + await this.createUsersWithArrayInputRaw({ body: body }); + } + + /** + * Creates list of users with given input array + */ + async createUsersWithListInputRaw(requestParameters: CreateUsersWithListInputRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithListInput.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/user/createWithList`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body.map(UserToJSON), + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Creates list of users with given input array + */ + async createUsersWithListInput(body: Array): Promise { + await this.createUsersWithListInputRaw({ body: body }); + } + + /** + * This can only be done by the logged in user. + * Delete user + */ + async deleteUserRaw(requestParameters: DeleteUserRequest): Promise> { + if (requestParameters.username === null || requestParameters.username === undefined) { + throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling deleteUser.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * This can only be done by the logged in user. + * Delete user + */ + async deleteUser(username: string): Promise { + await this.deleteUserRaw({ username: username }); + } + + /** + * Get user by user name + */ + async getUserByNameRaw(requestParameters: GetUserByNameRequest): Promise> { + if (requestParameters.username === null || requestParameters.username === undefined) { + throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling getUserByName.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => UserFromJSON(jsonValue)); + } + + /** + * Get user by user name + */ + async getUserByName(username: string): Promise { + const response = await this.getUserByNameRaw({ username: username }); + return await response.value(); + } + + /** + * Logs user into the system + */ + async loginUserRaw(requestParameters: LoginUserRequest): Promise> { + if (requestParameters.username === null || requestParameters.username === undefined) { + throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling loginUser.'); + } + + if (requestParameters.password === null || requestParameters.password === undefined) { + throw new runtime.RequiredError('password','Required parameter requestParameters.password was null or undefined when calling loginUser.'); + } + + const queryParameters: any = {}; + + if (requestParameters.username !== undefined) { + queryParameters['username'] = requestParameters.username; + } + + if (requestParameters.password !== undefined) { + queryParameters['password'] = requestParameters.password; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/user/login`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.TextApiResponse(response) as any; + } + + /** + * Logs user into the system + */ + async loginUser(username: string, password: string): Promise { + const response = await this.loginUserRaw({ username: username, password: password }); + return await response.value(); + } + + /** + * Logs out current logged in user session + */ + async logoutUserRaw(): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/user/logout`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Logs out current logged in user session + */ + async logoutUser(): Promise { + await this.logoutUserRaw(); + } + + /** + * This can only be done by the logged in user. + * Updated user + */ + async updateUserRaw(requestParameters: UpdateUserRequest): Promise> { + if (requestParameters.username === null || requestParameters.username === undefined) { + throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling updateUser.'); + } + + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updateUser.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + method: 'PUT', + headers: headerParameters, + query: queryParameters, + body: UserToJSON(requestParameters.body), + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => DefaultMetaOnlyResponseFromJSON(jsonValue)); + } + + /** + * This can only be done by the logged in user. + * Updated user + */ + async updateUser(username: string, body: User): Promise { + const response = await this.updateUserRaw({ username: username, body: body }); + return await response.value(); + } + +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApiSagas.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApiSagas.ts new file mode 100644 index 00000000000..9a2f070e145 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApiSagas.ts @@ -0,0 +1,395 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import {Api} from './'; +import {List} from 'immutable'; +import {all, fork, put, takeLatest} from "redux-saga/effects"; +import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords"; +import {Action} from "redux-ts-simple"; + +import { + DefaultMetaOnlyResponse, + DefaultMetaOnlyResponseRecord, + defaultMetaOnlyResponseRecordUtils, + User, + UserRecord, + userRecordUtils, +} from '../models'; + +const createSagaAction = (type: string) => originalCreateSagaAction(type, {namespace: "api_userApi"}); + +export const userApiSagaMap = new Map Generator>([ + ["createUser", createUserSaga], + ["createUsersWithArrayInput", createUsersWithArrayInputSaga], + ["createUsersWithListInput", createUsersWithListInputSaga], + ["deleteUser", deleteUserSaga], + ["getUserByName", getUserByNameSaga], + ["loginUser", loginUserSaga], + ["logoutUser", logoutUserSaga], + ["updateUser", updateUserSaga], + ] +); + +export function *userApiAllSagas() { + yield all([...userApiSagaMap.values()].map(actionSaga => fork(actionSaga))); +} + +//region createUser + +export interface PayloadCreateUser extends PayloadCreateUserRequest, BasePayloadApiAction { +} + +export interface PayloadCreateUserRequest { + body: UserRecord; +} + +export const createUserRequest = createSagaAction("createUserRequest"); +export const createUserSuccess = createSagaAction("createUserSuccess"); +export const createUserFailure = createSagaAction<{error: any, requestPayload: PayloadCreateUser}>("createUserFailure"); + +export const createUser = createSagaAction("createUser"); + +export function *createUserSaga() { + yield takeLatest(createUser, createUserSagaImp); +} + +export function *createUserSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + body, + } = _payloadRest_; + + yield put(createUserRequest(_action_.payload)); + + const response = yield apiCall(Api.userApi, Api.userApi.createUser, + userRecordUtils.toApi(body), + ); + + yield put(createUserSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(createUserFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region createUsersWithArrayInput + +export interface PayloadCreateUsersWithArrayInput extends PayloadCreateUsersWithArrayInputRequest, BasePayloadApiAction { +} + +export interface PayloadCreateUsersWithArrayInputRequest { + body: List; +} + +export const createUsersWithArrayInputRequest = createSagaAction("createUsersWithArrayInputRequest"); +export const createUsersWithArrayInputSuccess = createSagaAction("createUsersWithArrayInputSuccess"); +export const createUsersWithArrayInputFailure = createSagaAction<{error: any, requestPayload: PayloadCreateUsersWithArrayInput}>("createUsersWithArrayInputFailure"); + +export const createUsersWithArrayInput = createSagaAction("createUsersWithArrayInput"); + +export function *createUsersWithArrayInputSaga() { + yield takeLatest(createUsersWithArrayInput, createUsersWithArrayInputSagaImp); +} + +export function *createUsersWithArrayInputSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + body, + } = _payloadRest_; + + yield put(createUsersWithArrayInputRequest(_action_.payload)); + + const response = yield apiCall(Api.userApi, Api.userApi.createUsersWithArrayInput, + userRecordUtils.toApiArray(body), + ); + + yield put(createUsersWithArrayInputSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(createUsersWithArrayInputFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region createUsersWithListInput + +export interface PayloadCreateUsersWithListInput extends PayloadCreateUsersWithListInputRequest, BasePayloadApiAction { +} + +export interface PayloadCreateUsersWithListInputRequest { + body: List; +} + +export const createUsersWithListInputRequest = createSagaAction("createUsersWithListInputRequest"); +export const createUsersWithListInputSuccess = createSagaAction("createUsersWithListInputSuccess"); +export const createUsersWithListInputFailure = createSagaAction<{error: any, requestPayload: PayloadCreateUsersWithListInput}>("createUsersWithListInputFailure"); + +export const createUsersWithListInput = createSagaAction("createUsersWithListInput"); + +export function *createUsersWithListInputSaga() { + yield takeLatest(createUsersWithListInput, createUsersWithListInputSagaImp); +} + +export function *createUsersWithListInputSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + body, + } = _payloadRest_; + + yield put(createUsersWithListInputRequest(_action_.payload)); + + const response = yield apiCall(Api.userApi, Api.userApi.createUsersWithListInput, + userRecordUtils.toApiArray(body), + ); + + yield put(createUsersWithListInputSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(createUsersWithListInputFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region deleteUser + +export interface PayloadDeleteUser extends PayloadDeleteUserRequest, BasePayloadApiAction { +} + +export interface PayloadDeleteUserRequest { + username: string; +} + +export const deleteUserRequest = createSagaAction("deleteUserRequest"); +export const deleteUserSuccess = createSagaAction("deleteUserSuccess"); +export const deleteUserFailure = createSagaAction<{error: any, requestPayload: PayloadDeleteUser}>("deleteUserFailure"); + +export const deleteUser = createSagaAction("deleteUser"); + +export function *deleteUserSaga() { + yield takeLatest(deleteUser, deleteUserSagaImp); +} + +export function *deleteUserSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + username, + } = _payloadRest_; + + yield put(deleteUserRequest(_action_.payload)); + + const response = yield apiCall(Api.userApi, Api.userApi.deleteUser, + username, + ); + + yield put(deleteUserSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(deleteUserFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region getUserByName + +export interface PayloadGetUserByName extends PayloadGetUserByNameRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadGetUserByNameRequest { + username: string; +} + +export const getUserByNameRequest = createSagaAction("getUserByNameRequest"); +export const getUserByNameSuccess = createSagaAction("getUserByNameSuccess"); +export const getUserByNameSuccess_Entities = createSagaAction("getUserByNameSuccess_Entities"); +export const getUserByNameFailure = createSagaAction<{error: any, requestPayload: PayloadGetUserByName}>("getUserByNameFailure"); + +export const getUserByName = createSagaAction("getUserByName"); + +export function *getUserByNameSaga() { + yield takeLatest(getUserByName, getUserByNameSagaImp); +} + +export function *getUserByNameSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + username, + } = _payloadRest_; + + yield put(getUserByNameRequest(requestPayload)); + + const response: Required = yield apiCall(Api.userApi, Api.userApi.getUserByName, + username, + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = userRecordUtils.fromApiArrayAsEntities([response]); + yield put(normalizedEntities(successReturnValue)); + yield put(getUserByNameSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = userRecordUtils.fromApi(response); + yield put(getUserByNameSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getUserByNameFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region loginUser + +export interface PayloadLoginUser extends PayloadLoginUserRequest, BasePayloadApiAction { +} + +export interface PayloadLoginUserRequest { + username: string; + password: string; +} + +export const loginUserRequest = createSagaAction("loginUserRequest"); +export const loginUserSuccess = createSagaAction("loginUserSuccess"); +export const loginUserFailure = createSagaAction<{error: any, requestPayload: PayloadLoginUser}>("loginUserFailure"); + +export const loginUser = createSagaAction("loginUser"); + +export function *loginUserSaga() { + yield takeLatest(loginUser, loginUserSagaImp); +} + +export function *loginUserSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + username, + password, + } = _payloadRest_; + + yield put(loginUserRequest(_action_.payload)); + + const response: Required = yield apiCall(Api.userApi, Api.userApi.loginUser, + username, + password, + ); + + let successReturnValue: any = undefined; + yield put(loginUserSuccess(response)); + + return response; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(loginUserFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region logoutUser + +export interface PayloadLogoutUser extends BasePayloadApiAction { +} + + +export const logoutUserRequest = createSagaAction("logoutUserRequest"); +export const logoutUserSuccess = createSagaAction("logoutUserSuccess"); +export const logoutUserFailure = createSagaAction<{error: any, requestPayload: PayloadLogoutUser}>("logoutUserFailure"); + +export const logoutUser = createSagaAction("logoutUser"); + +export function *logoutUserSaga() { + yield takeLatest(logoutUser, logoutUserSagaImp); +} + +export function *logoutUserSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + + yield put(logoutUserRequest()); + + const response = yield apiCall(Api.userApi, Api.userApi.logoutUser, + ); + + yield put(logoutUserSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(logoutUserFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region updateUser + +export interface PayloadUpdateUser extends PayloadUpdateUserRequest, BasePayloadApiAction { +} + +export interface PayloadUpdateUserRequest { + username: string; + body: UserRecord; +} + +export const updateUserRequest = createSagaAction("updateUserRequest"); +export const updateUserSuccess = createSagaAction("updateUserSuccess"); +export const updateUserFailure = createSagaAction<{error: any, requestPayload: PayloadUpdateUser}>("updateUserFailure"); + +export const updateUser = createSagaAction("updateUser"); + +export function *updateUserSaga() { + yield takeLatest(updateUser, updateUserSagaImp); +} + +export function *updateUserSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + username, + body, + } = _payloadRest_; + + yield put(updateUserRequest(_action_.payload)); + + const response: Required = yield apiCall(Api.userApi, Api.userApi.updateUser, + username, + userRecordUtils.toApi(body), + ); + + yield put(updateUserSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(updateUserFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/allSagas.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/allSagas.ts new file mode 100644 index 00000000000..dae5870a93a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/allSagas.ts @@ -0,0 +1,19 @@ +import {all, fork} from "redux-saga/effects"; + +import { + behaviorApiAllSagas, + petApiAllSagas, + petPartApiAllSagas, + storeApiAllSagas, + userApiAllSagas, +} from "./"; + +export function *allApiSagas() { + yield all([ + fork(behaviorApiAllSagas), + fork(petApiAllSagas), + fork(petPartApiAllSagas), + fork(storeApiAllSagas), + fork(userApiAllSagas), + ]); +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/index.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/index.ts new file mode 100644 index 00000000000..4a025f4ed41 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/index.ts @@ -0,0 +1,12 @@ +export * from './SagaApiManager' +export * from './allSagas' +export * from './BehaviorApi'; +export * from './BehaviorApiSagas'; +export * from './PetApi'; +export * from './PetApiSagas'; +export * from './PetPartApi'; +export * from './PetPartApiSagas'; +export * from './StoreApi'; +export * from './StoreApiSagas'; +export * from './UserApi'; +export * from './UserApiSagas'; diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/index.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/index.ts new file mode 100644 index 00000000000..abbe33d5b20 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/index.ts @@ -0,0 +1,7 @@ +export * from './runtime'; +export * from './runtimeSagasAndRecords'; +export * from './ApiEntitiesRecord'; +export * from './ApiEntitiesReducer'; +export * from './ApiEntitiesSelectors'; +export * from './apis'; +export * from './models'; diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorType.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorType.ts new file mode 100644 index 00000000000..f10324a4775 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorType.ts @@ -0,0 +1,37 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Behavior type of a pet + * @export + * @enum {string} + */ +export enum BehaviorType { + Voluntary = 'Voluntary', + Involuntary = 'Involuntary', + Overt = 'Overt' +} + +export function BehaviorTypeFromJSON(json: any): BehaviorType { + return BehaviorTypeFromJSONTyped(json, false); +} + +export function BehaviorTypeFromJSONTyped(json: any, ignoreDiscriminator: boolean): BehaviorType { + return json as BehaviorType; +} + +export function BehaviorTypeToJSON(value?: BehaviorType | null): any { + return value as any; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorTypeRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorTypeRecord.ts new file mode 100644 index 00000000000..65fbcfab763 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorTypeRecord.ts @@ -0,0 +1 @@ +// This file is not needed and was generated only because of how codegen is built... Enums do not need to be converted to Records and can be used directly. diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Category.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Category.ts new file mode 100644 index 00000000000..faf9aabb9de --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Category.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * A category for a pet + * @export + * @interface Category + */ +export interface Category { + /** + * + * @type {number} + * @memberof Category + */ + id?: number; + /** + * + * @type {string} + * @memberof Category + */ + name?: string; +} + +export function CategoryFromJSON(json: any): Category { + return CategoryFromJSONTyped(json, false); +} + +export function CategoryFromJSONTyped(json: any, ignoreDiscriminator: boolean): Category { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'name': !exists(json, 'name') ? undefined : json['name'], + }; +} + +export function CategoryToJSON(value?: Category | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'name': value.name, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/CategoryRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/CategoryRecord.ts new file mode 100644 index 00000000000..f69d536f6ea --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/CategoryRecord.ts @@ -0,0 +1,104 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + Category, +} from './Category'; + + + +export const CategoryRecordProps = { + recType: "CategoryApiRecord" as "CategoryApiRecord", + id: null as string | null, + name: null as string | null, +}; + +export type CategoryRecordPropsType = typeof CategoryRecordProps; +export const CategoryRecord = Record(CategoryRecordProps, CategoryRecordProps.recType); +export type CategoryRecord = RecordOf; + +knownRecordFactories.set(CategoryRecordProps.recType, CategoryRecord); + +export const CategoryRecordEntityProps = { + ...CategoryRecordProps, + recType: "CategoryApiRecordEntity" as "CategoryApiRecordEntity", +}; + +export type CategoryRecordEntityPropsType = typeof CategoryRecordEntityProps; +export const CategoryRecordEntity = Record(CategoryRecordEntityProps, CategoryRecordEntityProps.recType); +export type CategoryRecordEntity = RecordOf; + +knownRecordFactories.set(CategoryRecordEntityProps.recType, CategoryRecordEntity); + +class CategoryRecordUtils extends ApiRecordUtils { + public normalize(apiObject: Category, asEntity?: boolean): Category { + (apiObject as any).recType = asEntity ? CategoryRecordEntityProps.recType : CategoryRecordProps.recType; + if (apiObject.id) { (apiObject as any).id = apiObject.id.toString(); } + return apiObject; + } + + public getSchema(): Schema { + return new schema.Entity("category", { + }); + } + + public *toInlined(entityId?: string | null) { + if (!entityId) {return undefined; } + const entity = yield select(apiEntityCategorySelector, {id: entityId}); + if (!entity) {return undefined; } + + const { + recType, + ...unchangedProperties + } = entity; + + const entityProperties = { + } + + return CategoryRecord({ + ...unchangedProperties, + ...entityProperties + }); + } + + public *toInlinedArray(entityIds: List | null) { + if (!entityIds) {return null; } + let entities = List(); + for (let entityIndex = 0; entityIndex < entityIds.count(); entityIndex++) { + const entity = yield call(this.toInlined, entityIds.get(entityIndex)); + if (entity) { + entities.push(entity); + } + } + return entities; + } + + public toApi(record: CategoryRecord): Category { + const apiObject = super.toApi(record); + if (record.id) { apiObject.id = parseFloat(record.id); } + return apiObject; + } +} + +export const categoryRecordUtils = new CategoryRecordUtils(); + +export const apiEntitiesCategorySelector = (state: any) => getApiEntitiesState(state).category as Map; +export const apiEntityCategorySelector = (state: any, {id}: {id?: string | null}) => id ? apiEntitiesCategorySelector(state).get(id) : undefined; + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponse.ts new file mode 100644 index 00000000000..b6ac416539a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponse.ts @@ -0,0 +1,64 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import { + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, +} from './'; + +/** + * + * @export + * @interface DefaultMetaOnlyResponse + */ +export interface DefaultMetaOnlyResponse { + /** + * + * @type {ResponseMeta} + * @memberof DefaultMetaOnlyResponse + */ + meta: ResponseMeta; +} + +export function DefaultMetaOnlyResponseFromJSON(json: any): DefaultMetaOnlyResponse { + return DefaultMetaOnlyResponseFromJSONTyped(json, false); +} + +export function DefaultMetaOnlyResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): DefaultMetaOnlyResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + }; +} + +export function DefaultMetaOnlyResponseToJSON(value?: DefaultMetaOnlyResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponseRecord.ts new file mode 100644 index 00000000000..b59a715e84c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponseRecord.ts @@ -0,0 +1,62 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + DefaultMetaOnlyResponse, +} from './DefaultMetaOnlyResponse'; + +import { + ResponseMeta, +} from './ResponseMeta'; + +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; + +export const DefaultMetaOnlyResponseRecordProps = { + recType: "DefaultMetaOnlyResponseApiRecord" as "DefaultMetaOnlyResponseApiRecord", + meta: ResponseMetaRecord(), +}; + +export type DefaultMetaOnlyResponseRecordPropsType = typeof DefaultMetaOnlyResponseRecordProps; +export const DefaultMetaOnlyResponseRecord = Record(DefaultMetaOnlyResponseRecordProps, DefaultMetaOnlyResponseRecordProps.recType); +export type DefaultMetaOnlyResponseRecord = RecordOf; + +knownRecordFactories.set(DefaultMetaOnlyResponseRecordProps.recType, DefaultMetaOnlyResponseRecord); + + +class DefaultMetaOnlyResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: DefaultMetaOnlyResponse, asEntity?: boolean): DefaultMetaOnlyResponse { + (apiObject as any).recType = DefaultMetaOnlyResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + return apiObject; + } + + public toApi(record: DefaultMetaOnlyResponseRecord): DefaultMetaOnlyResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + return apiObject; + } +} + +export const defaultMetaOnlyResponseRecordUtils = new DefaultMetaOnlyResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatus.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatus.ts new file mode 100644 index 00000000000..0a24b4b493f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatus.ts @@ -0,0 +1,46 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Status of the deployment request + * @export + * @enum {string} + */ +export enum DeploymentRequestStatus { + New = 'New', + Prepared = 'Prepared', + Printed = 'Printed', + Tested = 'Tested', + Completed = 'Completed', + Cancelled = 'Cancelled', + Promoted = 'Promoted', + Assigned = 'Assigned', + Ready = 'Ready', + Packaged = 'Packaged', + Pairing = 'Pairing', + Paired = 'Paired' +} + +export function DeploymentRequestStatusFromJSON(json: any): DeploymentRequestStatus { + return DeploymentRequestStatusFromJSONTyped(json, false); +} + +export function DeploymentRequestStatusFromJSONTyped(json: any, ignoreDiscriminator: boolean): DeploymentRequestStatus { + return json as DeploymentRequestStatus; +} + +export function DeploymentRequestStatusToJSON(value?: DeploymentRequestStatus | null): any { + return value as any; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatusRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatusRecord.ts new file mode 100644 index 00000000000..65fbcfab763 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatusRecord.ts @@ -0,0 +1 @@ +// This file is not needed and was generated only because of how codegen is built... Enums do not need to be converted to Records and can be used directly. diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCode.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCode.ts new file mode 100644 index 00000000000..101539269e4 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCode.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Error code returned when an error occurs + * @export + * @enum {string} + */ +export enum ErrorCode { + VolumeRangeAtLowestValue = 'Volume_Range_At_Lowest_Value', + MusicVolumeBlocksVolumeRangeDecrease = 'Music_Volume_Blocks_Volume_Range_Decrease', + VolumeRangeAtHighestValue = 'Volume_Range_At_Highest_Value', + MaximumVolumeBlocksVolumeRangeIncrease = 'Maximum_Volume_Blocks_Volume_Range_Increase', + MusicVolumeBlocksMaximumVolumeDecrease = 'Music_Volume_Blocks_Maximum_Volume_Decrease', + MaximumVolumeAtLowestValue = 'Maximum_Volume_At_Lowest_Value', + VolumeRangeBlocksMaximumVolumeDecrease = 'Volume_Range_Blocks_Maximum_Volume_Decrease', + MaximumVolumeAtHighestValue = 'Maximum_Volume_At_Highest_Value', + MessageGainBlocksMaximumVolumeIncrease = 'Message_Gain_Blocks_Maximum_Volume_Increase', + MusicVolumeBlocksMaximumVolumeIncrease = 'Music_Volume_Blocks_Maximum_Volume_Increase', + MaximumVolumeBlocksMessageGainDecrease = 'Maximum_Volume_Blocks_Message_Gain_Decrease', + MessageGainAtHighestValue = 'Message_Gain_At_Highest_Value', + MusicVolumeBlocksMessageGain = 'Music_Volume_Blocks_Message_Gain', + MaximumMessageGainLowerThanMinimum = 'Maximum_Message_Gain_Lower_Than_Minimum', + MaximumMessageGainHigherThanMaximum = 'Maximum_Message_Gain_Higher_Than_Maximum', + MaximumMessageGainLowerThanMessageGain = 'Maximum_Message_Gain_Lower_Than_Message_Gain', + MinimumVolumeBlocksMusicVolumeDecrease = 'Minimum_Volume_Blocks_Music_Volume_Decrease', + MaximumVolumeBlocksMusicVolumeIncrease = 'Maximum_Volume_Blocks_Music_Volume_Increase' +} + +export function ErrorCodeFromJSON(json: any): ErrorCode { + return ErrorCodeFromJSONTyped(json, false); +} + +export function ErrorCodeFromJSONTyped(json: any, ignoreDiscriminator: boolean): ErrorCode { + return json as ErrorCode; +} + +export function ErrorCodeToJSON(value?: ErrorCode | null): any { + return value as any; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCodeRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCodeRecord.ts new file mode 100644 index 00000000000..65fbcfab763 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCodeRecord.ts @@ -0,0 +1 @@ +// This file is not needed and was generated only because of how codegen is built... Enums do not need to be converted to Records and can be used directly. diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponse.ts new file mode 100644 index 00000000000..6118e070e10 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponse.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import { + Pet, + PetFromJSON, + PetFromJSONTyped, + PetToJSON, + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, +} from './'; + +/** + * + * @export + * @interface FindPetsByStatusResponse + */ +export interface FindPetsByStatusResponse { + /** + * + * @type {ResponseMeta} + * @memberof FindPetsByStatusResponse + */ + meta: ResponseMeta; + /** + * + * @type {Array} + * @memberof FindPetsByStatusResponse + */ + data?: Array; +} + +export function FindPetsByStatusResponseFromJSON(json: any): FindPetsByStatusResponse { + return FindPetsByStatusResponseFromJSONTyped(json, false); +} + +export function FindPetsByStatusResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): FindPetsByStatusResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + 'data': !exists(json, 'data') ? undefined : ((json['data'] as Array).map(PetFromJSON)), + }; +} + +export function FindPetsByStatusResponseToJSON(value?: FindPetsByStatusResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + 'data': value.data === undefined ? undefined : ((value.data as Array).map(PetToJSON)), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponseRecord.ts new file mode 100644 index 00000000000..3ac38102f82 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponseRecord.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories, appFromJS, NormalizedRecordEntities} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + FindPetsByStatusResponse, +} from './FindPetsByStatusResponse'; + +import { + Pet, +} from './Pet'; +import { + ResponseMeta, +} from './ResponseMeta'; + +import { + PetRecord, + petRecordUtils +} from './PetRecord'; +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; + +export const FindPetsByStatusResponseRecordProps = { + recType: "FindPetsByStatusResponseApiRecord" as "FindPetsByStatusResponseApiRecord", + meta: ResponseMetaRecord(), + data: (PetRecord(), null as List | null), +}; + +export type FindPetsByStatusResponseRecordPropsType = typeof FindPetsByStatusResponseRecordProps; +export const FindPetsByStatusResponseRecord = Record(FindPetsByStatusResponseRecordProps, FindPetsByStatusResponseRecordProps.recType); +export type FindPetsByStatusResponseRecord = RecordOf; + +knownRecordFactories.set(FindPetsByStatusResponseRecordProps.recType, FindPetsByStatusResponseRecord); + + +class FindPetsByStatusResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: FindPetsByStatusResponse, asEntity?: boolean): FindPetsByStatusResponse { + (apiObject as any).recType = FindPetsByStatusResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + if (apiObject.data) { petRecordUtils.normalizeArray(apiObject.data); } + return apiObject; + } + + public toApi(record: FindPetsByStatusResponseRecord): FindPetsByStatusResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + if (record.data) { apiObject.data = petRecordUtils.toApiArray(record.data); } + return apiObject; + } + + public fromApiPassthrough(apiObject: FindPetsByStatusResponse): List { + if (!apiObject.data) {return List(); } + const normalizedApiObject = petRecordUtils.normalizeArray(apiObject.data); + return appFromJS(normalizedApiObject); + } + + public fromApiPassthroughAsEntities(apiObject: FindPetsByStatusResponse): NormalizedRecordEntities { + if (!apiObject.data) {return {entities: {}, result: List()}; } + return ApiRecordUtils.toNormalizedRecordEntities(petRecordUtils.normalizeArrayAsEntities(apiObject.data), true); + } +} + +export const findPetsByStatusResponseRecordUtils = new FindPetsByStatusResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponse.ts new file mode 100644 index 00000000000..9f010d3b32b --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponse.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import { + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, + User, + UserFromJSON, + UserFromJSONTyped, + UserToJSON, +} from './'; + +/** + * + * @export + * @interface FindPetsByUserResponse + */ +export interface FindPetsByUserResponse { + /** + * + * @type {ResponseMeta} + * @memberof FindPetsByUserResponse + */ + meta: ResponseMeta; + /** + * + * @type {Array} + * @memberof FindPetsByUserResponse + */ + data?: Array; +} + +export function FindPetsByUserResponseFromJSON(json: any): FindPetsByUserResponse { + return FindPetsByUserResponseFromJSONTyped(json, false); +} + +export function FindPetsByUserResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): FindPetsByUserResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + 'data': !exists(json, 'data') ? undefined : ((json['data'] as Array).map(UserFromJSON)), + }; +} + +export function FindPetsByUserResponseToJSON(value?: FindPetsByUserResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + 'data': value.data === undefined ? undefined : ((value.data as Array).map(UserToJSON)), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponseRecord.ts new file mode 100644 index 00000000000..b1cddadbf54 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponseRecord.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories, appFromJS, NormalizedRecordEntities} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + FindPetsByUserResponse, +} from './FindPetsByUserResponse'; + +import { + ResponseMeta, +} from './ResponseMeta'; +import { + User, +} from './User'; + +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; +import { + UserRecord, + userRecordUtils +} from './UserRecord'; + +export const FindPetsByUserResponseRecordProps = { + recType: "FindPetsByUserResponseApiRecord" as "FindPetsByUserResponseApiRecord", + meta: ResponseMetaRecord(), + data: (UserRecord(), null as List | null), +}; + +export type FindPetsByUserResponseRecordPropsType = typeof FindPetsByUserResponseRecordProps; +export const FindPetsByUserResponseRecord = Record(FindPetsByUserResponseRecordProps, FindPetsByUserResponseRecordProps.recType); +export type FindPetsByUserResponseRecord = RecordOf; + +knownRecordFactories.set(FindPetsByUserResponseRecordProps.recType, FindPetsByUserResponseRecord); + + +class FindPetsByUserResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: FindPetsByUserResponse, asEntity?: boolean): FindPetsByUserResponse { + (apiObject as any).recType = FindPetsByUserResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + if (apiObject.data) { userRecordUtils.normalizeArray(apiObject.data); } + return apiObject; + } + + public toApi(record: FindPetsByUserResponseRecord): FindPetsByUserResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + if (record.data) { apiObject.data = userRecordUtils.toApiArray(record.data); } + return apiObject; + } + + public fromApiPassthrough(apiObject: FindPetsByUserResponse): List { + if (!apiObject.data) {return List(); } + const normalizedApiObject = userRecordUtils.normalizeArray(apiObject.data); + return appFromJS(normalizedApiObject); + } + + public fromApiPassthroughAsEntities(apiObject: FindPetsByUserResponse): NormalizedRecordEntities { + if (!apiObject.data) {return {entities: {}, result: List()}; } + return ApiRecordUtils.toNormalizedRecordEntities(userRecordUtils.normalizeArrayAsEntities(apiObject.data), true); + } +} + +export const findPetsByUserResponseRecordUtils = new FindPetsByUserResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponse.ts new file mode 100644 index 00000000000..98f03260391 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponse.ts @@ -0,0 +1,72 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import { + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, +} from './'; + +/** + * + * @export + * @interface GetBehaviorPermissionsResponse + */ +export interface GetBehaviorPermissionsResponse { + /** + * + * @type {ResponseMeta} + * @memberof GetBehaviorPermissionsResponse + */ + meta: ResponseMeta; + /** + * + * @type {{ [key: string]: boolean; }} + * @memberof GetBehaviorPermissionsResponse + */ + data?: { [key: string]: boolean; }; +} + +export function GetBehaviorPermissionsResponseFromJSON(json: any): GetBehaviorPermissionsResponse { + return GetBehaviorPermissionsResponseFromJSONTyped(json, false); +} + +export function GetBehaviorPermissionsResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetBehaviorPermissionsResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + 'data': !exists(json, 'data') ? undefined : json['data'], + }; +} + +export function GetBehaviorPermissionsResponseToJSON(value?: GetBehaviorPermissionsResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + 'data': value.data, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponseRecord.ts new file mode 100644 index 00000000000..eb7f7fdd70f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponseRecord.ts @@ -0,0 +1,72 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories, appFromJS, NormalizedRecordEntities} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + GetBehaviorPermissionsResponse, +} from './GetBehaviorPermissionsResponse'; + +import { + ResponseMeta, +} from './ResponseMeta'; + +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; + +export const GetBehaviorPermissionsResponseRecordProps = { + recType: "GetBehaviorPermissionsResponseApiRecord" as "GetBehaviorPermissionsResponseApiRecord", + meta: ResponseMetaRecord(), + data: null as { [key: string]: boolean; } | null, +}; + +export type GetBehaviorPermissionsResponseRecordPropsType = typeof GetBehaviorPermissionsResponseRecordProps; +export const GetBehaviorPermissionsResponseRecord = Record(GetBehaviorPermissionsResponseRecordProps, GetBehaviorPermissionsResponseRecordProps.recType); +export type GetBehaviorPermissionsResponseRecord = RecordOf; + +knownRecordFactories.set(GetBehaviorPermissionsResponseRecordProps.recType, GetBehaviorPermissionsResponseRecord); + + +class GetBehaviorPermissionsResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: GetBehaviorPermissionsResponse, asEntity?: boolean): GetBehaviorPermissionsResponse { + (apiObject as any).recType = GetBehaviorPermissionsResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + return apiObject; + } + + public toApi(record: GetBehaviorPermissionsResponseRecord): GetBehaviorPermissionsResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + return apiObject; + } + + public fromApiPassthrough(apiObject: GetBehaviorPermissionsResponse): { [key: string]: boolean; } { + return apiObject.data!; + } + + public fromApiPassthroughAsEntities(apiObject: GetBehaviorPermissionsResponse): NormalizedRecordEntities { + console.log("entities revival not supported on this response"); + return {entities: {}, result: List()}; + } +} + +export const getBehaviorPermissionsResponseRecordUtils = new GetBehaviorPermissionsResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponse.ts new file mode 100644 index 00000000000..da5e918c40f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponse.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import { + BehaviorType, + BehaviorTypeFromJSON, + BehaviorTypeFromJSONTyped, + BehaviorTypeToJSON, + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, +} from './'; + +/** + * + * @export + * @interface GetBehaviorTypeResponse + */ +export interface GetBehaviorTypeResponse { + /** + * + * @type {ResponseMeta} + * @memberof GetBehaviorTypeResponse + */ + meta: ResponseMeta; + /** + * + * @type {BehaviorType} + * @memberof GetBehaviorTypeResponse + */ + data?: BehaviorType; +} + +export function GetBehaviorTypeResponseFromJSON(json: any): GetBehaviorTypeResponse { + return GetBehaviorTypeResponseFromJSONTyped(json, false); +} + +export function GetBehaviorTypeResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetBehaviorTypeResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + 'data': !exists(json, 'data') ? undefined : BehaviorTypeFromJSON(json['data']), + }; +} + +export function GetBehaviorTypeResponseToJSON(value?: GetBehaviorTypeResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + 'data': BehaviorTypeToJSON(value.data), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponseRecord.ts new file mode 100644 index 00000000000..7113f4a6aa2 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponseRecord.ts @@ -0,0 +1,75 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories, appFromJS, NormalizedRecordEntities} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + GetBehaviorTypeResponse, +} from './GetBehaviorTypeResponse'; + +import { + BehaviorType, +} from './BehaviorType'; +import { + ResponseMeta, +} from './ResponseMeta'; + +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; + +export const GetBehaviorTypeResponseRecordProps = { + recType: "GetBehaviorTypeResponseApiRecord" as "GetBehaviorTypeResponseApiRecord", + meta: ResponseMetaRecord(), + data: null as BehaviorType | null, +}; + +export type GetBehaviorTypeResponseRecordPropsType = typeof GetBehaviorTypeResponseRecordProps; +export const GetBehaviorTypeResponseRecord = Record(GetBehaviorTypeResponseRecordProps, GetBehaviorTypeResponseRecordProps.recType); +export type GetBehaviorTypeResponseRecord = RecordOf; + +knownRecordFactories.set(GetBehaviorTypeResponseRecordProps.recType, GetBehaviorTypeResponseRecord); + + +class GetBehaviorTypeResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: GetBehaviorTypeResponse, asEntity?: boolean): GetBehaviorTypeResponse { + (apiObject as any).recType = GetBehaviorTypeResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + return apiObject; + } + + public toApi(record: GetBehaviorTypeResponseRecord): GetBehaviorTypeResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + return apiObject; + } + + public fromApiPassthrough(apiObject: GetBehaviorTypeResponse): BehaviorType { + return apiObject.data!; + } + + public fromApiPassthroughAsEntities(apiObject: GetBehaviorTypeResponse): NormalizedRecordEntities { + console.log("entities revival not supported on this response"); + return {entities: {}, result: List()}; + } +} + +export const getBehaviorTypeResponseRecordUtils = new GetBehaviorTypeResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponse.ts new file mode 100644 index 00000000000..ea8f86a0252 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponse.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import { + MatchingParts, + MatchingPartsFromJSON, + MatchingPartsFromJSONTyped, + MatchingPartsToJSON, + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, +} from './'; + +/** + * + * @export + * @interface GetMatchingPartsResponse + */ +export interface GetMatchingPartsResponse { + /** + * + * @type {ResponseMeta} + * @memberof GetMatchingPartsResponse + */ + meta: ResponseMeta; + /** + * + * @type {MatchingParts} + * @memberof GetMatchingPartsResponse + */ + data?: MatchingParts; +} + +export function GetMatchingPartsResponseFromJSON(json: any): GetMatchingPartsResponse { + return GetMatchingPartsResponseFromJSONTyped(json, false); +} + +export function GetMatchingPartsResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetMatchingPartsResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + 'data': !exists(json, 'data') ? undefined : MatchingPartsFromJSON(json['data']), + }; +} + +export function GetMatchingPartsResponseToJSON(value?: GetMatchingPartsResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + 'data': MatchingPartsToJSON(value.data), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponseRecord.ts new file mode 100644 index 00000000000..6b73951b1df --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponseRecord.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories, appFromJS, NormalizedRecordEntities} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + GetMatchingPartsResponse, +} from './GetMatchingPartsResponse'; + +import { + MatchingParts, +} from './MatchingParts'; +import { + ResponseMeta, +} from './ResponseMeta'; + +import { + MatchingPartsRecord, + matchingPartsRecordUtils +} from './MatchingPartsRecord'; +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; + +export const GetMatchingPartsResponseRecordProps = { + recType: "GetMatchingPartsResponseApiRecord" as "GetMatchingPartsResponseApiRecord", + meta: ResponseMetaRecord(), + data: (MatchingPartsRecord(), null as MatchingPartsRecord | null), +}; + +export type GetMatchingPartsResponseRecordPropsType = typeof GetMatchingPartsResponseRecordProps; +export const GetMatchingPartsResponseRecord = Record(GetMatchingPartsResponseRecordProps, GetMatchingPartsResponseRecordProps.recType); +export type GetMatchingPartsResponseRecord = RecordOf; + +knownRecordFactories.set(GetMatchingPartsResponseRecordProps.recType, GetMatchingPartsResponseRecord); + + +class GetMatchingPartsResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: GetMatchingPartsResponse, asEntity?: boolean): GetMatchingPartsResponse { + (apiObject as any).recType = GetMatchingPartsResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + if (apiObject.data) { matchingPartsRecordUtils.normalize(apiObject.data); } + return apiObject; + } + + public toApi(record: GetMatchingPartsResponseRecord): GetMatchingPartsResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + if (record.data) { apiObject.data = matchingPartsRecordUtils.toApi(record.data); } + return apiObject; + } + + public fromApiPassthrough(apiObject: GetMatchingPartsResponse): MatchingPartsRecord { + if (!apiObject.data) {return MatchingPartsRecord(); } + const normalizedApiObject = matchingPartsRecordUtils.normalize(apiObject.data); + return appFromJS(normalizedApiObject); + } + + public fromApiPassthroughAsEntities(apiObject: GetMatchingPartsResponse): NormalizedRecordEntities { + console.log("entities revival not supported on this response"); + return {entities: {}, result: List()}; + } +} + +export const getMatchingPartsResponseRecordUtils = new GetMatchingPartsResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponse.ts new file mode 100644 index 00000000000..b0b43d1b96b --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponse.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import { + PetPartType, + PetPartTypeFromJSON, + PetPartTypeFromJSONTyped, + PetPartTypeToJSON, + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, +} from './'; + +/** + * + * @export + * @interface GetPetPartTypeResponse + */ +export interface GetPetPartTypeResponse { + /** + * + * @type {ResponseMeta} + * @memberof GetPetPartTypeResponse + */ + meta: ResponseMeta; + /** + * + * @type {PetPartType} + * @memberof GetPetPartTypeResponse + */ + data?: PetPartType; +} + +export function GetPetPartTypeResponseFromJSON(json: any): GetPetPartTypeResponse { + return GetPetPartTypeResponseFromJSONTyped(json, false); +} + +export function GetPetPartTypeResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetPetPartTypeResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + 'data': !exists(json, 'data') ? undefined : PetPartTypeFromJSON(json['data']), + }; +} + +export function GetPetPartTypeResponseToJSON(value?: GetPetPartTypeResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + 'data': PetPartTypeToJSON(value.data), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponseRecord.ts new file mode 100644 index 00000000000..69caf5d0546 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponseRecord.ts @@ -0,0 +1,75 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories, appFromJS, NormalizedRecordEntities} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + GetPetPartTypeResponse, +} from './GetPetPartTypeResponse'; + +import { + PetPartType, +} from './PetPartType'; +import { + ResponseMeta, +} from './ResponseMeta'; + +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; + +export const GetPetPartTypeResponseRecordProps = { + recType: "GetPetPartTypeResponseApiRecord" as "GetPetPartTypeResponseApiRecord", + meta: ResponseMetaRecord(), + data: null as PetPartType | null, +}; + +export type GetPetPartTypeResponseRecordPropsType = typeof GetPetPartTypeResponseRecordProps; +export const GetPetPartTypeResponseRecord = Record(GetPetPartTypeResponseRecordProps, GetPetPartTypeResponseRecordProps.recType); +export type GetPetPartTypeResponseRecord = RecordOf; + +knownRecordFactories.set(GetPetPartTypeResponseRecordProps.recType, GetPetPartTypeResponseRecord); + + +class GetPetPartTypeResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: GetPetPartTypeResponse, asEntity?: boolean): GetPetPartTypeResponse { + (apiObject as any).recType = GetPetPartTypeResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + return apiObject; + } + + public toApi(record: GetPetPartTypeResponseRecord): GetPetPartTypeResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + return apiObject; + } + + public fromApiPassthrough(apiObject: GetPetPartTypeResponse): PetPartType { + return apiObject.data!; + } + + public fromApiPassthroughAsEntities(apiObject: GetPetPartTypeResponse): NormalizedRecordEntities { + console.log("entities revival not supported on this response"); + return {entities: {}, result: List()}; + } +} + +export const getPetPartTypeResponseRecordUtils = new GetPetPartTypeResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemId.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemId.ts new file mode 100644 index 00000000000..c158400740c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemId.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * Simplified identifier of an item + * @export + * @interface ItemId + */ +export interface ItemId { + /** + * Unique identifier of the item + * @type {string} + * @memberof ItemId + */ + id: string; + /** + * playlist + * @type {string} + * @memberof ItemId + */ + type: string; +} + +export function ItemIdFromJSON(json: any): ItemId { + return ItemIdFromJSONTyped(json, false); +} + +export function ItemIdFromJSONTyped(json: any, ignoreDiscriminator: boolean): ItemId { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': json['id'], + 'type': json['type'], + }; +} + +export function ItemIdToJSON(value?: ItemId | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'type': value.type, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemIdRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemIdRecord.ts new file mode 100644 index 00000000000..6980c92e9b8 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemIdRecord.ts @@ -0,0 +1,54 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + ItemId, +} from './ItemId'; + + + +export const ItemIdRecordProps = { + recType: "ItemIdApiRecord" as "ItemIdApiRecord", + id: "", + type: "", +}; + +export type ItemIdRecordPropsType = typeof ItemIdRecordProps; +export const ItemIdRecord = Record(ItemIdRecordProps, ItemIdRecordProps.recType); +export type ItemIdRecord = RecordOf; + +knownRecordFactories.set(ItemIdRecordProps.recType, ItemIdRecord); + + +class ItemIdRecordUtils extends ApiRecordUtils { + public normalize(apiObject: ItemId, asEntity?: boolean): ItemId { + (apiObject as any).recType = ItemIdRecordProps.recType; + return apiObject; + } + + public toApi(record: ItemIdRecord): ItemId { + const apiObject = super.toApi(record); + return apiObject; + } +} + +export const itemIdRecordUtils = new ItemIdRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingParts.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingParts.ts new file mode 100644 index 00000000000..790f42e9a53 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingParts.ts @@ -0,0 +1,72 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import { + Part, + PartFromJSON, + PartFromJSONTyped, + PartToJSON, +} from './'; + +/** + * Contains all the matching parts + * @export + * @interface MatchingParts + */ +export interface MatchingParts { + /** + * List of all the connected parts + * @type {Array} + * @memberof MatchingParts + */ + connected: Array; + /** + * List of all the related parts + * @type {Array} + * @memberof MatchingParts + */ + related: Array; +} + +export function MatchingPartsFromJSON(json: any): MatchingParts { + return MatchingPartsFromJSONTyped(json, false); +} + +export function MatchingPartsFromJSONTyped(json: any, ignoreDiscriminator: boolean): MatchingParts { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'connected': ((json['connected'] as Array).map(PartFromJSON)), + 'related': ((json['related'] as Array).map(PartFromJSON)), + }; +} + +export function MatchingPartsToJSON(value?: MatchingParts | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'connected': ((value.connected as Array).map(PartToJSON)), + 'related': ((value.related as Array).map(PartToJSON)), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingPartsRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingPartsRecord.ts new file mode 100644 index 00000000000..edc7d033ebd --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingPartsRecord.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + MatchingParts, +} from './MatchingParts'; + +import { + Part, +} from './Part'; + +import { + PartRecord, + partRecordUtils +} from './PartRecord'; + +export const MatchingPartsRecordProps = { + recType: "MatchingPartsApiRecord" as "MatchingPartsApiRecord", + connected: (PartRecord(), List()), + related: (PartRecord(), List()), +}; + +export type MatchingPartsRecordPropsType = typeof MatchingPartsRecordProps; +export const MatchingPartsRecord = Record(MatchingPartsRecordProps, MatchingPartsRecordProps.recType); +export type MatchingPartsRecord = RecordOf; + +knownRecordFactories.set(MatchingPartsRecordProps.recType, MatchingPartsRecord); + + +class MatchingPartsRecordUtils extends ApiRecordUtils { + public normalize(apiObject: MatchingParts, asEntity?: boolean): MatchingParts { + (apiObject as any).recType = MatchingPartsRecordProps.recType; + partRecordUtils.normalizeArray(apiObject.connected); + partRecordUtils.normalizeArray(apiObject.related); + return apiObject; + } + + public toApi(record: MatchingPartsRecord): MatchingParts { + const apiObject = super.toApi(record); + apiObject.connected = partRecordUtils.toApiArray(record.connected); + apiObject.related = partRecordUtils.toApiArray(record.related); + return apiObject; + } +} + +export const matchingPartsRecordUtils = new MatchingPartsRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponse.ts new file mode 100644 index 00000000000..63fa57adc03 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponse.ts @@ -0,0 +1,73 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * Describes the result of uploading an image resource + * @export + * @interface ModelApiResponse + */ +export interface ModelApiResponse { + /** + * + * @type {number} + * @memberof ModelApiResponse + */ + code?: number; + /** + * + * @type {string} + * @memberof ModelApiResponse + */ + type?: string; + /** + * + * @type {string} + * @memberof ModelApiResponse + */ + message?: string; +} + +export function ModelApiResponseFromJSON(json: any): ModelApiResponse { + return ModelApiResponseFromJSONTyped(json, false); +} + +export function ModelApiResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ModelApiResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'code': !exists(json, 'code') ? undefined : json['code'], + 'type': !exists(json, 'type') ? undefined : json['type'], + 'message': !exists(json, 'message') ? undefined : json['message'], + }; +} + +export function ModelApiResponseToJSON(value?: ModelApiResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'code': value.code, + 'type': value.type, + 'message': value.message, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponseRecord.ts new file mode 100644 index 00000000000..6a246575576 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponseRecord.ts @@ -0,0 +1,55 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + ModelApiResponse, +} from './ModelApiResponse'; + + + +export const ModelApiResponseRecordProps = { + recType: "ModelApiResponseApiRecord" as "ModelApiResponseApiRecord", + code: null as number | null, + type: null as string | null, + message: null as string | null, +}; + +export type ModelApiResponseRecordPropsType = typeof ModelApiResponseRecordProps; +export const ModelApiResponseRecord = Record(ModelApiResponseRecordProps, ModelApiResponseRecordProps.recType); +export type ModelApiResponseRecord = RecordOf; + +knownRecordFactories.set(ModelApiResponseRecordProps.recType, ModelApiResponseRecord); + + +class ModelApiResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: ModelApiResponse, asEntity?: boolean): ModelApiResponse { + (apiObject as any).recType = ModelApiResponseRecordProps.recType; + return apiObject; + } + + public toApi(record: ModelApiResponseRecord): ModelApiResponse { + const apiObject = super.toApi(record); + return apiObject; + } +} + +export const modelApiResponseRecordUtils = new ModelApiResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelError.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelError.ts new file mode 100644 index 00000000000..be3cda0de1b --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelError.ts @@ -0,0 +1,88 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import { + ItemId, + ItemIdFromJSON, + ItemIdFromJSONTyped, + ItemIdToJSON, +} from './'; + +/** + * This represent an error normally linked to a specific item from a previous request + * @export + * @interface ModelError + */ +export interface ModelError { + /** + * Usually contains the simple name of the exception + * @type {string} + * @memberof ModelError + */ + type: string; + /** + * + * @type {ItemId} + * @memberof ModelError + */ + itemInfo?: ItemId; + /** + * Simple explanation of the error + * @type {string} + * @memberof ModelError + */ + details?: string; + /** + * Message of the exception that will help developer to debug this problem if needed + * @type {string} + * @memberof ModelError + */ + exception?: string; +} + +export function ModelErrorFromJSON(json: any): ModelError { + return ModelErrorFromJSONTyped(json, false); +} + +export function ModelErrorFromJSONTyped(json: any, ignoreDiscriminator: boolean): ModelError { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'type': json['type'], + 'itemInfo': !exists(json, 'itemInfo') ? undefined : ItemIdFromJSON(json['itemInfo']), + 'details': !exists(json, 'details') ? undefined : json['details'], + 'exception': !exists(json, 'exception') ? undefined : json['exception'], + }; +} + +export function ModelErrorToJSON(value?: ModelError | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'type': value.type, + 'itemInfo': ItemIdToJSON(value.itemInfo), + 'details': value.details, + 'exception': value.exception, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelErrorRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelErrorRecord.ts new file mode 100644 index 00000000000..29f964f5f14 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelErrorRecord.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + ModelError, +} from './ModelError'; + +import { + ItemId, +} from './ItemId'; + +import { + ItemIdRecord, + itemIdRecordUtils +} from './ItemIdRecord'; + +export const ModelErrorRecordProps = { + recType: "ModelErrorApiRecord" as "ModelErrorApiRecord", + type: 'GenericException', + itemInfo: (ItemIdRecord(), null as ItemIdRecord | null), + details: null as string | null, + exception: null as string | null, +}; + +export type ModelErrorRecordPropsType = typeof ModelErrorRecordProps; +export const ModelErrorRecord = Record(ModelErrorRecordProps, ModelErrorRecordProps.recType); +export type ModelErrorRecord = RecordOf; + +knownRecordFactories.set(ModelErrorRecordProps.recType, ModelErrorRecord); + + +class ModelErrorRecordUtils extends ApiRecordUtils { + public normalize(apiObject: ModelError, asEntity?: boolean): ModelError { + (apiObject as any).recType = ModelErrorRecordProps.recType; + if (apiObject.itemInfo) { itemIdRecordUtils.normalize(apiObject.itemInfo); } + return apiObject; + } + + public toApi(record: ModelErrorRecord): ModelError { + const apiObject = super.toApi(record); + if (record.itemInfo) { apiObject.itemInfo = itemIdRecordUtils.toApi(record.itemInfo); } + return apiObject; + } +} + +export const modelErrorRecordUtils = new ModelErrorRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Order.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Order.ts new file mode 100644 index 00000000000..79b7455a617 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Order.ts @@ -0,0 +1,107 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * An order for a pets from the pet store + * @export + * @interface Order + */ +export interface Order { + /** + * + * @type {number} + * @memberof Order + */ + id?: number; + /** + * + * @type {number} + * @memberof Order + */ + petId?: number; + /** + * + * @type {number} + * @memberof Order + */ + quantity?: number; + /** + * + * @type {Date} + * @memberof Order + */ + shipDate?: Date; + /** + * Order Status + * @type {string} + * @memberof Order + */ + status?: OrderStatusEnum; + /** + * + * @type {boolean} + * @memberof Order + */ + complete?: boolean; +} + +/** +* @export +* @enum {string} +*/ +export enum OrderStatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' +} + +export function OrderFromJSON(json: any): Order { + return OrderFromJSONTyped(json, false); +} + +export function OrderFromJSONTyped(json: any, ignoreDiscriminator: boolean): Order { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'petId': !exists(json, 'petId') ? undefined : json['petId'], + 'quantity': !exists(json, 'quantity') ? undefined : json['quantity'], + 'shipDate': !exists(json, 'shipDate') ? undefined : (new Date(json['shipDate'])), + 'status': !exists(json, 'status') ? undefined : json['status'], + 'complete': !exists(json, 'complete') ? undefined : json['complete'], + }; +} + +export function OrderToJSON(value?: Order | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'petId': value.petId, + 'quantity': value.quantity, + 'shipDate': value.shipDate === undefined ? undefined : (value.shipDate.toISOString()), + 'status': value.status, + 'complete': value.complete, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/OrderRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/OrderRecord.ts new file mode 100644 index 00000000000..621b298df80 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/OrderRecord.ts @@ -0,0 +1,109 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + Order, + OrderStatusEnum, +} from './Order'; + + + +export const OrderRecordProps = { + recType: "OrderApiRecord" as "OrderApiRecord", + id: null as string | null, + petId: null as number | null, + quantity: null as number | null, + shipDate: null as Date | null, + status: null as OrderStatusEnum | null, + complete: null as boolean | null, +}; + +export type OrderRecordPropsType = typeof OrderRecordProps; +export const OrderRecord = Record(OrderRecordProps, OrderRecordProps.recType); +export type OrderRecord = RecordOf; + +knownRecordFactories.set(OrderRecordProps.recType, OrderRecord); + +export const OrderRecordEntityProps = { + ...OrderRecordProps, + recType: "OrderApiRecordEntity" as "OrderApiRecordEntity", +}; + +export type OrderRecordEntityPropsType = typeof OrderRecordEntityProps; +export const OrderRecordEntity = Record(OrderRecordEntityProps, OrderRecordEntityProps.recType); +export type OrderRecordEntity = RecordOf; + +knownRecordFactories.set(OrderRecordEntityProps.recType, OrderRecordEntity); + +class OrderRecordUtils extends ApiRecordUtils { + public normalize(apiObject: Order, asEntity?: boolean): Order { + (apiObject as any).recType = asEntity ? OrderRecordEntityProps.recType : OrderRecordProps.recType; + if (apiObject.id) { (apiObject as any).id = apiObject.id.toString(); } + return apiObject; + } + + public getSchema(): Schema { + return new schema.Entity("order", { + }); + } + + public *toInlined(entityId?: string | null) { + if (!entityId) {return undefined; } + const entity = yield select(apiEntityOrderSelector, {id: entityId}); + if (!entity) {return undefined; } + + const { + recType, + ...unchangedProperties + } = entity; + + const entityProperties = { + } + + return OrderRecord({ + ...unchangedProperties, + ...entityProperties + }); + } + + public *toInlinedArray(entityIds: List | null) { + if (!entityIds) {return null; } + let entities = List(); + for (let entityIndex = 0; entityIndex < entityIds.count(); entityIndex++) { + const entity = yield call(this.toInlined, entityIds.get(entityIndex)); + if (entity) { + entities.push(entity); + } + } + return entities; + } + + public toApi(record: OrderRecord): Order { + const apiObject = super.toApi(record); + if (record.id) { apiObject.id = parseFloat(record.id); } + return apiObject; + } +} + +export const orderRecordUtils = new OrderRecordUtils(); + +export const apiEntitiesOrderSelector = (state: any) => getApiEntitiesState(state).order as Map; +export const apiEntityOrderSelector = (state: any, {id}: {id?: string | null}) => id ? apiEntitiesOrderSelector(state).get(id) : undefined; + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Part.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Part.ts new file mode 100644 index 00000000000..e5a66755d75 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Part.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * Contains all the info about a pet part + * @export + * @interface Part + */ +export interface Part { + /** + * Unique identifier from the database + * @type {number} + * @memberof Part + */ + id: number; + /** + * Name of the part + * @type {string} + * @memberof Part + */ + name: string; +} + +export function PartFromJSON(json: any): Part { + return PartFromJSONTyped(json, false); +} + +export function PartFromJSONTyped(json: any, ignoreDiscriminator: boolean): Part { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + }; +} + +export function PartToJSON(value?: Part | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'name': value.name, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PartRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PartRecord.ts new file mode 100644 index 00000000000..0bbd36a831a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PartRecord.ts @@ -0,0 +1,56 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + Part, +} from './Part'; + + + +export const PartRecordProps = { + recType: "PartApiRecord" as "PartApiRecord", + id: "-1", + name: "", +}; + +export type PartRecordPropsType = typeof PartRecordProps; +export const PartRecord = Record(PartRecordProps, PartRecordProps.recType); +export type PartRecord = RecordOf; + +knownRecordFactories.set(PartRecordProps.recType, PartRecord); + + +class PartRecordUtils extends ApiRecordUtils { + public normalize(apiObject: Part, asEntity?: boolean): Part { + (apiObject as any).recType = PartRecordProps.recType; + (apiObject as any).id = apiObject.id.toString(); + return apiObject; + } + + public toApi(record: PartRecord): Part { + const apiObject = super.toApi(record); + apiObject.id = parseFloat(record.id); + return apiObject; + } +} + +export const partRecordUtils = new PartRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Pet.ts new file mode 100644 index 00000000000..4a79974b1ef --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Pet.ts @@ -0,0 +1,238 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import { + Category, + CategoryFromJSON, + CategoryFromJSONTyped, + CategoryToJSON, + DeploymentRequestStatus, + DeploymentRequestStatusFromJSON, + DeploymentRequestStatusFromJSONTyped, + DeploymentRequestStatusToJSON, + Tag, + TagFromJSON, + TagFromJSONTyped, + TagToJSON, + WarningCode, + WarningCodeFromJSON, + WarningCodeFromJSONTyped, + WarningCodeToJSON, +} from './'; + +/** + * A pet for sale in the pet store + * @export + * @interface Pet + */ +export interface Pet { + /** + * + * @type {number} + * @memberof Pet + */ + id: number; + /** + * + * @type {number} + * @memberof Pet + */ + friendId?: number; + /** + * + * @type {Array} + * @memberof Pet + */ + otherFriendIds: Array; + /** + * + * @type {number} + * @memberof Pet + */ + friendAge: number; + /** + * + * @type {number} + * @memberof Pet + */ + age: number; + /** + * + * @type {boolean} + * @memberof Pet + */ + isHappy: boolean; + /** + * + * @type {boolean} + * @memberof Pet + */ + isTall: boolean; + /** + * + * @type {Category} + * @memberof Pet + */ + category: Category; + /** + * + * @type {Category} + * @memberof Pet + */ + optionalCategory?: Category; + /** + * + * @type {string} + * @memberof Pet + */ + name: string; + /** + * + * @type {Array} + * @memberof Pet + */ + _entries?: Array; + /** + * + * @type {string} + * @memberof Pet + */ + surname?: string; + /** + * + * @type {Array} + * @memberof Pet + */ + photoUrls: Array; + /** + * + * @type {WarningCode} + * @memberof Pet + */ + warningStatus: WarningCode; + /** + * + * @type {DeploymentRequestStatus} + * @memberof Pet + */ + depStatus?: DeploymentRequestStatus; + /** + * + * @type {DeploymentRequestStatus} + * @memberof Pet + */ + alternateStatus: DeploymentRequestStatus; + /** + * + * @type {Array} + * @memberof Pet + */ + otherDepStatuses: Array; + /** + * + * @type {Array} + * @memberof Pet + */ + tags: Array; + /** + * + * @type {Array} + * @memberof Pet + */ + optionalTags?: Array; + /** + * pet status in the store + * @type {string} + * @memberof Pet + */ + status: PetStatusEnum; +} + +/** +* @export +* @enum {string} +*/ +export enum PetStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} + +export function PetFromJSON(json: any): Pet { + return PetFromJSONTyped(json, false); +} + +export function PetFromJSONTyped(json: any, ignoreDiscriminator: boolean): Pet { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': json['id'], + 'friendId': !exists(json, 'friendId') ? undefined : json['friendId'], + 'otherFriendIds': json['otherFriendIds'], + 'friendAge': json['friendAge'], + 'age': json['age'], + 'isHappy': json['isHappy'], + 'isTall': json['isTall'], + 'category': CategoryFromJSON(json['category']), + 'optionalCategory': !exists(json, 'optionalCategory') ? undefined : CategoryFromJSON(json['optionalCategory']), + 'name': json['name'], + '_entries': !exists(json, 'entries') ? undefined : ((json['entries'] as Array).map(CategoryFromJSON)), + 'surname': !exists(json, 'surname') ? undefined : json['surname'], + 'photoUrls': json['photoUrls'], + 'warningStatus': WarningCodeFromJSON(json['warningStatus']), + 'depStatus': !exists(json, 'depStatus') ? undefined : DeploymentRequestStatusFromJSON(json['depStatus']), + 'alternateStatus': DeploymentRequestStatusFromJSON(json['alternateStatus']), + 'otherDepStatuses': ((json['otherDepStatuses'] as Array).map(DeploymentRequestStatusFromJSON)), + 'tags': ((json['tags'] as Array).map(TagFromJSON)), + 'optionalTags': !exists(json, 'optionalTags') ? undefined : ((json['optionalTags'] as Array).map(TagFromJSON)), + 'status': json['status'], + }; +} + +export function PetToJSON(value?: Pet | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'friendId': value.friendId, + 'otherFriendIds': value.otherFriendIds, + 'friendAge': value.friendAge, + 'age': value.age, + 'isHappy': value.isHappy, + 'isTall': value.isTall, + 'category': CategoryToJSON(value.category), + 'optionalCategory': CategoryToJSON(value.optionalCategory), + 'name': value.name, + 'entries': value._entries === undefined ? undefined : ((value._entries as Array).map(CategoryToJSON)), + 'surname': value.surname, + 'photoUrls': value.photoUrls, + 'warningStatus': WarningCodeToJSON(value.warningStatus), + 'depStatus': DeploymentRequestStatusToJSON(value.depStatus), + 'alternateStatus': DeploymentRequestStatusToJSON(value.alternateStatus), + 'otherDepStatuses': ((value.otherDepStatuses as Array).map(DeploymentRequestStatusToJSON)), + 'tags': ((value.tags as Array).map(TagToJSON)), + 'optionalTags': value.optionalTags === undefined ? undefined : ((value.optionalTags as Array).map(TagToJSON)), + 'status': value.status, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartType.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartType.ts new file mode 100644 index 00000000000..4b7c05fbd4b --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartType.ts @@ -0,0 +1,37 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Type of pet part + * @export + * @enum {string} + */ +export enum PetPartType { + Curved = 'Curved', + Smooth = 'Smooth', + Long = 'Long' +} + +export function PetPartTypeFromJSON(json: any): PetPartType { + return PetPartTypeFromJSONTyped(json, false); +} + +export function PetPartTypeFromJSONTyped(json: any, ignoreDiscriminator: boolean): PetPartType { + return json as PetPartType; +} + +export function PetPartTypeToJSON(value?: PetPartType | null): any { + return value as any; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartTypeRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartTypeRecord.ts new file mode 100644 index 00000000000..65fbcfab763 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartTypeRecord.ts @@ -0,0 +1 @@ +// This file is not needed and was generated only because of how codegen is built... Enums do not need to be converted to Records and can be used directly. diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRecord.ts new file mode 100644 index 00000000000..8292c5ee074 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRecord.ts @@ -0,0 +1,177 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + Pet, + PetStatusEnum, +} from './Pet'; + +import { + Category, +} from './Category'; +import { + DeploymentRequestStatus, +} from './DeploymentRequestStatus'; +import { + Tag, +} from './Tag'; +import { + WarningCode, +} from './WarningCode'; + +import { + CategoryRecord, + categoryRecordUtils +} from './CategoryRecord'; +import { + TagRecord, + tagRecordUtils +} from './TagRecord'; + +export const PetRecordProps = { + recType: "PetApiRecord" as "PetApiRecord", + id: "-1", + friendId: null as string | null, + otherFriendIds: List(), + friendAge: 0, + age: 2, + isHappy: true, + isTall: false, + category: CategoryRecord(), + optionalCategory: (CategoryRecord(), null as CategoryRecord | null), + name: "", + _entries: (CategoryRecord(), null as List | null), + surname: null as string | null, + photoUrls: List(), + warningStatus: WarningCode.ReduceVolumeRangeToAvoidLargeSteps, + depStatus: null as DeploymentRequestStatus | null, + alternateStatus: DeploymentRequestStatus.New, + otherDepStatuses: List(), + tags: (TagRecord(), List()), + optionalTags: (TagRecord(), null as List | null), + status: PetStatusEnum.Pending, +}; + +export type PetRecordPropsType = typeof PetRecordProps; +export const PetRecord = Record(PetRecordProps, PetRecordProps.recType); +export type PetRecord = RecordOf; + +knownRecordFactories.set(PetRecordProps.recType, PetRecord); + +export const PetRecordEntityProps = { + ...PetRecordProps, + recType: "PetApiRecordEntity" as "PetApiRecordEntity", + category: "-1", + optionalCategory: null as string | null, + _entries: null as List | null, + tags: List(), + optionalTags: null as List | null, +}; + +export type PetRecordEntityPropsType = typeof PetRecordEntityProps; +export const PetRecordEntity = Record(PetRecordEntityProps, PetRecordEntityProps.recType); +export type PetRecordEntity = RecordOf; + +knownRecordFactories.set(PetRecordEntityProps.recType, PetRecordEntity); + +class PetRecordUtils extends ApiRecordUtils { + public normalize(apiObject: Pet, asEntity?: boolean): Pet { + (apiObject as any).recType = asEntity ? PetRecordEntityProps.recType : PetRecordProps.recType; + (apiObject as any).id = apiObject.id.toString(); + if (apiObject.friendId) { (apiObject as any).friendId = apiObject.friendId.toString(); } + (apiObject as any).otherFriendIds = apiObject.otherFriendIds.map(item => item.toString()); + categoryRecordUtils.normalize(apiObject.category); + if (apiObject.optionalCategory) { categoryRecordUtils.normalize(apiObject.optionalCategory); } + if (apiObject._entries) { categoryRecordUtils.normalizeArray(apiObject._entries); } + tagRecordUtils.normalizeArray(apiObject.tags); + if (apiObject.optionalTags) { tagRecordUtils.normalizeArray(apiObject.optionalTags); } + return apiObject; + } + + public getSchema(): Schema { + return new schema.Entity("pet", { + category: categoryRecordUtils.getSchema(), + optionalCategory: categoryRecordUtils.getSchema(), + _entries: [categoryRecordUtils.getSchema()], + tags: [tagRecordUtils.getSchema()], + optionalTags: [tagRecordUtils.getSchema()], + }); + } + + public *toInlined(entityId?: string | null) { + if (!entityId) {return undefined; } + const entity = yield select(apiEntityPetSelector, {id: entityId}); + if (!entity) {return undefined; } + + const { + recType, + category: category_original, + optionalCategory: optionalCategory_original, + _entries: _entries_original, + tags: tags_original, + optionalTags: optionalTags_original, + ...unchangedProperties + } = entity; + + const entityProperties = { + category: yield call(categoryRecordUtils.toInlined, entity.category), + optionalCategory: entity.optionalCategory ? yield call(categoryRecordUtils.toInlined, entity.optionalCategory) : null, + _entries: entity._entries ? yield call(categoryRecordUtils.toInlinedArray, entity._entries) : null, + tags: yield call(tagRecordUtils.toInlinedArray, entity.tags), + optionalTags: entity.optionalTags ? yield call(tagRecordUtils.toInlinedArray, entity.optionalTags) : null, + } + + return PetRecord({ + ...unchangedProperties, + ...entityProperties + }); + } + + public *toInlinedArray(entityIds: List | null) { + if (!entityIds) {return null; } + let entities = List(); + for (let entityIndex = 0; entityIndex < entityIds.count(); entityIndex++) { + const entity = yield call(this.toInlined, entityIds.get(entityIndex)); + if (entity) { + entities.push(entity); + } + } + return entities; + } + + public toApi(record: PetRecord): Pet { + const apiObject = super.toApi(record); + apiObject.id = parseFloat(record.id); + if (record.friendId) { apiObject.friendId = parseFloat(record.friendId); } + apiObject.otherFriendIds = record.otherFriendIds.map(item => parseFloat(item)).toArray(); + apiObject.category = categoryRecordUtils.toApi(record.category); + if (record.optionalCategory) { apiObject.optionalCategory = categoryRecordUtils.toApi(record.optionalCategory); } + if (record._entries) { apiObject._entries = categoryRecordUtils.toApiArray(record._entries); } + apiObject.tags = tagRecordUtils.toApiArray(record.tags); + if (record.optionalTags) { apiObject.optionalTags = tagRecordUtils.toApiArray(record.optionalTags); } + return apiObject; + } +} + +export const petRecordUtils = new PetRecordUtils(); + +export const apiEntitiesPetSelector = (state: any) => getApiEntitiesState(state).pet as Map; +export const apiEntityPetSelector = (state: any, {id}: {id?: string | null}) => id ? apiEntitiesPetSelector(state).get(id) : undefined; + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMeta.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMeta.ts new file mode 100644 index 00000000000..5b63ca5e8c5 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMeta.ts @@ -0,0 +1,134 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import { + ErrorCode, + ErrorCodeFromJSON, + ErrorCodeFromJSONTyped, + ErrorCodeToJSON, +} from './'; + +/** + * Mandatory part of each response given by our API + * @export + * @interface ResponseMeta + */ +export interface ResponseMeta { + /** + * Code returned by the function + * @type {string} + * @memberof ResponseMeta + */ + code: ResponseMetaCodeEnum; + /** + * Explanation of what went wrong + * @type {string} + * @memberof ResponseMeta + */ + detail?: string; + /** + * Message of the exception that will help developer to debug this problem if needed + * @type {string} + * @memberof ResponseMeta + */ + exception?: string; + /** + * Type of error + * @type {string} + * @memberof ResponseMeta + */ + type?: string; + /** + * + * @type {ErrorCode} + * @memberof ResponseMeta + */ + errorCode?: ErrorCode; + /** + * An array of all the specific error encountered during the request + * @type {Array} + * @memberof ResponseMeta + */ + errors?: Array; +} + +/** +* @export +* @enum {string} +*/ +export enum ResponseMetaCodeEnum { + Ok = 'Ok', + GenericException = 'Generic_Exception', + FieldErrorException = 'Field_Error_Exception', + ImageValidationException = 'Image_Validation_Exception', + InvalidContainerCreationWithNoDefaultAssetException = 'Invalid_Container_Creation_With_No_Default_Asset_Exception', + InvalidOverrideModeException = 'Invalid_Override_Mode_Exception', + InvalidTagException = 'Invalid_Tag_Exception', + ItemUseException = 'Item_Use_Exception', + MissingPlatformForSoftwareException = 'Missing_Platform_For_Software_Exception', + MissingSoftwareForPlatformException = 'Missing_Software_For_Platform_Exception', + PlatformNotSupportedException = 'Platform_Not_Supported_Exception', + RefreshDataException = 'Refresh_Data_Exception', + RoleAssignmentException = 'Role_Assignment_Exception', + TaskAlreadyRunningException = 'Task_Already_Running_Exception', + LoggedOutException = 'Logged_Out_Exception', + AuthorizationException = 'Authorization_Exception', + UnauthorizedActionForCurrentUserException = 'Unauthorized_Action_For_Current_User_Exception', + UserAlreadyExistsButIsNotAuthenticatedException = 'User_Already_Exists_But_Is_Not_Authenticated_Exception', + UserAlreadyHasActiveOrClosedGalaxieApiProductException = 'User_Already_Has_Active_Or_Closed_Galaxie_Api_Product_Exception', + UserAlreadyHasMultipleGalaxieApiProductsException = 'User_Already_Has_Multiple_Galaxie_Api_Products_Exception', + RecurlyApiException = 'Recurly_Api_Exception', + RecurlyTransactionErrorException = 'Recurly_Transaction_Error_Exception', + GalaxieApiException = 'Galaxie_Api_Exception' +} + +export function ResponseMetaFromJSON(json: any): ResponseMeta { + return ResponseMetaFromJSONTyped(json, false); +} + +export function ResponseMetaFromJSONTyped(json: any, ignoreDiscriminator: boolean): ResponseMeta { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'code': json['code'], + 'detail': !exists(json, 'detail') ? undefined : json['detail'], + 'exception': !exists(json, 'exception') ? undefined : json['exception'], + 'type': !exists(json, 'type') ? undefined : json['type'], + 'errorCode': !exists(json, 'errorCode') ? undefined : ErrorCodeFromJSON(json['errorCode']), + 'errors': !exists(json, 'errors') ? undefined : json['errors'], + }; +} + +export function ResponseMetaToJSON(value?: ResponseMeta | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'code': value.code, + 'detail': value.detail, + 'exception': value.exception, + 'type': value.type, + 'errorCode': ErrorCodeToJSON(value.errorCode), + 'errors': value.errors, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMetaRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMetaRecord.ts new file mode 100644 index 00000000000..79a092e4988 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMetaRecord.ts @@ -0,0 +1,62 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + ResponseMeta, + ResponseMetaCodeEnum, +} from './ResponseMeta'; + +import { + ErrorCode, +} from './ErrorCode'; + + +export const ResponseMetaRecordProps = { + recType: "ResponseMetaApiRecord" as "ResponseMetaApiRecord", + code: ResponseMetaCodeEnum.Ok, + detail: null as string | null, + exception: null as string | null, + type: null as string | null, + errorCode: null as ErrorCode | null, + errors: null as Array | null, +}; + +export type ResponseMetaRecordPropsType = typeof ResponseMetaRecordProps; +export const ResponseMetaRecord = Record(ResponseMetaRecordProps, ResponseMetaRecordProps.recType); +export type ResponseMetaRecord = RecordOf; + +knownRecordFactories.set(ResponseMetaRecordProps.recType, ResponseMetaRecord); + + +class ResponseMetaRecordUtils extends ApiRecordUtils { + public normalize(apiObject: ResponseMeta, asEntity?: boolean): ResponseMeta { + (apiObject as any).recType = ResponseMetaRecordProps.recType; + return apiObject; + } + + public toApi(record: ResponseMetaRecord): ResponseMeta { + const apiObject = super.toApi(record); + return apiObject; + } +} + +export const responseMetaRecordUtils = new ResponseMetaRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Tag.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Tag.ts new file mode 100644 index 00000000000..8ea5895e79b --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Tag.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * A tag for a pet + * @export + * @interface Tag + */ +export interface Tag { + /** + * + * @type {number} + * @memberof Tag + */ + id?: number; + /** + * + * @type {string} + * @memberof Tag + */ + name?: string; +} + +export function TagFromJSON(json: any): Tag { + return TagFromJSONTyped(json, false); +} + +export function TagFromJSONTyped(json: any, ignoreDiscriminator: boolean): Tag { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'name': !exists(json, 'name') ? undefined : json['name'], + }; +} + +export function TagToJSON(value?: Tag | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'name': value.name, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/TagRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/TagRecord.ts new file mode 100644 index 00000000000..dd3b631ac85 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/TagRecord.ts @@ -0,0 +1,104 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + Tag, +} from './Tag'; + + + +export const TagRecordProps = { + recType: "TagApiRecord" as "TagApiRecord", + id: null as string | null, + name: null as string | null, +}; + +export type TagRecordPropsType = typeof TagRecordProps; +export const TagRecord = Record(TagRecordProps, TagRecordProps.recType); +export type TagRecord = RecordOf; + +knownRecordFactories.set(TagRecordProps.recType, TagRecord); + +export const TagRecordEntityProps = { + ...TagRecordProps, + recType: "TagApiRecordEntity" as "TagApiRecordEntity", +}; + +export type TagRecordEntityPropsType = typeof TagRecordEntityProps; +export const TagRecordEntity = Record(TagRecordEntityProps, TagRecordEntityProps.recType); +export type TagRecordEntity = RecordOf; + +knownRecordFactories.set(TagRecordEntityProps.recType, TagRecordEntity); + +class TagRecordUtils extends ApiRecordUtils { + public normalize(apiObject: Tag, asEntity?: boolean): Tag { + (apiObject as any).recType = asEntity ? TagRecordEntityProps.recType : TagRecordProps.recType; + if (apiObject.id) { (apiObject as any).id = apiObject.id.toString(); } + return apiObject; + } + + public getSchema(): Schema { + return new schema.Entity("tag", { + }); + } + + public *toInlined(entityId?: string | null) { + if (!entityId) {return undefined; } + const entity = yield select(apiEntityTagSelector, {id: entityId}); + if (!entity) {return undefined; } + + const { + recType, + ...unchangedProperties + } = entity; + + const entityProperties = { + } + + return TagRecord({ + ...unchangedProperties, + ...entityProperties + }); + } + + public *toInlinedArray(entityIds: List | null) { + if (!entityIds) {return null; } + let entities = List(); + for (let entityIndex = 0; entityIndex < entityIds.count(); entityIndex++) { + const entity = yield call(this.toInlined, entityIds.get(entityIndex)); + if (entity) { + entities.push(entity); + } + } + return entities; + } + + public toApi(record: TagRecord): Tag { + const apiObject = super.toApi(record); + if (record.id) { apiObject.id = parseFloat(record.id); } + return apiObject; + } +} + +export const tagRecordUtils = new TagRecordUtils(); + +export const apiEntitiesTagSelector = (state: any) => getApiEntitiesState(state).tag as Map; +export const apiEntityTagSelector = (state: any, {id}: {id?: string | null}) => id ? apiEntitiesTagSelector(state).get(id) : undefined; + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/User.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/User.ts new file mode 100644 index 00000000000..6219c91e3e4 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/User.ts @@ -0,0 +1,129 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * A User who is purchasing from the pet store + * @export + * @interface User + */ +export interface User { + /** + * + * @type {number} + * @memberof User + */ + id: number; + /** + * + * @type {string} + * @memberof User + */ + username?: string; + /** + * + * @type {string} + * @memberof User + */ + firstName?: string; + /** + * + * @type {string} + * @memberof User + */ + lastName?: string; + /** + * + * @type {string} + * @memberof User + */ + email?: string; + /** + * + * @type {string} + * @memberof User + */ + password?: string; + /** + * + * @type {string} + * @memberof User + */ + phone?: string; + /** + * User Status + * @type {number} + * @memberof User + */ + userStatus?: number; + /** + * + * @type {User} + * @memberof User + */ + subUser?: User; + /** + * + * @type {User} + * @memberof User + */ + subUser2: User; +} + +export function UserFromJSON(json: any): User { + return UserFromJSONTyped(json, false); +} + +export function UserFromJSONTyped(json: any, ignoreDiscriminator: boolean): User { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': json['id'], + 'username': !exists(json, 'username') ? undefined : json['username'], + 'firstName': !exists(json, 'firstName') ? undefined : json['firstName'], + 'lastName': !exists(json, 'lastName') ? undefined : json['lastName'], + 'email': !exists(json, 'email') ? undefined : json['email'], + 'password': !exists(json, 'password') ? undefined : json['password'], + 'phone': !exists(json, 'phone') ? undefined : json['phone'], + 'userStatus': !exists(json, 'userStatus') ? undefined : json['userStatus'], + 'subUser': !exists(json, 'subUser') ? undefined : UserFromJSON(json['subUser']), + 'subUser2': UserFromJSON(json['subUser2']), + }; +} + +export function UserToJSON(value?: User | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'username': value.username, + 'firstName': value.firstName, + 'lastName': value.lastName, + 'email': value.email, + 'password': value.password, + 'phone': value.phone, + 'userStatus': value.userStatus, + 'subUser': UserToJSON(value.subUser), + 'subUser2': UserToJSON(value.subUser2), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/UserRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/UserRecord.ts new file mode 100644 index 00000000000..292519c32b2 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/UserRecord.ts @@ -0,0 +1,112 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + User, +} from './User'; + + + +export const UserRecordProps = { + recType: "UserApiRecord" as "UserApiRecord", + id: "-1", + username: null as string | null, + firstName: null as string | null, + lastName: null as string | null, + email: null as string | null, + password: null as string | null, + phone: null as string | null, + userStatus: null as number | null, + subUser: null as User | null, + subUser2: {} as any as User, +}; + +export type UserRecordPropsType = typeof UserRecordProps; +export const UserRecord = Record(UserRecordProps, UserRecordProps.recType); +export type UserRecord = RecordOf; + +knownRecordFactories.set(UserRecordProps.recType, UserRecord); + +export const UserRecordEntityProps = { + ...UserRecordProps, + recType: "UserApiRecordEntity" as "UserApiRecordEntity", +}; + +export type UserRecordEntityPropsType = typeof UserRecordEntityProps; +export const UserRecordEntity = Record(UserRecordEntityProps, UserRecordEntityProps.recType); +export type UserRecordEntity = RecordOf; + +knownRecordFactories.set(UserRecordEntityProps.recType, UserRecordEntity); + +class UserRecordUtils extends ApiRecordUtils { + public normalize(apiObject: User, asEntity?: boolean): User { + (apiObject as any).recType = asEntity ? UserRecordEntityProps.recType : UserRecordProps.recType; + (apiObject as any).id = apiObject.id.toString(); + return apiObject; + } + + public getSchema(): Schema { + return new schema.Entity("user", { + }); + } + + public *toInlined(entityId?: string | null) { + if (!entityId) {return undefined; } + const entity = yield select(apiEntityUserSelector, {id: entityId}); + if (!entity) {return undefined; } + + const { + recType, + ...unchangedProperties + } = entity; + + const entityProperties = { + } + + return UserRecord({ + ...unchangedProperties, + ...entityProperties + }); + } + + public *toInlinedArray(entityIds: List | null) { + if (!entityIds) {return null; } + let entities = List(); + for (let entityIndex = 0; entityIndex < entityIds.count(); entityIndex++) { + const entity = yield call(this.toInlined, entityIds.get(entityIndex)); + if (entity) { + entities.push(entity); + } + } + return entities; + } + + public toApi(record: UserRecord): User { + const apiObject = super.toApi(record); + apiObject.id = parseFloat(record.id); + return apiObject; + } +} + +export const userRecordUtils = new UserRecordUtils(); + +export const apiEntitiesUserSelector = (state: any) => getApiEntitiesState(state).user as Map; +export const apiEntityUserSelector = (state: any, {id}: {id?: string | null}) => id ? apiEntitiesUserSelector(state).get(id) : undefined; + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCode.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCode.ts new file mode 100644 index 00000000000..f0b6dfe654a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCode.ts @@ -0,0 +1,37 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Warning code returned when a potential problem is detected + * @export + * @enum {string} + */ +export enum WarningCode { + ReduceVolumeRangeToAvoidLargeSteps = 'Reduce_Volume_Range_To_Avoid_Large_Steps', + RaiseAmplifierVolume = 'Raise_Amplifier_Volume', + NoVolumeRangeSpecified = 'No_Volume_Range_Specified' +} + +export function WarningCodeFromJSON(json: any): WarningCode { + return WarningCodeFromJSONTyped(json, false); +} + +export function WarningCodeFromJSONTyped(json: any, ignoreDiscriminator: boolean): WarningCode { + return json as WarningCode; +} + +export function WarningCodeToJSON(value?: WarningCode | null): any { + return value as any; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCodeRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCodeRecord.ts new file mode 100644 index 00000000000..65fbcfab763 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCodeRecord.ts @@ -0,0 +1 @@ +// This file is not needed and was generated only because of how codegen is built... Enums do not need to be converted to Records and can be used directly. diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/index.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/index.ts new file mode 100644 index 00000000000..6881bb9feda --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/index.ts @@ -0,0 +1,41 @@ +export * from './BehaviorType'; +export * from './Category'; +export * from './CategoryRecord'; +export * from './DefaultMetaOnlyResponse'; +export * from './DefaultMetaOnlyResponseRecord'; +export * from './DeploymentRequestStatus'; +export * from './ErrorCode'; +export * from './FindPetsByStatusResponse'; +export * from './FindPetsByStatusResponseRecord'; +export * from './FindPetsByUserResponse'; +export * from './FindPetsByUserResponseRecord'; +export * from './GetBehaviorPermissionsResponse'; +export * from './GetBehaviorPermissionsResponseRecord'; +export * from './GetBehaviorTypeResponse'; +export * from './GetBehaviorTypeResponseRecord'; +export * from './GetMatchingPartsResponse'; +export * from './GetMatchingPartsResponseRecord'; +export * from './GetPetPartTypeResponse'; +export * from './GetPetPartTypeResponseRecord'; +export * from './ItemId'; +export * from './ItemIdRecord'; +export * from './MatchingParts'; +export * from './MatchingPartsRecord'; +export * from './ModelApiResponse'; +export * from './ModelApiResponseRecord'; +export * from './ModelError'; +export * from './ModelErrorRecord'; +export * from './Order'; +export * from './OrderRecord'; +export * from './Part'; +export * from './PartRecord'; +export * from './Pet'; +export * from './PetRecord'; +export * from './PetPartType'; +export * from './ResponseMeta'; +export * from './ResponseMetaRecord'; +export * from './Tag'; +export * from './TagRecord'; +export * from './User'; +export * from './UserRecord'; +export * from './WarningCode'; diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts new file mode 100644 index 00000000000..da5d9059bad --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts @@ -0,0 +1,319 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); + +const isBlob = (value: any) => typeof Blob !== 'undefined' && value instanceof Blob; + +/** + * This is the base class for all generated API classes. + */ +export class BaseAPI { + + private middleware: Middleware[]; + + constructor(protected configuration = new Configuration()) { + this.middleware = configuration.middleware; + } + + withMiddleware(this: T, ...middlewares: Middleware[]) { + const next = this.clone(); + next.middleware = next.middleware.concat(...middlewares); + return next; + } + + withPreMiddleware(this: T, ...preMiddlewares: Array) { + const middlewares = preMiddlewares.map((pre) => ({ pre })); + return this.withMiddleware(...middlewares); + } + + withPostMiddleware(this: T, ...postMiddlewares: Array) { + const middlewares = postMiddlewares.map((post) => ({ post })); + return this.withMiddleware(...middlewares); + } + + protected async request(context: RequestOpts): Promise { + const { url, init } = this.createFetchParams(context); + const response = await this.fetchApi(url, init); + if (response.status >= 200 && response.status < 300) { + return response; + } + throw response; + } + + private createFetchParams(context: RequestOpts) { + let url = this.configuration.basePath + context.path; + if (context.query !== undefined && Object.keys(context.query).length !== 0) { + // only add the querystring to the URL if there are query parameters. + // this is done to avoid urls ending with a "?" character which buggy webservers + // do not handle correctly sometimes. + url += '?' + this.configuration.queryParamsStringify(context.query); + } + const body = ((typeof FormData !== "undefined" && context.body instanceof FormData) || context.body instanceof URLSearchParams || isBlob(context.body)) + ? context.body + : JSON.stringify(context.body); + + const headers = Object.assign({}, this.configuration.headers, context.headers); + const init = { + method: context.method, + headers: headers, + body, + credentials: this.configuration.credentials + }; + return { url, init }; + } + + private fetchApi = async (url: string, init: RequestInit) => { + let fetchParams = { url, init }; + for (const middleware of this.middleware) { + if (middleware.pre) { + fetchParams = await middleware.pre({ + fetch: this.fetchApi, + ...fetchParams, + }) || fetchParams; + } + } + let response = await this.configuration.fetchApi(fetchParams.url, fetchParams.init); + for (const middleware of this.middleware) { + if (middleware.post) { + response = await middleware.post({ + fetch: this.fetchApi, + url, + init, + response: response.clone(), + }) || response; + } + } + return response; + } + + /** + * Create a shallow clone of `this` by constructing a new instance + * and then shallow cloning data members. + */ + private clone(this: T): T { + const constructor = this.constructor as any; + const next = new constructor(this.configuration); + next.middleware = this.middleware.slice(); + return next; + } +}; + +export class RequiredError extends Error { + name: "RequiredError" = "RequiredError"; + constructor(public field: string, msg?: string) { + super(msg); + } +} + +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +export type FetchAPI = WindowOrWorkerGlobalScope['fetch']; + +export interface ConfigurationParameters { + basePath?: string; // override base path + fetchApi?: FetchAPI; // override for fetch implementation + middleware?: Middleware[]; // middleware to apply before/after fetch requests + queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings + username?: string; // parameter for basic security + password?: string; // parameter for basic security + apiKey?: string | ((name: string) => string); // parameter for apiKey security + accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + headers?: HTTPHeaders; //header params we want to use on every request + credentials?: RequestCredentials; //value for the credentials param we want to use on each request +} + +export class Configuration { + constructor(private configuration: ConfigurationParameters = {}) {} + + get basePath(): string { + return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; + } + + get fetchApi(): FetchAPI { + return this.configuration.fetchApi || window.fetch.bind(window); + } + + get middleware(): Middleware[] { + return this.configuration.middleware || []; + } + + get queryParamsStringify(): (params: HTTPQuery) => string { + return this.configuration.queryParamsStringify || querystring; + } + + get username(): string | undefined { + return this.configuration.username; + } + + get password(): string | undefined { + return this.configuration.password; + } + + get apiKey(): ((name: string) => string) | undefined { + const apiKey = this.configuration.apiKey; + if (apiKey) { + return typeof apiKey === 'function' ? apiKey : () => apiKey; + } + return undefined; + } + + get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + const accessToken = this.configuration.accessToken; + if (accessToken) { + return typeof accessToken === 'function' ? accessToken : () => accessToken; + } + return undefined; + } + + get headers(): HTTPHeaders | undefined { + return this.configuration.headers; + } + + get credentials(): RequestCredentials | undefined { + return this.configuration.credentials; + } +} + +export type Json = any; +export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; +export type HTTPHeaders = { [key: string]: string }; +export type HTTPQuery = { [key: string]: string | number | null | boolean | Array | HTTPQuery }; +export type HTTPBody = Json | FormData | URLSearchParams; +export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original'; + +export interface FetchParams { + url: string; + init: RequestInit; +} + +export interface RequestOpts { + path: string; + method: HTTPMethod; + headers: HTTPHeaders; + query?: HTTPQuery; + body?: HTTPBody; +} + +export function exists(json: any, key: string) { + const value = json[key]; + return value !== null && value !== undefined; +} + +export function querystring(params: HTTPQuery, prefix: string = ''): string { + return Object.keys(params) + .map((key) => { + const fullKey = prefix + (prefix.length ? `[${key}]` : key); + const value = params[key]; + if (value instanceof Array) { + const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue))) + .join(`&${encodeURIComponent(fullKey)}=`); + return `${encodeURIComponent(fullKey)}=${multiValue}`; + } + if (value instanceof Date) { + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`; + } + if (value instanceof Object) { + return querystring(value as HTTPQuery, fullKey); + } + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; + }) + .filter(part => part.length > 0) + .join('&'); +} + +export function mapValues(data: any, fn: (item: any) => any) { + return Object.keys(data).reduce( + (acc, key) => ({ ...acc, [key]: fn(data[key]) }), + {} + ); +} + +export function canConsumeForm(consumes: Consume[]): boolean { + for (const consume of consumes) { + if ('multipart/form-data' === consume.contentType) { + return true; + } + } + return false; +} + +export interface Consume { + contentType: string +} + +export interface RequestContext { + fetch: FetchAPI; + url: string; + init: RequestInit; +} + +export interface ResponseContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + response: Response; +} + +export interface Middleware { + pre?(context: RequestContext): Promise; + post?(context: ResponseContext): Promise; +} + +export interface ApiResponse { + raw: Response; + value(): Promise; +} + +export interface ResponseTransformer { + (json: any): T; +} + +export class JSONApiResponse { + constructor(public raw: Response, private transformer: ResponseTransformer = (jsonValue: any) => jsonValue) {} + + async value(): Promise { + return this.transformer(await this.raw.json()); + } +} + +export class VoidApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return undefined; + } +} + +export class BlobApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.blob(); + }; +} + +export class TextApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.text(); + }; +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtimeSagasAndRecords.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtimeSagasAndRecords.ts new file mode 100644 index 00000000000..e182521fac3 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtimeSagasAndRecords.ts @@ -0,0 +1,120 @@ +/* tslint:disable */ +/* eslint-disable */ + +import {fromJS as originalFromJS, isIndexed, List, Map as ImmMap, RecordOf} from 'immutable'; +import {normalize, NormalizedSchema, schema, Schema} from "normalizr"; +import {ActionDefinition, createAction} from "redux-ts-simple"; + +export const knownRecordFactories = new Map(); +export const knownIndexedSetByKey: (string | number)[] = []; + +export function appFromJS(any: any): any { + return originalFromJS(any, (key, value) => { + if (isIndexed(value)) { + return knownIndexedSetByKey.indexOf(key) !== -1 ? value.toSet() : value.toList(); + } // we're reviving an array -> it's a List + const MatchingType = knownRecordFactories.get(value.get('recType')) as { new(input?: any): any }; // check if we know a Record with this type + if (MatchingType) { + return new MatchingType(value); + } + return value.toMap(); // no matching Record type found -> it's a plain old Map + }); +} + +export type NormalizedRecordEntity = NormalizedSchema<{ [key: string]: Map> }, string>; +export type NormalizedRecordEntities = NormalizedSchema<{ [key: string]: Map> }, List>; + +export abstract class ApiRecordUtils> { + public abstract normalize(apiObject: TAPI, asEntity?: boolean): any; + + public getSchema(): Schema { + console.log("Entity mode not supported on this record."); + return new schema.Entity("entityNotSupported"); + } + + public normalizeArray(apiObjectArray: TAPI[], asEntity?: boolean): TAPI[] { + apiObjectArray.forEach(apiObject => this.normalize(apiObject, asEntity)); + return apiObjectArray; + } + + public normalizeAsEntities(apiObject: TAPI): NormalizedSchema { + const normalized = this.normalize(apiObject, true); + return normalize(normalized, this.getSchema()); + } + + public normalizeArrayAsEntities(apiObject: TAPI[]): NormalizedSchema { + const normalized = this.normalizeArray(apiObject, true); + return normalize(normalized, new schema.Array(this.getSchema())); + } + + public fromApi(apiObject: TAPI): TREC { + return appFromJS(this.normalize(apiObject)); + } + + public fromApiArray(apiObjectArray: TAPI[]): List { + this.normalizeArray(apiObjectArray); + return appFromJS(apiObjectArray); + } + + public fromApiAsEntities(apiObject: TAPI): NormalizedRecordEntity { + return ApiRecordUtils.toNormalizedRecordEntities(this.normalizeAsEntities(apiObject), false); + } + + public fromApiArrayAsEntities(apiObject: TAPI[]): NormalizedRecordEntities { + return ApiRecordUtils.toNormalizedRecordEntities(this.normalizeArrayAsEntities(apiObject), true); + } + + public toApi(record: TREC): TAPI { + const apiObject = record.toJS(); + delete apiObject.recType; + return apiObject; + } + + public toApiArray(records: List): TAPI[] { + return records.map(record => this.toApi(record)).toArray(); + } + + public static toNormalizedRecordEntities(normalizedAsEntities: any, forArray: boolean) { + const entities = normalizedAsEntities.entities; + for (const entityKey of Object.keys(entities)) { + entities[entityKey] = appFromJS(entities[entityKey]); + } + normalizedAsEntities.result = appFromJS(normalizedAsEntities.result || (forArray ? "" : [])); + return normalizedAsEntities; + } +} + +export const allApiActionFailures: SagaActionDefinition[] = []; + +export interface BaseEntitySupportPayloadApiAction { + toInlined?: boolean; + toEntities?: boolean; + markErrorsAsHandled?: boolean; +} + +export interface BasePayloadApiAction { + markErrorsAsHandled?: boolean; +} + +export interface SagaActionDefinition extends ActionDefinition { + toString: () => string; +} + +export function createSagaAction(type: string, options?: { doNotAutoRegisterFailure?: boolean, namespace?: string }): SagaActionDefinition { + const {doNotAutoRegisterFailure, namespace} = options || {} as any; + let actionDefinition = createAction(namespace ? `${namespace}-${type}` : type); + (actionDefinition as any).toString = () => actionDefinition.type; + if (type.endsWith("Failure") && !doNotAutoRegisterFailure) { + allApiActionFailures.push(actionDefinition); + } + return actionDefinition; +} + +export let apiCall: any>(context: Ctx, fn: Fn, ...args: Parameters) => Generator; + +export function setApiCall(apiCallFc: any>(context: Ctx, fn: Fn, ...args: Parameters) => Generator) { + console.log("init apiCall"); + apiCall = apiCallFc; +} + +export const normalizedEntities = createSagaAction("normalizedEntities"); \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/tsconfig.json new file mode 100644 index 00000000000..5047f4d59a3 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "es6", + "strict": true, + "module": "commonjs", + "moduleResolution": "node", + "outDir": "dist", + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "dist", + "node_modules" + ] +} diff --git a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/package.json b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/package.json index 96268c493a5..232f78295b2 100644 --- a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/package.json +++ b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/package.json @@ -10,7 +10,7 @@ "prepare": "npm run build" }, "devDependencies": { - "typescript": "^3.6" + "typescript": "^3.9.5" }, "publishConfig": { "registry": "https://skimdb.npmjs.com/registry" diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Category.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Category.ts new file mode 100644 index 00000000000..faf9aabb9de --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Category.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * A category for a pet + * @export + * @interface Category + */ +export interface Category { + /** + * + * @type {number} + * @memberof Category + */ + id?: number; + /** + * + * @type {string} + * @memberof Category + */ + name?: string; +} + +export function CategoryFromJSON(json: any): Category { + return CategoryFromJSONTyped(json, false); +} + +export function CategoryFromJSONTyped(json: any, ignoreDiscriminator: boolean): Category { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'name': !exists(json, 'name') ? undefined : json['name'], + }; +} + +export function CategoryToJSON(value?: Category | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'name': value.name, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/ModelApiResponse.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/ModelApiResponse.ts new file mode 100644 index 00000000000..63fa57adc03 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/ModelApiResponse.ts @@ -0,0 +1,73 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * Describes the result of uploading an image resource + * @export + * @interface ModelApiResponse + */ +export interface ModelApiResponse { + /** + * + * @type {number} + * @memberof ModelApiResponse + */ + code?: number; + /** + * + * @type {string} + * @memberof ModelApiResponse + */ + type?: string; + /** + * + * @type {string} + * @memberof ModelApiResponse + */ + message?: string; +} + +export function ModelApiResponseFromJSON(json: any): ModelApiResponse { + return ModelApiResponseFromJSONTyped(json, false); +} + +export function ModelApiResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ModelApiResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'code': !exists(json, 'code') ? undefined : json['code'], + 'type': !exists(json, 'type') ? undefined : json['type'], + 'message': !exists(json, 'message') ? undefined : json['message'], + }; +} + +export function ModelApiResponseToJSON(value?: ModelApiResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'code': value.code, + 'type': value.type, + 'message': value.message, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Order.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Order.ts new file mode 100644 index 00000000000..104c3157f61 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Order.ts @@ -0,0 +1,107 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * An order for a pets from the pet store + * @export + * @interface Order + */ +export interface Order { + /** + * + * @type {number} + * @memberof Order + */ + id?: number; + /** + * + * @type {number} + * @memberof Order + */ + petId?: number; + /** + * + * @type {number} + * @memberof Order + */ + quantity?: number; + /** + * + * @type {Date} + * @memberof Order + */ + shipDate?: Date; + /** + * Order Status + * @type {string} + * @memberof Order + */ + status?: OrderStatusEnum; + /** + * + * @type {boolean} + * @memberof Order + */ + complete?: boolean; +} + +export function OrderFromJSON(json: any): Order { + return OrderFromJSONTyped(json, false); +} + +export function OrderFromJSONTyped(json: any, ignoreDiscriminator: boolean): Order { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'petId': !exists(json, 'petId') ? undefined : json['petId'], + 'quantity': !exists(json, 'quantity') ? undefined : json['quantity'], + 'shipDate': !exists(json, 'shipDate') ? undefined : (new Date(json['shipDate'])), + 'status': !exists(json, 'status') ? undefined : json['status'], + 'complete': !exists(json, 'complete') ? undefined : json['complete'], + }; +} + +export function OrderToJSON(value?: Order | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'petId': value.petId, + 'quantity': value.quantity, + 'shipDate': value.shipDate === undefined ? undefined : (value.shipDate.toISOString()), + 'status': value.status, + 'complete': value.complete, + }; +} + +/** +* @export +* @enum {string} +*/ +export enum OrderStatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Pet.ts new file mode 100644 index 00000000000..7e084c084a9 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Pet.ts @@ -0,0 +1,118 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import { + Category, + CategoryFromJSON, + CategoryFromJSONTyped, + CategoryToJSON, + Tag, + TagFromJSON, + TagFromJSONTyped, + TagToJSON, +} from './'; + +/** + * A pet for sale in the pet store + * @export + * @interface Pet + */ +export interface Pet { + /** + * + * @type {number} + * @memberof Pet + */ + id?: number; + /** + * + * @type {Category} + * @memberof Pet + */ + category?: Category; + /** + * + * @type {string} + * @memberof Pet + */ + name: string; + /** + * + * @type {Array} + * @memberof Pet + */ + photoUrls: Array; + /** + * + * @type {Array} + * @memberof Pet + */ + tags?: Array; + /** + * pet status in the store + * @type {string} + * @memberof Pet + */ + status?: PetStatusEnum; +} + +export function PetFromJSON(json: any): Pet { + return PetFromJSONTyped(json, false); +} + +export function PetFromJSONTyped(json: any, ignoreDiscriminator: boolean): Pet { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'category': !exists(json, 'category') ? undefined : CategoryFromJSON(json['category']), + 'name': json['name'], + 'photoUrls': json['photoUrls'], + 'tags': !exists(json, 'tags') ? undefined : ((json['tags'] as Array).map(TagFromJSON)), + 'status': !exists(json, 'status') ? undefined : json['status'], + }; +} + +export function PetToJSON(value?: Pet | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'category': CategoryToJSON(value.category), + 'name': value.name, + 'photoUrls': value.photoUrls, + 'tags': value.tags === undefined ? undefined : ((value.tags as Array).map(TagToJSON)), + 'status': value.status, + }; +} + +/** +* @export +* @enum {string} +*/ +export enum PetStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Tag.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Tag.ts new file mode 100644 index 00000000000..8ea5895e79b --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Tag.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * A tag for a pet + * @export + * @interface Tag + */ +export interface Tag { + /** + * + * @type {number} + * @memberof Tag + */ + id?: number; + /** + * + * @type {string} + * @memberof Tag + */ + name?: string; +} + +export function TagFromJSON(json: any): Tag { + return TagFromJSONTyped(json, false); +} + +export function TagFromJSONTyped(json: any, ignoreDiscriminator: boolean): Tag { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'name': !exists(json, 'name') ? undefined : json['name'], + }; +} + +export function TagToJSON(value?: Tag | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'name': value.name, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/User.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/User.ts new file mode 100644 index 00000000000..841b50d0fa2 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/User.ts @@ -0,0 +1,113 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * A User who is purchasing from the pet store + * @export + * @interface User + */ +export interface User { + /** + * + * @type {number} + * @memberof User + */ + id?: number; + /** + * + * @type {string} + * @memberof User + */ + username?: string; + /** + * + * @type {string} + * @memberof User + */ + firstName?: string; + /** + * + * @type {string} + * @memberof User + */ + lastName?: string; + /** + * + * @type {string} + * @memberof User + */ + email?: string; + /** + * + * @type {string} + * @memberof User + */ + password?: string; + /** + * + * @type {string} + * @memberof User + */ + phone?: string; + /** + * User Status + * @type {number} + * @memberof User + */ + userStatus?: number; +} + +export function UserFromJSON(json: any): User { + return UserFromJSONTyped(json, false); +} + +export function UserFromJSONTyped(json: any, ignoreDiscriminator: boolean): User { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'username': !exists(json, 'username') ? undefined : json['username'], + 'firstName': !exists(json, 'firstName') ? undefined : json['firstName'], + 'lastName': !exists(json, 'lastName') ? undefined : json['lastName'], + 'email': !exists(json, 'email') ? undefined : json['email'], + 'password': !exists(json, 'password') ? undefined : json['password'], + 'phone': !exists(json, 'phone') ? undefined : json['phone'], + 'userStatus': !exists(json, 'userStatus') ? undefined : json['userStatus'], + }; +} + +export function UserToJSON(value?: User | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'username': value.username, + 'firstName': value.firstName, + 'lastName': value.lastName, + 'email': value.email, + 'password': value.password, + 'phone': value.phone, + 'userStatus': value.userStatus, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/index.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/index.ts index 92ab264fa9c..099f52268b7 100644 --- a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/index.ts +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/index.ts @@ -1,4 +1,3 @@ - /** * A category for a pet * @export @@ -18,7 +17,6 @@ export interface Category { */ name?: string; } - /** * Describes the result of uploading an image resource * @export @@ -44,7 +42,6 @@ export interface ModelApiResponse { */ message?: string; } - /** * An order for a pets from the pet store * @export @@ -98,7 +95,6 @@ export enum OrderStatusEnum { Approved = 'approved', Delivered = 'delivered' } - /** * A pet for sale in the pet store * @export @@ -152,7 +148,6 @@ export enum PetStatusEnum { Pending = 'pending', Sold = 'sold' } - /** * A tag for a pet * @export @@ -172,7 +167,6 @@ export interface Tag { */ name?: string; } - /** * A User who is purchasing from the pet store * @export