fixes #13131: support matrix parameters and other parameter styles in typescript-angular (#13132)

* fix TypescriptAngularPetstoreIntegrationTest

(since this has been abandoned for a long time: just copy the generated code the the "expected" directory)

* fix TypescriptAngularArrayAndObjectIntegrationTest

(since this has been abandoned for a long time: just copy the generated code the the "expected" directory)

* fix TypescriptAngularAdditionalPropertiesIntegrationTest

(since this has been abandoned for a long time: just copy the generated code the the "expected" directory)

* fixes #13131: add custom path parameter expansion to typescript-angular

* fixes #13131: add example for typescript-angular: paramExpansionStrategy=custom

* fixes #13131: document usage of paramExpansionStrategy=custom in README.mustache

* fixes #13131: fix unit tests and sample url for http-param-expander package

* fixes #13131: update samples

* fixes #13131: drop new cli parameter, handle encoding in template only

* fixes #13131: add TestNG groups to all Typescript tests

* fixes #13131: old angular/typescript does not understand type imports

* Apply suggestions from code review

Co-authored-by: Esteban Gehring <esteban.gehring@gmail.com>

* fixes #13131: implement backwards-compatible behavior for format: 'date-time'

* fixes #13131: update typescript-angular integrationtests

* fixes #13131: review fixes + lots of documentation

* fixes #13131: update integrationtests

* fixes #13131: update docs/examples

* fixes #13131: update integrationtests

* fixes #13131: unify enums to union-types to make the api feel mora angular-ish

* fixes #13131: update examples

* fixes #13131: update docs/examples after merge of master

Co-authored-by: Christoph Linder <post@christoph-linder.ch>
Co-authored-by: Esteban Gehring <esteban.gehring@gmail.com>
This commit is contained in:
Christoph Linder 2022-08-24 09:35:40 +02:00 committed by GitHub
parent 4f94d449dc
commit b9a6be0cba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
189 changed files with 6797 additions and 3034 deletions

View File

@ -232,7 +232,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer|✗|OAS3
|ParameterStyling||OAS3
|ParameterStyling||OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3

View File

@ -24,6 +24,7 @@ import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.openapitools.codegen.CodegenConstants.ENUM_PROPERTY_NAMING_TYPE;
import org.openapitools.codegen.CodegenConstants.MODEL_PROPERTY_NAMING_TYPE;
import org.openapitools.codegen.CodegenConstants.PARAM_NAMING_TYPE;
@ -39,13 +40,183 @@ import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.openapitools.codegen.languages.AbstractTypeScriptClientCodegen.ParameterExpander.ParamStyle.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
/**
* Help generating code for any kind of URL parameters (path, matrix, query).
* <p>
* Generators may use this class when substituting URL-parameter-placeholders
* with generated code:
* </p>
* <p>
* While parsing placeholders character-by-character, this class helps accumulating these characters and
* building the final placeholder name.
* </p>
* <p>
* With the placeholder name, this class tries to find the parameter in the operation.
* The class then uses this parameter to build code that is usable by the generator.
* </p>
*/
// TODO: this class grew quite large and most code now is specific to TypeScriptAngularClientCodeGen.java.
// => move code-generation to the concrete generator and let the generator pass this as lambda
@SuppressWarnings("StringBufferField")
public static class ParameterExpander {
private static final Pattern JS_QUOTE_PATTERN = Pattern.compile("\"");
private static final String JS_QUOTE_REPLACEMENT = "\\\"";
/**
* How the parameter is formatted/converted/encoded in the actual request.
* <p>
* See e.g. OpenAPI 3.1 spec: <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">Style Values</a>.
* </p>
*/
public enum ParamStyle {
matrix,
label,
form,
simple,
spaceDelimited,
pipeDelimited,
deepObject;
public String asString() {
return name();
}
}
/**
* Where the parameter is located in the request.
* <p>
* See e.g. OpenAPI 3.1 spec: <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations">Parameter Locations</a>
* </p>
*/
public enum Location {
query((operation, param) -> operation.queryParams.contains(param), form),
header((operation, param) -> operation.headerParams.contains(param), simple),
path((operation, param) -> operation.pathParams.contains(param), simple),
cookie((operation, param) -> operation.cookieParams.contains(param), form);
public final ParamStyle defaultStyle;
public final BiPredicate<CodegenOperation, CodegenParameter> isPresentIn;
Location(BiPredicate<CodegenOperation, CodegenParameter> isPresentIn, ParamStyle defaultStyle) {
this.defaultStyle = defaultStyle;
this.isPresentIn = isPresentIn;
}
public String defaultStyle(@Nullable String style) {
if (style != null && !style.trim().isEmpty()) {
return style;
}
return defaultStyle.asString();
}
public static Location fromParam(CodegenOperation op, CodegenParameter param) {
return Arrays.stream(values())
.filter(v -> v.isPresentIn.test(op, param))
.findAny()
.orElseThrow(() -> new IllegalArgumentException(String.format(
Locale.ROOT,
"Cannot find param ' %s' in operation '%s'",
param, op.operationId
)));
}
}
private final StringBuilder parameterName = new StringBuilder();
private final CodegenOperation op;
private final Function<String, String> toParameterName;
public ParameterExpander(CodegenOperation op, Function<String, String> toParameterName) {
this.op = op;
this.toParameterName = toParameterName;
}
private void reset() {
parameterName.setLength(0);
}
public void appendToParameterName(char c) {
parameterName.append(c);
}
public String buildPathEntry() {
CodegenParameter parameter = findPathParameterByName();
String result = "";
if (parameter != null) {
String generatedParameterName = toParameterName.apply(parameterName.toString());
result = buildPathEntry(parameter, generatedParameterName);
}
reset();
return result;
}
private String buildPathEntry(CodegenParameter parameter, String generatedParameterName) {
Location location = Location.fromParam(op, parameter);
String style = location.defaultStyle(parameter.style);
String optsObject = String.format(
Locale.ROOT,
"{name: %s, value: %s, in: %s, style: %s, explode: %s, dataType: %s, dataFormat: %s}",
quotedJSString(parameter.paramName),
generatedParameterName,
quotedJSString(location.name()),
quotedJSString(style),
parameter.isExplode,
quotedJSString(parameter.dataType),
nullableQuotedJSString(parameter.dataFormat)
);
String result = String.format(Locale.ROOT, "${this.configuration.encodeParam(%s)}", optsObject);
return result;
}
private @Nullable CodegenParameter findPathParameterByName() {
for (CodegenParameter param : op.pathParams) {
if (param.baseName.equals(parameterName.toString())) {
return param;
}
}
return null;
}
private static String quotedJSString(String string) {
String escaped = escapeForQuotedJSString(string);
String result = '"' + escaped + '"';
return result;
}
protected static String escapeForQuotedJSString(String string) {
String quoted = JS_QUOTE_PATTERN.matcher(string)
.replaceAll(JS_QUOTE_REPLACEMENT);
return quoted;
}
protected String nullableQuotedJSString(@Nullable String string) {
if (string == null) {
return "undefined";
}
String result = quotedJSString(string);
return result;
}
}
private final Logger LOGGER = LoggerFactory.getLogger(AbstractTypeScriptClientCodegen.class);
private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";

View File

@ -20,6 +20,7 @@ package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.media.Schema;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.openapitools.codegen.meta.features.GlobalFeature;
import org.openapitools.codegen.model.ModelMap;
import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.model.OperationMap;
@ -86,7 +87,10 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
public TypeScriptAngularClientCodegen() {
super();
modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme));
modifyFeatureSet(features -> features
.includeDocumentationFeatures(DocumentationFeature.Readme)
.includeGlobalFeatures(GlobalFeature.ParameterStyling)
);
this.outputFolder = "generated-code/typescript-angular";
@ -160,6 +164,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
supportingFiles.add(new SupportingFile("configuration.mustache", getIndexDirectory(), "configuration.ts"));
supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts"));
supportingFiles.add(new SupportingFile("encoder.mustache", getIndexDirectory(), "encoder.ts"));
supportingFiles.add(new SupportingFile("param.mustache", getIndexDirectory(), "param.ts"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("README.mustache", getIndexDirectory(), "README.md"));
@ -404,6 +409,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
List<CodegenOperation> ops = objs.getOperation();
boolean hasSomeFormParams = false;
boolean hasSomeEncodableParams = false;
for (CodegenOperation op : ops) {
if (op.getHasFormParams()) {
hasSomeFormParams = true;
@ -413,7 +419,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
// Prep a string buffer where we're going to set up our new version of the string.
StringBuilder pathBuffer = new StringBuilder();
StringBuilder parameterName = new StringBuilder();
ParameterExpander paramExpander = new ParameterExpander(op, this::toParamName);
int insideCurly = 0;
// Iterate through existing string, one character at a time.
@ -422,27 +428,18 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
case '{':
// We entered curly braces, so track that.
insideCurly++;
// Add the more complicated component instead of just the brace.
pathBuffer.append("${encodeURIComponent(String(");
break;
case '}':
// We exited curly braces, so track that.
insideCurly--;
// Add the more complicated component instead of just the brace.
CodegenParameter parameter = findPathParameterByName(op, parameterName.toString());
pathBuffer.append(toParamName(parameterName.toString()));
if (parameter != null && parameter.isDateTime) {
pathBuffer.append(".toISOString()");
}
pathBuffer.append("))}");
parameterName.setLength(0);
pathBuffer.append(paramExpander.buildPathEntry());
hasSomeEncodableParams = true;
break;
default:
char nextChar = op.path.charAt(i);
if (insideCurly > 0) {
parameterName.append(nextChar);
paramExpander.appendToParameterName(nextChar);
} else {
pathBuffer.append(nextChar);
}
@ -455,6 +452,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
}
operations.put("hasSomeFormParams", hasSomeFormParams);
operations.put("hasSomeEncodableParams", hasSomeEncodableParams);
// Add additional filename information for model imports in the services
List<Map<String, String>> imports = operations.getImports();
@ -467,22 +465,6 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
return operations;
}
/**
* Finds and returns a path parameter of an operation by its name
*
* @param operation the operation
* @param parameterName the name of the parameter
* @return param
*/
private CodegenParameter findPathParameterByName(CodegenOperation operation, String parameterName) {
for (CodegenParameter param : operation.pathParams) {
if (param.baseName.equals(parameterName)) {
return param;
}
}
return null;
}
@Override
public ModelsMap postProcessModels(ModelsMap objs) {
ModelsMap result = super.postProcessModels(objs);

View File

@ -201,3 +201,26 @@ import { environment } from '../environments/environment';
})
export class AppModule { }
```
### Customizing path parameter encoding
Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple'
and Dates for format 'date-time' are encoded correctly.
Other styles (e.g. "matrix") are not that easy to encode
and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]).
To implement your own parameter encoding (or call another library),
pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object
(see [General Usage](#general-usage) above).
Example value for use in your Configuration-Provider:
```typescript
new Configuration({
encodeParam: (param: Param) => myFancyParamEncoder(param),
})
```
[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations
[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values
[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander

View File

@ -365,7 +365,8 @@ export class {{classname}} {
}
{{/isResponseFile}}
return this.httpClient.{{httpMethod}}{{^isResponseFile}}<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>{{/isResponseFile}}(`${this.configuration.basePath}{{{path}}}`,{{#isBodyAllowed}}
let localVarPath = `{{{path}}}`;
return this.httpClient.{{httpMethod}}{{^isResponseFile}}<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>{{/isResponseFile}}(`${this.configuration.basePath}${localVarPath}`,{{#isBodyAllowed}}
{{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}{{#hasFormParams}}localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams{{/hasFormParams}}{{^hasFormParams}}null{{/hasFormParams}}{{/bodyParam}},{{/isBodyAllowed}}
{
{{#httpContextInOptions}}

View File

@ -1,4 +1,5 @@
import { HttpParameterCodec } from '@angular/common/http';
import { Param } from './param';
export interface {{configurationParametersInterfaceName}} {
/**
@ -13,7 +14,18 @@ export interface {{configurationParametersInterfaceName}} {
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* Override the default method for encoding path parameters in various
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam?: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
@ -35,7 +47,18 @@ export class {{configurationClassName}} {
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* Encoding of various path parameter
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
@ -51,6 +74,12 @@ export class {{configurationClassName}} {
this.basePath = configurationParameters.basePath;
this.withCredentials = configurationParameters.withCredentials;
this.encoder = configurationParameters.encoder;
if (configurationParameters.encodeParam) {
this.encodeParam = configurationParameters.encodeParam;
}
else {
this.encodeParam = param => this.defaultEncodeParam(param);
}
if (configurationParameters.credentials) {
this.credentials = configurationParameters.credentials;
}
@ -157,4 +186,20 @@ export class {{configurationClassName}} {
? value()
: value;
}
private defaultEncodeParam(param: Param): string {
// This implementation exists as fallback for missing configuration
// and for backwards compatibility to older typescript-angular generator versions.
// It only works for the 'simple' parameter style.
// Date-handling only works for the 'date-time' format.
// All other styles and Date-formats are probably handled incorrectly.
//
// But: if that's all you need (i.e.: the most common use-case): no need for customization!
const value = param.dataFormat === 'date-time'
? (param.value as Date).toISOString()
: param.value;
return encodeURIComponent(String(value));
}
}

View File

@ -3,3 +3,4 @@ export * from './model/models';
export * from './variables';
export * from './configuration';
export * from './api.module';
export * from './param';

View File

@ -0,0 +1,69 @@
/**
* Standard parameter styles defined by OpenAPI spec
*/
export type StandardParamStyle =
| 'matrix'
| 'label'
| 'form'
| 'simple'
| 'spaceDelimited'
| 'pipeDelimited'
| 'deepObject'
;
/**
* The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user.
*/
export type ParamStyle = StandardParamStyle | string;
/**
* Standard parameter locations defined by OpenAPI spec
*/
export type ParamLocation = 'query' | 'header' | 'path' | 'cookie';
/**
* Standard types as defined in <a href="https://swagger.io/specification/#data-types">OpenAPI Specification: Data Types</a>
*/
export type StandardDataType =
| "integer"
| "number"
| "boolean"
| "string"
| "object"
| "array"
;
/**
* Standard {@link DataType}s plus your own types/classes.
*/
export type DataType = StandardDataType | string;
/**
* Standard formats as defined in <a href="https://swagger.io/specification/#data-types">OpenAPI Specification: Data Types</a>
*/
export type StandardDataFormat =
| "int32"
| "int64"
| "float"
| "double"
| "byte"
| "binary"
| "date"
| "date-time"
| "password"
;
export type DataFormat = StandardDataFormat | string;
/**
* The parameter to encode.
*/
export interface Param {
name: string;
value: unknown;
in: ParamLocation;
style: ParamStyle,
explode: boolean;
dataType: DataType;
dataFormat: DataFormat | undefined;
}

View File

@ -33,7 +33,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import static org.testng.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.fail;
/**
@ -84,9 +84,10 @@ public class AssertFile {
Arrays.sort(actual);
}
assertEquals(expected,
actual,
String.format(Locale.ROOT, "Directory content of '%s' and '%s' differ.", expectedDir, actualDir));
// Use AssertJ as it also prints a diff
assertThat(actual)
.describedAs(String.format(Locale.ROOT, "Directory content of '%s' and '%s' differ.", expectedDir, actualDir))
.containsExactly(expected);
return FileVisitResult.CONTINUE;
}

View File

@ -16,6 +16,9 @@ import java.util.List;
import java.util.Map;
import java.util.HashMap;
import static org.openapitools.codegen.typescript.TypeScriptGroups.*;
@Test(groups = {TYPESCRIPT})
public class SharedTypeScriptTest {
@Test
public void typesInImportsAreSplittedTest() throws IOException {

View File

@ -20,7 +20,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
@Test(groups = {TypeScriptGroups.TYPESCRIPT})
public class TypeScriptClientCodegenTest {
@Test
public void getTypeDeclarationTest() {

View File

@ -6,11 +6,11 @@ import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.TypeScriptClientCodegen;
import org.openapitools.codegen.utils.ModelUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test(groups = {TypeScriptGroups.TYPESCRIPT})
public class TypeScriptClientModelTest {
@Test(description = "convert an array oneof model")

View File

@ -0,0 +1,28 @@
package org.openapitools.codegen.typescript;
/**
* TestNG supports grouping using <a href="https://testng.org/doc/documentation-main.html#test-groups">Test Groups</a>.
* <br>
* <p>
* Using groups also enables running only a subset of tests, e.g. only for the generator you are currently working on.
* </p>
* <p>
* This speeds up development <strong>a lot</strong>, especially if run from an IDE with support for TestNG groups
* (e.g. IntelliJ IDEA and derivatives, VS Code, and lots of others)
* </p>
* <br>
* <p>Suggested groups/group-names are:</p>
* <ul>
* <li>one per language (e.g.: "typescript") since most generators for one language share lots of code</li>
* <li>one per language + generator (i.e. the generator name, e.g.: "typescript-angular")</li>
* </ul>
*/
public final class TypeScriptGroups {
public static final String TYPESCRIPT = "typescript";
public static final String TYPESCRIPT_AURELIA = "typescript-aurelia";
public static final String TYPESCRIPT_AXIOS = "typescript-axios";
public static final String TYPESCRIPT_FETCH = "typescript-fetch";
public static final String TYPESCRIPT_ANGULAR = "typescript-angular";
public static final String TYPESCRIPT_NESTJS = "typescript-nestjs";
public static final String TYPESCRIPT_NODE = "typescript-node";
}

View File

@ -21,10 +21,13 @@ import org.openapitools.codegen.AbstractOptionsTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptAureliaClientCodegen;
import org.openapitools.codegen.options.TypeScriptAureliaClientOptionsProvider;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_AURELIA})
public class TypeScriptAureliaClientOptionsTest extends AbstractOptionsTest {
private TypeScriptAureliaClientCodegen clientCodegen = mock(TypeScriptAureliaClientCodegen.class, mockSettings);

View File

@ -2,10 +2,12 @@ package org.openapitools.codegen.typescript.axios;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.languages.TypeScriptAxiosClientCodegen;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_AXIOS})
public class TypeScriptAxiosClientCodegenTest {
TypeScriptAxiosClientCodegen codegen = new TypeScriptAxiosClientCodegen();

View File

@ -1,17 +1,22 @@
package org.openapitools.codegen.typescript.fetch;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.openapitools.codegen.utils.ModelUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_FETCH})
public class TypeScriptFetchClientCodegenTest {
@Test
public void testSnapshotVersion() {

View File

@ -21,10 +21,13 @@ import org.openapitools.codegen.AbstractOptionsTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen;
import org.openapitools.codegen.options.TypeScriptFetchClientOptionsProvider;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_FETCH})
public class TypeScriptFetchClientOptionsTest extends AbstractOptionsTest {
private TypeScriptFetchClientCodegen clientCodegen = mock(TypeScriptFetchClientCodegen.class, mockSettings);

View File

@ -26,6 +26,7 @@ import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.Assert;
import org.testng.annotations.Test;
@ -45,6 +46,7 @@ import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanVal
import static io.swagger.codegen.utils.ModelUtils.updateCodegenPropertyEnum;
*/
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_FETCH})
@SuppressWarnings("static-method")
public class TypeScriptFetchModelTest {

View File

@ -11,6 +11,7 @@ import io.swagger.v3.oas.models.responses.ApiResponses;
import org.openapitools.codegen.*;
import org.openapitools.codegen.config.CodegenConfigurator;
import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.Assert;
import org.testng.annotations.Test;
@ -21,6 +22,7 @@ import java.util.HashMap;
import java.util.Map;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR})
public class TypeScriptAngularClientCodegenTest {
@Test
public void toVarName() {

View File

@ -21,10 +21,13 @@ import org.openapitools.codegen.AbstractOptionsTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen;
import org.openapitools.codegen.options.TypeScriptAngularClientOptionsProvider;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR})
public class TypeScriptAngularClientOptionsTest extends AbstractOptionsTest {
private TypeScriptAngularClientCodegen clientCodegen = mock(TypeScriptAngularClientCodegen.class, mockSettings);

View File

@ -27,6 +27,7 @@ import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen;
import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.Assert;
import org.testng.annotations.Test;
@ -38,6 +39,7 @@ import java.time.ZoneOffset;
import java.util.Date;
import java.util.Locale;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR})
@SuppressWarnings("static-method")
public class TypeScriptAngularModelTest {

View File

@ -21,12 +21,23 @@ import org.openapitools.codegen.AbstractIntegrationTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen;
import org.openapitools.codegen.testutils.IntegrationTestPathsConfig;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR})
public class TypescriptAngularAdditionalPropertiesIntegrationTest extends AbstractIntegrationTest {
{
// when running repeatedly from an IDE, some files do not get overwritten
// and thus are missing from the FILES metadata.
// Since metadata-verification is not the core responsibility of this test: disable it.
generateMetadata = false;
}
@Override
protected CodegenConfig getCodegenConfig() {
return new TypeScriptAngularClientCodegen();
@ -46,4 +57,11 @@ public class TypescriptAngularAdditionalPropertiesIntegrationTest extends Abstra
protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() {
return new IntegrationTestPathsConfig("typescript/additional-properties");
}
@Test
@Override
public void generatesCorrectDirectoryStructure() throws IOException {
// test are currently disabled in Superclass
super.generatesCorrectDirectoryStructure();
}
}

View File

@ -3,9 +3,11 @@ package org.openapitools.codegen.typescript.typescriptangular;
import io.swagger.v3.oas.models.OpenAPI;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR})
public class TypescriptAngularApiVersionTest {
@Test(description = "tests if API version specification is used if no version is provided in additional properties")

View File

@ -21,12 +21,23 @@ import org.openapitools.codegen.AbstractIntegrationTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen;
import org.openapitools.codegen.testutils.IntegrationTestPathsConfig;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR})
public class TypescriptAngularArrayAndObjectIntegrationTest extends AbstractIntegrationTest {
{
// when running repeatedly from an IDE, some files do not get overwritten
// and thus are missing from the FILES metadata.
// Since metadata-verification is not the core responsibility of this test: disable it.
generateMetadata = false;
}
@Override
protected CodegenConfig getCodegenConfig() {
return new TypeScriptAngularClientCodegen();
@ -46,4 +57,11 @@ public class TypescriptAngularArrayAndObjectIntegrationTest extends AbstractInte
protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() {
return new IntegrationTestPathsConfig("typescript/array-and-object");
}
@Test
@Override
public void generatesCorrectDirectoryStructure() throws IOException {
// test are currently disabled in Superclass
super.generatesCorrectDirectoryStructure();
}
}

View File

@ -0,0 +1,66 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.typescript.typescriptangular;
import org.openapitools.codegen.AbstractIntegrationTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen;
import org.openapitools.codegen.testutils.IntegrationTestPathsConfig;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR})
public class TypescriptAngularParamsStrategyCustomIntegrationTest extends AbstractIntegrationTest {
{
// when running repeatedly from an IDE, some files do not get overwritten
// and thus are missing from the FILES metadata.
// Since metadata-verification is not the core responsibility of this test: disable it.
generateMetadata = false;
}
@Override
protected CodegenConfig getCodegenConfig() {
return new TypeScriptAngularClientCodegen();
}
@Override
protected Map<String, String> configProperties() {
Map<String, String> properties = new HashMap<>();
properties.put("npmName", "custom-path-params-integration-test");
properties.put("npmVersion", "1.0.3");
properties.put("snapshot", "false");
return properties;
}
@Override
protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() {
return new IntegrationTestPathsConfig("typescript/custom-path-params");
}
@Test
@Override
public void generatesCorrectDirectoryStructure() throws IOException {
// test are currently disabled in Superclass
super.generatesCorrectDirectoryStructure();
}
}

View File

@ -21,12 +21,23 @@ import org.openapitools.codegen.AbstractIntegrationTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen;
import org.openapitools.codegen.testutils.IntegrationTestPathsConfig;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR})
public class TypescriptAngularPetstoreIntegrationTest extends AbstractIntegrationTest {
{
// when running repeatedly from an IDE, some files do not get overwritten
// and thus are missing from the FILES metadata.
// Since metadata-verification is not the core responsibility of this test: disable it.
generateMetadata = false;
}
@Override
protected CodegenConfig getCodegenConfig() {
return new TypeScriptAngularClientCodegen();
@ -46,4 +57,11 @@ public class TypescriptAngularPetstoreIntegrationTest extends AbstractIntegratio
protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() {
return new IntegrationTestPathsConfig("typescript/petstore");
}
@Test
@Override
public void generatesCorrectDirectoryStructure() throws IOException {
// test are currently disabled in Superclass
super.generatesCorrectDirectoryStructure();
}
}

View File

@ -10,10 +10,12 @@ import io.swagger.v3.oas.models.responses.ApiResponses;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS})
public class TypeScriptNestjsClientCodegenTest {
@Test
public void testModelFileSuffix() {

View File

@ -20,10 +20,13 @@ import org.openapitools.codegen.AbstractOptionsTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen;
import org.openapitools.codegen.options.TypeScriptNestjsClientOptionsProvider;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS})
public class TypeScriptNestjsClientOptionsTest extends AbstractOptionsTest {
private TypeScriptNestjsClientCodegen clientCodegen = mock(TypeScriptNestjsClientCodegen.class, mockSettings);

View File

@ -25,9 +25,11 @@ import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS})
@SuppressWarnings("static-method")
public class TypeScriptNestjsModelTest {

View File

@ -20,10 +20,13 @@ import org.openapitools.codegen.AbstractIntegrationTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen;
import org.openapitools.codegen.testutils.IntegrationTestPathsConfig;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS})
public class TypescriptNestjsAdditionalPropertiesIntegrationTest extends AbstractIntegrationTest {
@Override

View File

@ -3,9 +3,11 @@ package org.openapitools.codegen.typescript.typescriptnestjs;
import io.swagger.v3.oas.models.OpenAPI;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS})
public class TypescriptNestjsApiVersionTest {
@Test(description = "tests if API version specification is used if no version is provided in additional properties")

View File

@ -20,10 +20,13 @@ import org.openapitools.codegen.AbstractIntegrationTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen;
import org.openapitools.codegen.testutils.IntegrationTestPathsConfig;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS})
public class TypescriptNestjsArrayAndObjectIntegrationTest extends AbstractIntegrationTest {
@Override

View File

@ -20,10 +20,13 @@ import org.openapitools.codegen.AbstractIntegrationTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen;
import org.openapitools.codegen.testutils.IntegrationTestPathsConfig;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS})
public class TypescriptNestjsPetstoreIntegrationTest extends AbstractIntegrationTest {
@Override

View File

@ -11,12 +11,14 @@ import org.openapitools.codegen.model.ModelMap;
import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.model.OperationMap;
import org.openapitools.codegen.model.OperationsMap;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.*;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NODE})
public class TypeScriptNodeClientCodegenTest {
private TypeScriptNodeClientCodegen codegen;

View File

@ -21,10 +21,13 @@ import org.openapitools.codegen.AbstractOptionsTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen;
import org.openapitools.codegen.options.TypeScriptNodeClientOptionsProvider;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NODE})
public class TypeScriptNodeClientOptionsTest extends AbstractOptionsTest {
private TypeScriptNodeClientCodegen clientCodegen = mock(TypeScriptNodeClientCodegen.class, mockSettings);

View File

@ -18,17 +18,16 @@
package org.openapitools.codegen.typescript.typescriptnode;
import com.google.common.collect.Sets;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen;
import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.Assert;
import org.testng.annotations.Test;
@ -40,6 +39,7 @@ import java.time.ZoneOffset;
import java.util.Date;
import java.util.Locale;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NODE})
@SuppressWarnings("static-method")
public class TypeScriptNodeModelTest {

View File

@ -21,10 +21,13 @@ import org.openapitools.codegen.AbstractIntegrationTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen;
import org.openapitools.codegen.testutils.IntegrationTestPathsConfig;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NODE})
public class TypescriptNodeES5IntegrationTest extends AbstractIntegrationTest {
@Override

View File

@ -20,10 +20,13 @@ import org.openapitools.codegen.AbstractIntegrationTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen;
import org.openapitools.codegen.testutils.IntegrationTestPathsConfig;
import org.openapitools.codegen.typescript.TypeScriptGroups;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NODE})
public class TypescriptNodeEnumIntegrationTest extends AbstractIntegrationTest {
@Override

View File

@ -1,3 +1,4 @@
wwwroot/*.js
node_modules
typings
dist

View File

@ -1,23 +0,0 @@
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# 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 Swagger Codegen 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

View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -2,7 +2,7 @@
### Building
To build and compile the typescript sources to javascript use:
To install the required dependencies and to build the typescript sources run:
```
npm install
npm run build
@ -10,11 +10,11 @@ npm run build
### publishing
First build the package than run ```npm publish```
First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!)
### consuming
navigate to the folder of your consuming project and run one of next commando's.
Navigate to the folder of your consuming project and run one of next commands.
_published:_
@ -22,23 +22,205 @@ _published:_
npm install additionalPropertiesTest@1.0.2 --save
```
_unPublished (not recommended):_
_without publishing (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save
npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save
```
In your angular2 project:
_It's important to take the tgz file, otherwise you'll get trouble with links on windows_
_using `npm link`:_
In PATH_TO_GENERATED_PACKAGE/dist:
```
npm link
```
In your project:
```
npm link additionalPropertiesTest
```
__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages.
Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround.
Published packages are not effected by this issue.
#### General usage
In your Angular project:
```
// without configuring providers
import { ApiModule } from 'additionalPropertiesTest';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
ApiModule,
// make sure to import the HttpClientModule in the AppModule only,
// see https://github.com/angular/angular/issues/20575
HttpClientModule
],
declarations: [ AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
```
// configuring providers
import { ApiModule, Configuration, ConfigurationParameters } from 'additionalPropertiesTest';
export function apiConfigFactory (): Configuration {
const params: ConfigurationParameters = {
// set configuration parameters here.
}
return new Configuration(params);
}
@NgModule({
imports: [ ApiModule.forRoot(apiConfigFactory) ],
declarations: [ AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
```
// configuring providers with an authentication service that manages your access tokens
import { ApiModule, Configuration } from 'additionalPropertiesTest';
@NgModule({
imports: [ ApiModule ],
declarations: [ AppComponent ],
providers: [
{
provide: Configuration,
useFactory: (authService: AuthService) => new Configuration(
{
basePath: environment.apiUrl,
accessToken: authService.getAccessToken.bind(authService)
}
),
deps: [AuthService],
multi: false
}
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
```
import { DefaultApi } from 'additionalPropertiesTest';
export class AppComponent {
constructor(private apiGateway: DefaultApi) { }
}
```
Note: The ApiModule is restricted to being instantiated once app wide.
This is to ensure that all services are treated as singletons.
#### Using multiple OpenAPI files / APIs / ApiModules
In order to use multiple `ApiModules` generated from different OpenAPI files,
you can create an alias name when importing the modules
in order to avoid naming conflicts:
```
import { ApiModule } from 'my-api-path';
import { ApiModule as OtherApiModule } from 'my-other-api-path';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
ApiModule,
OtherApiModule,
// make sure to import the HttpClientModule in the AppModule only,
// see https://github.com/angular/angular/issues/20575
HttpClientModule
]
})
export class AppModule {
}
```
TODO: paste example.
### Set service base path
If different than the generated base path, during app bootstrap, you can provide the base path to your service.
```
import { BASE_PATH } from './path-to-swagger-gen-service/index';
import { BASE_PATH } from 'additionalPropertiesTest';
bootstrap(AppComponent, [
{ provide: BASE_PATH, useValue: 'https://your-web-service.com' },
]);
```
or
```
import { BASE_PATH } from 'additionalPropertiesTest';
@NgModule({
imports: [],
declarations: [ AppComponent ],
providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
#### Using @angular/cli
First extend your `src/environments/*.ts` files by adding the corresponding base path:
```
export const environment = {
production: false,
API_BASE_PATH: 'http://127.0.0.1:8080'
};
```
In the src/app/app.module.ts:
```
import { BASE_PATH } from 'additionalPropertiesTest';
import { environment } from '../environments/environment';
@NgModule({
declarations: [
AppComponent
],
imports: [ ],
providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }],
bootstrap: [ AppComponent ]
})
export class AppModule { }
```
### Customizing path parameter encoding
Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple'
and Dates for format 'date-time' are encoded correctly.
Other styles (e.g. "matrix") are not that easy to encode
and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]).
To implement your own parameter encoding (or call another library),
pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object
(see [General Usage](#general-usage) above).
Example value for use in your Configuration-Provider:
```typescript
new Configuration({
encodeParam: (param: Param) => myFancyParamEncoder(param),
})
```
[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations
[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values
[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander

View File

@ -1,21 +1,31 @@
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core';
import { Configuration } from './configuration';
import { HttpClient } from '@angular/common/http';
import { UserService } from './api/user.service';
@NgModule({
imports: [ CommonModule, HttpModule ],
imports: [],
declarations: [],
exports: [],
providers: [ UserService ]
providers: []
})
export class ApiModule {
public static forConfig(configuration: Configuration): ModuleWithProviders {
public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders<ApiModule> {
return {
ngModule: ApiModule,
providers: [ {provide: Configuration, useValue: configuration}]
providers: [ { provide: Configuration, useFactory: configurationFactory } ]
};
}
constructor( @Optional() @SkipSelf() parentModule: ApiModule,
@Optional() http: HttpClient) {
if (parentModule) {
throw new Error('ApiModule is already loaded. Import in your base AppModule only.');
}
if (!http) {
throw new Error('You need to import the HttpClientModule in your AppModule! \n' +
'See also https://github.com/angular/angular/issues/20575');
}
}
}

View File

@ -1 +1,3 @@
export * from './user.service';
import { UserService } from './user.service';
export const APIS = [UserService];

View File

@ -1,166 +1,222 @@
/**
* Swagger Additional Properties
* OpenAPI Additional Properties
* This is a test spec
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
* The version of the OpenAPI document: 1.0.0
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Inject, Injectable, Optional } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Response, ResponseContentType } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import '../rxjs-operators';
import { User } from '../model/user';
import { BASE_PATH } from '../variables';
import { Configuration } from '../configuration';
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
@Injectable()
// @ts-ignore
import { User } from '../model/user';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
@Injectable({
providedIn: 'root'
})
export class UserService {
protected basePath = 'http://additional-properties.swagger.io/v2';
public defaultHeaders: Headers = new Headers();
public configuration: Configuration = new Configuration();
constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (basePath) {
this.basePath = basePath;
}
protected basePath = 'http://additional-properties.swagger.io/v2';
public defaultHeaders = new HttpHeaders();
public configuration = new Configuration();
public encoder: HttpParameterCodec;
constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) {
if (configuration) {
this.configuration = configuration;
this.basePath = basePath || configuration.basePath || this.basePath;
}
if (typeof this.configuration.basePath !== 'string') {
if (Array.isArray(basePath) && basePath.length > 0) {
basePath = basePath[0];
}
if (typeof basePath !== 'string') {
basePath = this.basePath;
}
this.configuration.basePath = basePath;
}
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
}
// @ts-ignore
private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams {
if (typeof value === "object" && value instanceof Date === false) {
httpParams = this.addToHttpParamsRecursive(httpParams, value);
} else {
httpParams = this.addToHttpParamsRecursive(httpParams, value, key);
}
return httpParams;
}
private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams {
if (value == null) {
return httpParams;
}
if (typeof value === "object") {
if (Array.isArray(value)) {
(value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
} else if (value instanceof Date) {
if (key != null) {
httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10));
} else {
throw Error("key may not be null if value is Date");
}
} else {
Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive(
httpParams, value[k], key != null ? `${key}.${k}` : k));
}
} else if (key != null) {
httpParams = httpParams.append(key, value);
} else {
throw Error("key may not be null if value is not object or array");
}
return httpParams;
}
/**
* Add a new User to the store
*
* @param body User object that needs to be added to the store
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public addUser(body?: User, extraHttpRequestParams?: any): Observable<{}> {
return this.addUserWithHttpInfo(body, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
public addUser(body?: { [key: string]: string; }, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public addUser(body?: { [key: string]: string; }, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public addUser(body?: { [key: string]: string; }, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public addUser(body?: { [key: string]: string; }, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/user`;
return this.httpClient.post<any>(`${this.configuration.basePath}${localVarPath}`,
body,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Update an existing User
*
* @param body User object that needs to be added to the store
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public updateUser(body?: User, extraHttpRequestParams?: any): Observable<{}> {
return this.updateUserWithHttpInfo(body, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
public updateUser(body?: { [key: string]: string; }, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public updateUser(body?: { [key: string]: string; }, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public updateUser(body?: { [key: string]: string; }, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public updateUser(body?: { [key: string]: string; }, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
/**
* Add a new User to the store
*
* @param body User object that needs to be added to the store
*/
public addUserWithHttpInfo(body?: User, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/user`;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
let consumes: string[] = [
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612
search: queryParameters,
responseType: ResponseContentType.Json
});
return this.http.request(path, requestOptions);
}
/**
* Update an existing User
*
* @param body User object that needs to be added to the store
*/
public updateUserWithHttpInfo(body?: User, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/user`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612
search: queryParameters,
responseType: ResponseContentType.Json
});
return this.http.request(path, requestOptions);
let localVarPath = `/user`;
return this.httpClient.put<any>(`${this.configuration.basePath}${localVarPath}`,
body,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
}

View File

@ -1,24 +1,166 @@
import { HttpParameterCodec } from '@angular/common/http';
import { Param } from './param';
export interface ConfigurationParameters {
apiKey?: string;
username?: string;
password?: string;
accessToken?: string;
basePath?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* Override the default method for encoding path parameters in various
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam?: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'.
*/
credentials?: {[ key: string ]: string | (() => string | undefined)};
}
export class Configuration {
apiKey: string;
username: string;
password: string;
accessToken: string;
basePath: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* Encoding of various path parameter
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'.
*/
credentials: {[ key: string ]: string | (() => string | undefined)};
constructor(configurationParameters: ConfigurationParameters = {}) {
this.apiKeys = configurationParameters.apiKeys;
this.username = configurationParameters.username;
this.password = configurationParameters.password;
this.accessToken = configurationParameters.accessToken;
this.basePath = configurationParameters.basePath;
this.withCredentials = configurationParameters.withCredentials;
this.encoder = configurationParameters.encoder;
if (configurationParameters.encodeParam) {
this.encodeParam = configurationParameters.encodeParam;
}
else {
this.encodeParam = param => this.defaultEncodeParam(param);
}
if (configurationParameters.credentials) {
this.credentials = configurationParameters.credentials;
}
else {
this.credentials = {};
}
}
constructor(configurationParameters: ConfigurationParameters = {}) {
this.apiKey = configurationParameters.apiKey;
this.username = configurationParameters.username;
this.password = configurationParameters.password;
this.accessToken = configurationParameters.accessToken;
this.basePath = configurationParameters.basePath;
}
/**
* Select the correct content-type to use for a request.
* Uses {@link Configuration#isJsonMime} to determine the correct content-type.
* If no content type is found return the first found type if the contentTypes is not empty
* @param contentTypes - the array of content types that are available for selection
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderContentType (contentTypes: string[]): string | undefined {
if (contentTypes.length === 0) {
return undefined;
}
const type = contentTypes.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return contentTypes[0];
}
return type;
}
/**
* Select the correct accept content-type to use for a request.
* Uses {@link Configuration#isJsonMime} to determine the correct accept content-type.
* If no content type is found return the first found type if the contentTypes is not empty
* @param accepts - the array of content types that are available for selection.
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderAccept(accepts: string[]): string | undefined {
if (accepts.length === 0) {
return undefined;
}
const type = accepts.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return accepts[0];
}
return type;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
public isJsonMime(mime: string): boolean {
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
}
public lookupCredential(key: string): string | undefined {
const value = this.credentials[key];
return typeof value === 'function'
? value()
: value;
}
private defaultEncodeParam(param: Param): string {
// This implementation exists as fallback for missing configuration
// and for backwards compatibility to older typescript-angular generator versions.
// It only works for the 'simple' parameter style.
// Date-handling only works for the 'date-time' format.
// All other styles and Date-formats are probably handled incorrectly.
//
// But: if that's all you need (i.e.: the most common use-case): no need for customization!
const value = param.dataFormat === 'date-time'
? (param.value as Date).toISOString()
: param.value;
return encodeURIComponent(String(value));
}
}

View File

@ -0,0 +1,20 @@
import { HttpParameterCodec } from '@angular/common/http';
/**
* Custom HttpParameterCodec
* Workaround for https://github.com/angular/angular/issues/18261
*/
export class CustomHttpParameterCodec implements HttpParameterCodec {
encodeKey(k: string): string {
return encodeURIComponent(k);
}
encodeValue(v: string): string {
return encodeURIComponent(v);
}
decodeKey(k: string): string {
return decodeURIComponent(k);
}
decodeValue(v: string): string {
return decodeURIComponent(v);
}
}

View File

@ -1,11 +1,17 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update"
# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host=""
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id=""
@ -37,9 +43,9 @@ if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@github.com/${git_user_id}/${git_repo_id}.git
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git
fi
fi
@ -47,6 +53,5 @@ fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -3,3 +3,4 @@ export * from './model/models';
export * from './variables';
export * from './configuration';
export * from './api.module';
export * from './param';

View File

@ -1,37 +1,24 @@
/**
* Swagger Additional Properties
* OpenAPI Additional Properties
* This is a test spec
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
* The version of the OpenAPI document: 1.0.0
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface User {
[key: string]: string | any;
[key: string]: string | any;
id?: number;
/**
* User Status
*/
userStatus?: number;
}

View File

@ -0,0 +1,6 @@
{
"$schema": "./node_modules/ng-packagr/ng-package.schema.json",
"lib": {
"entryFile": "index.ts"
}
}

View File

@ -1,38 +1,34 @@
{
"name": "additionalPropertiesTest",
"version": "1.0.2",
"description": "swagger client for additionalPropertiesTest",
"author": "Swagger Codegen Contributors",
"description": "OpenAPI client for additionalPropertiesTest",
"author": "OpenAPI-Generator Contributors",
"repository": {
"type": "git",
"url": "https:////.git"
},
"keywords": [
"swagger-client"
"openapi-client",
"openapi-generator"
],
"license": "Apache-2.0",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"license": "Unlicense",
"scripts": {
"build": "typings install && tsc --outDir dist/"
"build": "ng-packagr -p ng-package.json"
},
"peerDependencies": {
"@angular/core": "^2.0.0",
"@angular/http": "^2.0.0",
"@angular/common": "^2.0.0",
"@angular/compiler": "^2.0.0",
"core-js": "^2.4.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.12",
"zone.js": "^0.6.17"
"@angular/core": "^14.0.5",
"rxjs": "^7.5.5"
},
"devDependencies": {
"@angular/core": "^2.0.0",
"@angular/http": "^2.0.0",
"@angular/common": "^2.0.0",
"@angular/compiler": "^2.0.0",
"@angular/platform-browser": "^2.0.0",
"core-js": "^2.4.0",
"@angular/common": "^14.0.5",
"@angular/compiler": "^14.0.5",
"@angular/compiler-cli": "^14.0.5",
"@angular/core": "^14.0.5",
"@angular/platform-browser": "^14.0.5",
"ng-packagr": "^14.0.2",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.12",
"zone.js": "^0.6.17",
"typescript": "^4.0",
"typings": "^1.3.2"
}
}
"rxjs": "^7.5.5",
"tsickle": "^0.46.3",
"typescript": ">=4.6.0 <=4.8.0",
"zone.js": "^0.11.5"
}}

View File

@ -0,0 +1,69 @@
/**
* Standard parameter styles defined by OpenAPI spec
*/
export type StandardParamStyle =
| 'matrix'
| 'label'
| 'form'
| 'simple'
| 'spaceDelimited'
| 'pipeDelimited'
| 'deepObject'
;
/**
* The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user.
*/
export type ParamStyle = StandardParamStyle | string;
/**
* Standard parameter locations defined by OpenAPI spec
*/
export type ParamLocation = 'query' | 'header' | 'path' | 'cookie';
/**
* Standard types as defined in <a href="https://swagger.io/specification/#data-types">OpenAPI Specification: Data Types</a>
*/
export type StandardDataType =
| "integer"
| "number"
| "boolean"
| "string"
| "object"
| "array"
;
/**
* Standard {@link DataType}s plus your own types/classes.
*/
export type DataType = StandardDataType | string;
/**
* Standard formats as defined in <a href="https://swagger.io/specification/#data-types">OpenAPI Specification: Data Types</a>
*/
export type StandardDataFormat =
| "int32"
| "int64"
| "float"
| "double"
| "byte"
| "binary"
| "date"
| "date-time"
| "password"
;
export type DataFormat = StandardDataFormat | string;
/**
* The parameter to encode.
*/
export interface Param {
name: string;
value: unknown;
in: ParamLocation;
style: ParamStyle,
explode: boolean;
dataType: DataType;
dataFormat: DataFormat | undefined;
}

View File

@ -1,11 +0,0 @@
// RxJS imports according to https://angular.io/docs/ts/latest/guide/server-communication.html#!#rxjs
// See node_module/rxjs/Rxjs.js
// Import just the rxjs statics and operators we need for THIS app.
// Statics
import 'rxjs/add/observable/throw';
// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

View File

@ -1,28 +1,28 @@
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true,
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"removeComments": true,
"sourceMap": true,
"outDir": "./lib",
"noLib": false,
"declaration": true
},
"exclude": [
"node_modules",
"typings/main.d.ts",
"typings/main",
"lib",
"dist"
],
"filesGlob": [
"./model/*.ts",
"./api/*.ts",
"typings/browser.d.ts"
]
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true,
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"removeComments": true,
"sourceMap": true,
"outDir": "./dist",
"noLib": false,
"declaration": true,
"lib": [ "es6", "dom" ],
"typeRoots": [
"node_modules/@types"
]
},
"exclude": [
"node_modules",
"dist"
],
"filesGlob": [
"./model/*.ts",
"./api/*.ts"
]
}

View File

@ -1,5 +0,0 @@
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160725163759"
}
}

View File

@ -1,3 +1,9 @@
import { OpaqueToken } from '@angular/core';
import { InjectionToken } from '@angular/core';
export const BASE_PATH = new OpaqueToken('basePath');
export const BASE_PATH = new InjectionToken<string>('basePath');
export const COLLECTION_FORMATS = {
'csv': ',',
'tsv': ' ',
'ssv': ' ',
'pipes': '|'
}

View File

@ -1,3 +1,4 @@
wwwroot/*.js
node_modules
typings
dist

View File

@ -1,23 +0,0 @@
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# 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 Swagger Codegen 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

View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -2,7 +2,7 @@
### Building
To build and compile the typescript sources to javascript use:
To install the required dependencies and to build the typescript sources run:
```
npm install
npm run build
@ -10,11 +10,11 @@ npm run build
### publishing
First build the package than run ```npm publish```
First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!)
### consuming
navigate to the folder of your consuming project and run one of next commando's.
Navigate to the folder of your consuming project and run one of next commands.
_published:_
@ -22,23 +22,205 @@ _published:_
npm install arrayAndAnyTest@1.0.2 --save
```
_unPublished (not recommended):_
_without publishing (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save
npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save
```
In your angular2 project:
_It's important to take the tgz file, otherwise you'll get trouble with links on windows_
_using `npm link`:_
In PATH_TO_GENERATED_PACKAGE/dist:
```
npm link
```
In your project:
```
npm link arrayAndAnyTest
```
__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages.
Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround.
Published packages are not effected by this issue.
#### General usage
In your Angular project:
```
// without configuring providers
import { ApiModule } from 'arrayAndAnyTest';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
ApiModule,
// make sure to import the HttpClientModule in the AppModule only,
// see https://github.com/angular/angular/issues/20575
HttpClientModule
],
declarations: [ AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
```
// configuring providers
import { ApiModule, Configuration, ConfigurationParameters } from 'arrayAndAnyTest';
export function apiConfigFactory (): Configuration {
const params: ConfigurationParameters = {
// set configuration parameters here.
}
return new Configuration(params);
}
@NgModule({
imports: [ ApiModule.forRoot(apiConfigFactory) ],
declarations: [ AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
```
// configuring providers with an authentication service that manages your access tokens
import { ApiModule, Configuration } from 'arrayAndAnyTest';
@NgModule({
imports: [ ApiModule ],
declarations: [ AppComponent ],
providers: [
{
provide: Configuration,
useFactory: (authService: AuthService) => new Configuration(
{
basePath: environment.apiUrl,
accessToken: authService.getAccessToken.bind(authService)
}
),
deps: [AuthService],
multi: false
}
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
```
import { DefaultApi } from 'arrayAndAnyTest';
export class AppComponent {
constructor(private apiGateway: DefaultApi) { }
}
```
Note: The ApiModule is restricted to being instantiated once app wide.
This is to ensure that all services are treated as singletons.
#### Using multiple OpenAPI files / APIs / ApiModules
In order to use multiple `ApiModules` generated from different OpenAPI files,
you can create an alias name when importing the modules
in order to avoid naming conflicts:
```
import { ApiModule } from 'my-api-path';
import { ApiModule as OtherApiModule } from 'my-other-api-path';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
ApiModule,
OtherApiModule,
// make sure to import the HttpClientModule in the AppModule only,
// see https://github.com/angular/angular/issues/20575
HttpClientModule
]
})
export class AppModule {
}
```
TODO: paste example.
### Set service base path
If different than the generated base path, during app bootstrap, you can provide the base path to your service.
```
import { BASE_PATH } from './path-to-swagger-gen-service/index';
import { BASE_PATH } from 'arrayAndAnyTest';
bootstrap(AppComponent, [
{ provide: BASE_PATH, useValue: 'https://your-web-service.com' },
]);
```
or
```
import { BASE_PATH } from 'arrayAndAnyTest';
@NgModule({
imports: [],
declarations: [ AppComponent ],
providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
#### Using @angular/cli
First extend your `src/environments/*.ts` files by adding the corresponding base path:
```
export const environment = {
production: false,
API_BASE_PATH: 'http://127.0.0.1:8080'
};
```
In the src/app/app.module.ts:
```
import { BASE_PATH } from 'arrayAndAnyTest';
import { environment } from '../environments/environment';
@NgModule({
declarations: [
AppComponent
],
imports: [ ],
providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }],
bootstrap: [ AppComponent ]
})
export class AppModule { }
```
### Customizing path parameter encoding
Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple'
and Dates for format 'date-time' are encoded correctly.
Other styles (e.g. "matrix") are not that easy to encode
and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]).
To implement your own parameter encoding (or call another library),
pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object
(see [General Usage](#general-usage) above).
Example value for use in your Configuration-Provider:
```typescript
new Configuration({
encodeParam: (param: Param) => myFancyParamEncoder(param),
})
```
[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations
[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values
[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander

View File

@ -1,21 +1,31 @@
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core';
import { Configuration } from './configuration';
import { HttpClient } from '@angular/common/http';
import { ProjectService } from './api/project.service';
@NgModule({
imports: [ CommonModule, HttpModule ],
imports: [],
declarations: [],
exports: [],
providers: [ ProjectService ]
providers: []
})
export class ApiModule {
public static forConfig(configuration: Configuration): ModuleWithProviders {
public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders<ApiModule> {
return {
ngModule: ApiModule,
providers: [ {provide: Configuration, useValue: configuration}]
providers: [ { provide: Configuration, useFactory: configurationFactory } ]
};
}
constructor( @Optional() @SkipSelf() parentModule: ApiModule,
@Optional() http: HttpClient) {
if (parentModule) {
throw new Error('ApiModule is already loaded. Import in your base AppModule only.');
}
if (!http) {
throw new Error('You need to import the HttpClientModule in your AppModule! \n' +
'See also https://github.com/angular/angular/issues/20575');
}
}
}

View File

@ -1 +1,3 @@
export * from './project.service';
import { ProjectService } from './project.service';
export const APIS = [ProjectService];

View File

@ -1,58 +1,109 @@
/**
* Cupix API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* OpenAPI spec version: 1.7.0
* The version of the OpenAPI document: 1.7.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Inject, Injectable, Optional } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Response, ResponseContentType } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import '../rxjs-operators';
import { ProjectEntity } from '../model/projectEntity';
import { ProjectList } from '../model/projectList';
import { BASE_PATH } from '../variables';
import { Configuration } from '../configuration';
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
@Injectable()
// @ts-ignore
import { ProjectEntity } from '../model/projectEntity';
// @ts-ignore
import { ProjectList } from '../model/projectList';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
@Injectable({
providedIn: 'root'
})
export class ProjectService {
protected basePath = 'https://localhost/v1';
public defaultHeaders: Headers = new Headers();
public configuration: Configuration = new Configuration();
constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (basePath) {
this.basePath = basePath;
}
protected basePath = '/v1';
public defaultHeaders = new HttpHeaders();
public configuration = new Configuration();
public encoder: HttpParameterCodec;
constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) {
if (configuration) {
this.configuration = configuration;
this.basePath = basePath || configuration.basePath || this.basePath;
}
if (typeof this.configuration.basePath !== 'string') {
if (Array.isArray(basePath) && basePath.length > 0) {
basePath = basePath[0];
}
if (typeof basePath !== 'string') {
basePath = this.basePath;
}
this.configuration.basePath = basePath;
}
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
}
/**
* @param consumes string[] mime-types
* @return true: consumes contains 'multipart/form-data', false: otherwise
*/
private canConsumeForm(consumes: string[]): boolean {
const form = 'multipart/form-data';
for (const consume of consumes) {
if (form === consume) {
return true;
}
}
return false;
}
// @ts-ignore
private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams {
if (typeof value === "object" && value instanceof Date === false) {
httpParams = this.addToHttpParamsRecursive(httpParams, value);
} else {
httpParams = this.addToHttpParamsRecursive(httpParams, value, key);
}
return httpParams;
}
private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams {
if (value == null) {
return httpParams;
}
if (typeof value === "object") {
if (Array.isArray(value)) {
(value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
} else if (value instanceof Date) {
if (key != null) {
httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10));
} else {
throw Error("key may not be null if value is Date");
}
} else {
Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive(
httpParams, value[k], key != null ? `${key}.${k}` : k));
}
} else if (key != null) {
httpParams = httpParams.append(key, value);
} else {
throw Error("key may not be null if value is not object or array");
}
return httpParams;
}
/**
@ -63,233 +114,206 @@ export class ProjectService {
* @param longitude
* @param latitude
* @param meta
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public createProject(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, extraHttpRequestParams?: any): Observable<ProjectEntity> {
return this.createProjectWithHttpInfo(name, address, longitude, latitude, meta, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
public createProject(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<ProjectEntity>;
public createProject(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpResponse<ProjectEntity>>;
public createProject(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpEvent<ProjectEntity>>;
public createProject(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<any> {
/**
* Delete a Project
* Returns a Project JSON object
* @param id Project id
*/
public deleteProjectById(id: number, extraHttpRequestParams?: any): Observable<{}> {
return this.deleteProjectByIdWithHttpInfo(id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Get a Project
* Returns a Project JSON object
* @param id Project id
*/
public getProjectById(id: number, extraHttpRequestParams?: any): Observable<ProjectEntity> {
return this.getProjectByIdWithHttpInfo(id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Get project list
* Returns a Project JSON object
* @param page
* @param perPage
* @param kind
* @param q
* @param filter
* @param latitude Valid with kind as location
* @param longitude Valid with kind as location
* @param scope Valid with kind as location, and between 1~9
*/
public getProjectList(page?: number, perPage?: number, kind?: string, q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, extraHttpRequestParams?: any): Observable<ProjectList> {
return this.getProjectListWithHttpInfo(page, perPage, kind, q, filter, latitude, longitude, scope, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Update project
*
* @param id Project id
* @param name User ID
* @param address Address
* @param longitude
* @param latitude
* @param meta
* @param thumbnail Project thumbnail
*/
public updateProject(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: any, extraHttpRequestParams?: any): Observable<ProjectEntity> {
return this.updateProjectWithHttpInfo(id, name, address, longitude, latitude, meta, thumbnail, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Create a Project
* Creates an empty Project
* @param name
* @param address
* @param longitude
* @param latitude
* @param meta
*/
public createProjectWithHttpInfo(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/projects`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
let formParams = new URLSearchParams();
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
let consumes: string[] = [
const consumes: string[] = [
'application/x-www-form-urlencoded'
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
headers.set('Content-Type', 'application/x-www-form-urlencoded');
const canConsumeForm = this.canConsumeForm(consumes);
let localVarFormParams: { append(param: string, value: any): any; };
let localVarUseForm = false;
let localVarConvertFormParamsToString = false;
if (localVarUseForm) {
localVarFormParams = new FormData();
} else {
localVarFormParams = new HttpParams({encoder: this.encoder});
}
if (name !== undefined) {
formParams.set('name', <any>name);
localVarFormParams = localVarFormParams.append('name', <any>name) as any || localVarFormParams;
}
if (address !== undefined) {
formParams.set('address', <any>address);
localVarFormParams = localVarFormParams.append('address', <any>address) as any || localVarFormParams;
}
if (longitude !== undefined) {
formParams.set('longitude', <any>longitude);
localVarFormParams = localVarFormParams.append('longitude', <any>longitude) as any || localVarFormParams;
}
if (latitude !== undefined) {
formParams.set('latitude', <any>latitude);
localVarFormParams = localVarFormParams.append('latitude', <any>latitude) as any || localVarFormParams;
}
if (meta !== undefined) {
formParams.set('meta', <any>meta);
localVarFormParams = localVarFormParams.append('meta', <any>meta) as any || localVarFormParams;
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: formParams.toString(),
search: queryParameters,
responseType: ResponseContentType.Json
});
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
return this.http.request(path, requestOptions);
let localVarPath = `/projects`;
return this.httpClient.post<ProjectEntity>(`${this.configuration.basePath}${localVarPath}`,
localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Delete a Project
* Returns a Project JSON object
* @param id Project id
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public deleteProjectByIdWithHttpInfo(id: number, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/projects/${id}`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
public deleteProjectById(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<any>;
public deleteProjectById(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpResponse<any>>;
public deleteProjectById(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpEvent<any>>;
public deleteProjectById(id: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling deleteProjectById.');
}
let localVarHeaders = this.defaultHeaders;
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters,
responseType: ResponseContentType.Json
});
return this.http.request(path, requestOptions);
let localVarPath = `/projects/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int32"})}`;
return this.httpClient.delete<any>(`${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get a Project
* Returns a Project JSON object
* @param id Project id
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getProjectByIdWithHttpInfo(id: number, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/projects/${id}`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
public getProjectById(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<ProjectEntity>;
public getProjectById(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpResponse<ProjectEntity>>;
public getProjectById(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpEvent<ProjectEntity>>;
public getProjectById(id: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling getProjectById.');
}
let localVarHeaders = this.defaultHeaders;
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
responseType: ResponseContentType.Json
});
return this.http.request(path, requestOptions);
let localVarPath = `/projects/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int32"})}`;
return this.httpClient.get<ProjectEntity>(`${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
@ -303,65 +327,95 @@ export class ProjectService {
* @param latitude Valid with kind as location
* @param longitude Valid with kind as location
* @param scope Valid with kind as location, and between 1~9
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getProjectListWithHttpInfo(page?: number, perPage?: number, kind?: string, q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/projects`;
public getProjectList(page?: number, perPage?: number, kind?: 'my_models' | 'published' | 'location', q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<ProjectList>;
public getProjectList(page?: number, perPage?: number, kind?: 'my_models' | 'published' | 'location', q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpResponse<ProjectList>>;
public getProjectList(page?: number, perPage?: number, kind?: 'my_models' | 'published' | 'location', q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpEvent<ProjectList>>;
public getProjectList(page?: number, perPage?: number, kind?: 'my_models' | 'published' | 'location', q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<any> {
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (page !== undefined) {
queryParameters.set('page', <any>page);
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (page !== undefined && page !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
}
if (perPage !== undefined) {
queryParameters.set('per_page', <any>perPage);
if (perPage !== undefined && perPage !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>perPage, 'per_page');
}
if (kind !== undefined) {
queryParameters.set('kind', <any>kind);
if (kind !== undefined && kind !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>kind, 'kind');
}
if (q !== undefined) {
queryParameters.set('q', <any>q);
if (q !== undefined && q !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>q, 'q');
}
if (filter !== undefined) {
queryParameters.set('filter', <any>filter);
if (filter !== undefined && filter !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>filter, 'filter');
}
if (latitude !== undefined) {
queryParameters.set('latitude', <any>latitude);
if (latitude !== undefined && latitude !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>latitude, 'latitude');
}
if (longitude !== undefined) {
queryParameters.set('longitude', <any>longitude);
if (longitude !== undefined && longitude !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>longitude, 'longitude');
}
if (scope !== undefined) {
queryParameters.set('scope', <any>scope);
if (scope !== undefined && scope !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>scope, 'scope');
}
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
responseType: ResponseContentType.Json
});
return this.http.request(path, requestOptions);
let localVarPath = `/projects`;
return this.httpClient.get<ProjectList>(`${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Update project
*
* @param id Project id
* @param name User ID
* @param address Address
@ -369,62 +423,97 @@ export class ProjectService {
* @param latitude
* @param meta
* @param thumbnail Project thumbnail
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public updateProjectWithHttpInfo(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: any, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/projects/${id}`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
let formParams = new URLSearchParams();
// verify required parameter 'id' is not null or undefined
public updateProject(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<ProjectEntity>;
public updateProject(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpResponse<ProjectEntity>>;
public updateProject(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpEvent<ProjectEntity>>;
public updateProject(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling updateProject.');
}
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
let consumes: string[] = [
const consumes: string[] = [
'multipart/form-data'
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
headers.set('Content-Type', 'application/x-www-form-urlencoded');
const canConsumeForm = this.canConsumeForm(consumes);
let localVarFormParams: { append(param: string, value: any): any; };
let localVarUseForm = false;
let localVarConvertFormParamsToString = false;
// use FormData to transmit files using content-type "multipart/form-data"
// see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data
localVarUseForm = canConsumeForm;
if (localVarUseForm) {
localVarFormParams = new FormData();
} else {
localVarFormParams = new HttpParams({encoder: this.encoder});
}
if (name !== undefined) {
formParams.set('name', <any>name);
localVarFormParams = localVarFormParams.append('name', <any>name) as any || localVarFormParams;
}
if (address !== undefined) {
formParams.set('address', <any>address);
localVarFormParams = localVarFormParams.append('address', <any>address) as any || localVarFormParams;
}
if (longitude !== undefined) {
formParams.set('longitude', <any>longitude);
localVarFormParams = localVarFormParams.append('longitude', <any>longitude) as any || localVarFormParams;
}
if (latitude !== undefined) {
formParams.set('latitude', <any>latitude);
localVarFormParams = localVarFormParams.append('latitude', <any>latitude) as any || localVarFormParams;
}
if (meta !== undefined) {
formParams.set('meta', <any>meta);
localVarFormParams = localVarFormParams.append('meta', <any>meta) as any || localVarFormParams;
}
if (thumbnail !== undefined) {
formParams.set('thumbnail', <any>thumbnail);
localVarFormParams = localVarFormParams.append('thumbnail', <any>thumbnail) as any || localVarFormParams;
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: formParams.toString(),
search: queryParameters,
responseType: ResponseContentType.Json
});
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
return this.http.request(path, requestOptions);
let localVarPath = `/projects/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int32"})}`;
return this.httpClient.put<ProjectEntity>(`${this.configuration.basePath}${localVarPath}`,
localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
}

View File

@ -1,24 +1,166 @@
import { HttpParameterCodec } from '@angular/common/http';
import { Param } from './param';
export interface ConfigurationParameters {
apiKey?: string;
username?: string;
password?: string;
accessToken?: string;
basePath?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* Override the default method for encoding path parameters in various
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam?: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'.
*/
credentials?: {[ key: string ]: string | (() => string | undefined)};
}
export class Configuration {
apiKey: string;
username: string;
password: string;
accessToken: string;
basePath: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* Encoding of various path parameter
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'.
*/
credentials: {[ key: string ]: string | (() => string | undefined)};
constructor(configurationParameters: ConfigurationParameters = {}) {
this.apiKeys = configurationParameters.apiKeys;
this.username = configurationParameters.username;
this.password = configurationParameters.password;
this.accessToken = configurationParameters.accessToken;
this.basePath = configurationParameters.basePath;
this.withCredentials = configurationParameters.withCredentials;
this.encoder = configurationParameters.encoder;
if (configurationParameters.encodeParam) {
this.encodeParam = configurationParameters.encodeParam;
}
else {
this.encodeParam = param => this.defaultEncodeParam(param);
}
if (configurationParameters.credentials) {
this.credentials = configurationParameters.credentials;
}
else {
this.credentials = {};
}
}
constructor(configurationParameters: ConfigurationParameters = {}) {
this.apiKey = configurationParameters.apiKey;
this.username = configurationParameters.username;
this.password = configurationParameters.password;
this.accessToken = configurationParameters.accessToken;
this.basePath = configurationParameters.basePath;
}
/**
* Select the correct content-type to use for a request.
* Uses {@link Configuration#isJsonMime} to determine the correct content-type.
* If no content type is found return the first found type if the contentTypes is not empty
* @param contentTypes - the array of content types that are available for selection
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderContentType (contentTypes: string[]): string | undefined {
if (contentTypes.length === 0) {
return undefined;
}
const type = contentTypes.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return contentTypes[0];
}
return type;
}
/**
* Select the correct accept content-type to use for a request.
* Uses {@link Configuration#isJsonMime} to determine the correct accept content-type.
* If no content type is found return the first found type if the contentTypes is not empty
* @param accepts - the array of content types that are available for selection.
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderAccept(accepts: string[]): string | undefined {
if (accepts.length === 0) {
return undefined;
}
const type = accepts.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return accepts[0];
}
return type;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
public isJsonMime(mime: string): boolean {
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
}
public lookupCredential(key: string): string | undefined {
const value = this.credentials[key];
return typeof value === 'function'
? value()
: value;
}
private defaultEncodeParam(param: Param): string {
// This implementation exists as fallback for missing configuration
// and for backwards compatibility to older typescript-angular generator versions.
// It only works for the 'simple' parameter style.
// Date-handling only works for the 'date-time' format.
// All other styles and Date-formats are probably handled incorrectly.
//
// But: if that's all you need (i.e.: the most common use-case): no need for customization!
const value = param.dataFormat === 'date-time'
? (param.value as Date).toISOString()
: param.value;
return encodeURIComponent(String(value));
}
}

View File

@ -0,0 +1,20 @@
import { HttpParameterCodec } from '@angular/common/http';
/**
* Custom HttpParameterCodec
* Workaround for https://github.com/angular/angular/issues/18261
*/
export class CustomHttpParameterCodec implements HttpParameterCodec {
encodeKey(k: string): string {
return encodeURIComponent(k);
}
encodeValue(v: string): string {
return encodeURIComponent(v);
}
decodeKey(k: string): string {
return decodeURIComponent(k);
}
decodeValue(v: string): string {
return decodeURIComponent(v);
}
}

View File

@ -1,11 +1,17 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update"
# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host=""
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id=""
@ -37,9 +43,9 @@ if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@github.com/${git_user_id}/${git_repo_id}.git
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git
fi
fi
@ -47,6 +53,5 @@ fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -3,3 +3,4 @@ export * from './model/models';
export * from './variables';
export * from './configuration';
export * from './api.module';
export * from './param';

View File

@ -1,54 +1,34 @@
/**
* Cupix API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* OpenAPI spec version: 1.7.0
* The version of the OpenAPI document: 1.7.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ProjectEntityLocation } from './projectEntityLocation';
export interface ProjectEntity {
id: number;
kind?: ProjectEntity.KindEnum;
thumbnailUrl?: string;
thumbnail_url?: string;
name?: string;
state?: string;
meta?: any;
meta?: object;
location?: ProjectEntityLocation;
createdAt?: Date;
updatedAt?: Date;
publishedAt?: Date;
created_at?: string;
updated_at?: string;
published_at?: string;
}
export namespace ProjectEntity {
export enum KindEnum {
Project = <any> 'project'
}
export type KindEnum = 'project';
export const KindEnum = {
Project: 'project' as KindEnum
};
}

View File

@ -1,32 +1,18 @@
/**
* Cupix API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* OpenAPI spec version: 1.7.0
* The version of the OpenAPI document: 1.7.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface ProjectEntityLocation {
lat?: number;
lon?: number;
}

View File

@ -1,31 +1,18 @@
/**
* Cupix API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* OpenAPI spec version: 1.7.0
* The version of the OpenAPI document: 1.7.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ProjectEntity } from './projectEntity';
export interface ProjectList {
contents: Array<ProjectEntity>;
}

View File

@ -0,0 +1,6 @@
{
"$schema": "./node_modules/ng-packagr/ng-package.schema.json",
"lib": {
"entryFile": "index.ts"
}
}

View File

@ -1,38 +1,34 @@
{
"name": "arrayAndAnyTest",
"version": "1.0.2",
"description": "swagger client for arrayAndAnyTest",
"author": "Swagger Codegen Contributors",
"description": "OpenAPI client for arrayAndAnyTest",
"author": "OpenAPI-Generator Contributors",
"repository": {
"type": "git",
"url": "https:////.git"
},
"keywords": [
"swagger-client"
"openapi-client",
"openapi-generator"
],
"license": "Apache-2.0",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"license": "Unlicense",
"scripts": {
"build": "typings install && tsc --outDir dist/"
"build": "ng-packagr -p ng-package.json"
},
"peerDependencies": {
"@angular/core": "^2.0.0",
"@angular/http": "^2.0.0",
"@angular/common": "^2.0.0",
"@angular/compiler": "^2.0.0",
"core-js": "^2.4.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.12",
"zone.js": "^0.6.17"
"@angular/core": "^14.0.5",
"rxjs": "^7.5.5"
},
"devDependencies": {
"@angular/core": "^2.0.0",
"@angular/http": "^2.0.0",
"@angular/common": "^2.0.0",
"@angular/compiler": "^2.0.0",
"@angular/platform-browser": "^2.0.0",
"core-js": "^2.4.0",
"@angular/common": "^14.0.5",
"@angular/compiler": "^14.0.5",
"@angular/compiler-cli": "^14.0.5",
"@angular/core": "^14.0.5",
"@angular/platform-browser": "^14.0.5",
"ng-packagr": "^14.0.2",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.12",
"zone.js": "^0.6.17",
"typescript": "^4.0",
"typings": "^1.3.2"
}
}
"rxjs": "^7.5.5",
"tsickle": "^0.46.3",
"typescript": ">=4.6.0 <=4.8.0",
"zone.js": "^0.11.5"
}}

View File

@ -0,0 +1,69 @@
/**
* Standard parameter styles defined by OpenAPI spec
*/
export type StandardParamStyle =
| 'matrix'
| 'label'
| 'form'
| 'simple'
| 'spaceDelimited'
| 'pipeDelimited'
| 'deepObject'
;
/**
* The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user.
*/
export type ParamStyle = StandardParamStyle | string;
/**
* Standard parameter locations defined by OpenAPI spec
*/
export type ParamLocation = 'query' | 'header' | 'path' | 'cookie';
/**
* Standard types as defined in <a href="https://swagger.io/specification/#data-types">OpenAPI Specification: Data Types</a>
*/
export type StandardDataType =
| "integer"
| "number"
| "boolean"
| "string"
| "object"
| "array"
;
/**
* Standard {@link DataType}s plus your own types/classes.
*/
export type DataType = StandardDataType | string;
/**
* Standard formats as defined in <a href="https://swagger.io/specification/#data-types">OpenAPI Specification: Data Types</a>
*/
export type StandardDataFormat =
| "int32"
| "int64"
| "float"
| "double"
| "byte"
| "binary"
| "date"
| "date-time"
| "password"
;
export type DataFormat = StandardDataFormat | string;
/**
* The parameter to encode.
*/
export interface Param {
name: string;
value: unknown;
in: ParamLocation;
style: ParamStyle,
explode: boolean;
dataType: DataType;
dataFormat: DataFormat | undefined;
}

View File

@ -1,11 +0,0 @@
// RxJS imports according to https://angular.io/docs/ts/latest/guide/server-communication.html#!#rxjs
// See node_module/rxjs/Rxjs.js
// Import just the rxjs statics and operators we need for THIS app.
// Statics
import 'rxjs/add/observable/throw';
// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

View File

@ -1,28 +1,28 @@
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true,
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"removeComments": true,
"sourceMap": true,
"outDir": "./lib",
"noLib": false,
"declaration": true
},
"exclude": [
"node_modules",
"typings/main.d.ts",
"typings/main",
"lib",
"dist"
],
"filesGlob": [
"./model/*.ts",
"./api/*.ts",
"typings/browser.d.ts"
]
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true,
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"removeComments": true,
"sourceMap": true,
"outDir": "./dist",
"noLib": false,
"declaration": true,
"lib": [ "es6", "dom" ],
"typeRoots": [
"node_modules/@types"
]
},
"exclude": [
"node_modules",
"dist"
],
"filesGlob": [
"./model/*.ts",
"./api/*.ts"
]
}

View File

@ -1,5 +0,0 @@
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160725163759"
}
}

View File

@ -1,3 +1,9 @@
import { OpaqueToken } from '@angular/core';
import { InjectionToken } from '@angular/core';
export const BASE_PATH = new OpaqueToken('basePath');
export const BASE_PATH = new InjectionToken<string>('basePath');
export const COLLECTION_FORMATS = {
'csv': ',',
'tsv': ' ',
'ssv': ' ',
'pipes': '|'
}

View File

@ -0,0 +1,4 @@
wwwroot/*.js
node_modules
typings
dist

View File

@ -0,0 +1,226 @@
## custom-path-params-integration-test@1.0.3
### Building
To install the required dependencies and to build the typescript sources run:
```
npm install
npm run build
```
### publishing
First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!)
### consuming
Navigate to the folder of your consuming project and run one of next commands.
_published:_
```
npm install custom-path-params-integration-test@1.0.3 --save
```
_without publishing (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save
```
_It's important to take the tgz file, otherwise you'll get trouble with links on windows_
_using `npm link`:_
In PATH_TO_GENERATED_PACKAGE/dist:
```
npm link
```
In your project:
```
npm link custom-path-params-integration-test
```
__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages.
Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround.
Published packages are not effected by this issue.
#### General usage
In your Angular project:
```
// without configuring providers
import { ApiModule } from 'custom-path-params-integration-test';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
ApiModule,
// make sure to import the HttpClientModule in the AppModule only,
// see https://github.com/angular/angular/issues/20575
HttpClientModule
],
declarations: [ AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
```
// configuring providers
import { ApiModule, Configuration, ConfigurationParameters } from 'custom-path-params-integration-test';
export function apiConfigFactory (): Configuration {
const params: ConfigurationParameters = {
// set configuration parameters here.
}
return new Configuration(params);
}
@NgModule({
imports: [ ApiModule.forRoot(apiConfigFactory) ],
declarations: [ AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
```
// configuring providers with an authentication service that manages your access tokens
import { ApiModule, Configuration } from 'custom-path-params-integration-test';
@NgModule({
imports: [ ApiModule ],
declarations: [ AppComponent ],
providers: [
{
provide: Configuration,
useFactory: (authService: AuthService) => new Configuration(
{
basePath: environment.apiUrl,
accessToken: authService.getAccessToken.bind(authService)
}
),
deps: [AuthService],
multi: false
}
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
```
import { DefaultApi } from 'custom-path-params-integration-test';
export class AppComponent {
constructor(private apiGateway: DefaultApi) { }
}
```
Note: The ApiModule is restricted to being instantiated once app wide.
This is to ensure that all services are treated as singletons.
#### Using multiple OpenAPI files / APIs / ApiModules
In order to use multiple `ApiModules` generated from different OpenAPI files,
you can create an alias name when importing the modules
in order to avoid naming conflicts:
```
import { ApiModule } from 'my-api-path';
import { ApiModule as OtherApiModule } from 'my-other-api-path';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
ApiModule,
OtherApiModule,
// make sure to import the HttpClientModule in the AppModule only,
// see https://github.com/angular/angular/issues/20575
HttpClientModule
]
})
export class AppModule {
}
```
### Set service base path
If different than the generated base path, during app bootstrap, you can provide the base path to your service.
```
import { BASE_PATH } from 'custom-path-params-integration-test';
bootstrap(AppComponent, [
{ provide: BASE_PATH, useValue: 'https://your-web-service.com' },
]);
```
or
```
import { BASE_PATH } from 'custom-path-params-integration-test';
@NgModule({
imports: [],
declarations: [ AppComponent ],
providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
#### Using @angular/cli
First extend your `src/environments/*.ts` files by adding the corresponding base path:
```
export const environment = {
production: false,
API_BASE_PATH: 'http://127.0.0.1:8080'
};
```
In the src/app/app.module.ts:
```
import { BASE_PATH } from 'custom-path-params-integration-test';
import { environment } from '../environments/environment';
@NgModule({
declarations: [
AppComponent
],
imports: [ ],
providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }],
bootstrap: [ AppComponent ]
})
export class AppModule { }
```
### Customizing path parameter encoding
Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple'
and Dates for format 'date-time' are encoded correctly.
Other styles (e.g. "matrix") are not that easy to encode
and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]).
To implement your own parameter encoding (or call another library),
pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object
(see [General Usage](#general-usage) above).
Example value for use in your Configuration-Provider:
```typescript
new Configuration({
encodeParam: (param: Param) => myFancyParamEncoder(param),
})
```
[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations
[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values
[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander

View File

@ -0,0 +1,31 @@
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core';
import { Configuration } from './configuration';
import { HttpClient } from '@angular/common/http';
import { MatrixParamsService } from './api/matrixParams.service';
@NgModule({
imports: [],
declarations: [],
exports: [],
providers: []
})
export class ApiModule {
public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders<ApiModule> {
return {
ngModule: ApiModule,
providers: [ { provide: Configuration, useFactory: configurationFactory } ]
};
}
constructor( @Optional() @SkipSelf() parentModule: ApiModule,
@Optional() http: HttpClient) {
if (parentModule) {
throw new Error('ApiModule is already loaded. Import in your base AppModule only.');
}
if (!http) {
throw new Error('You need to import the HttpClientModule in your AppModule! \n' +
'See also https://github.com/angular/angular/issues/20575');
}
}
}

View File

@ -0,0 +1,3 @@
export * from './matrixParams.service';
import { MatrixParamsService } from './matrixParams.service';
export const APIS = [MatrixParamsService];

View File

@ -0,0 +1,310 @@
/**
* Path Parameter Stuff
* This API shows the usage of various path parameter styles
*
* 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.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { ComplexParams } from '../model/complexParams';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
@Injectable({
providedIn: 'root'
})
export class MatrixParamsService {
protected basePath = 'http://localhost';
public defaultHeaders = new HttpHeaders();
public configuration = new Configuration();
public encoder: HttpParameterCodec;
constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) {
if (configuration) {
this.configuration = configuration;
}
if (typeof this.configuration.basePath !== 'string') {
if (Array.isArray(basePath) && basePath.length > 0) {
basePath = basePath[0];
}
if (typeof basePath !== 'string') {
basePath = this.basePath;
}
this.configuration.basePath = basePath;
}
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
}
// @ts-ignore
private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams {
if (typeof value === "object" && value instanceof Date === false) {
httpParams = this.addToHttpParamsRecursive(httpParams, value);
} else {
httpParams = this.addToHttpParamsRecursive(httpParams, value, key);
}
return httpParams;
}
private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams {
if (value == null) {
return httpParams;
}
if (typeof value === "object") {
if (Array.isArray(value)) {
(value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
} else if (value instanceof Date) {
if (key != null) {
httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10));
} else {
throw Error("key may not be null if value is Date");
}
} else {
Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive(
httpParams, value[k], key != null ? `${key}.${k}` : k));
}
} else if (key != null) {
httpParams = httpParams.append(key, value);
} else {
throw Error("key may not be null if value is not object or array");
}
return httpParams;
}
/**
* @param matrixParamExploded
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public complexMatrixParamExploded(matrixParamExploded?: ComplexParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public complexMatrixParamExploded(matrixParamExploded?: ComplexParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public complexMatrixParamExploded(matrixParamExploded?: ComplexParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public complexMatrixParamExploded(matrixParamExploded?: ComplexParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/complexMatrixParamExploded${this.configuration.encodeParam({name: "matrixParamExploded", value: matrixParamExploded, in: "path", style: "matrix", explode: true, dataType: "ComplexParams", dataFormat: undefined})}`;
return this.httpClient.put<any>(`${this.configuration.basePath}${localVarPath}`,
null,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* @param matrixParamFlat
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public complexMatrixParamFlat(matrixParamFlat?: ComplexParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public complexMatrixParamFlat(matrixParamFlat?: ComplexParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public complexMatrixParamFlat(matrixParamFlat?: ComplexParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public complexMatrixParamFlat(matrixParamFlat?: ComplexParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/complexMatrixParamFlat${this.configuration.encodeParam({name: "matrixParamFlat", value: matrixParamFlat, in: "path", style: "matrix", explode: false, dataType: "ComplexParams", dataFormat: undefined})}`;
return this.httpClient.put<any>(`${this.configuration.basePath}${localVarPath}`,
null,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* @param plainParamFlat
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public plainMatrixParamFlat(plainParamFlat?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public plainMatrixParamFlat(plainParamFlat?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public plainMatrixParamFlat(plainParamFlat?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public plainMatrixParamFlat(plainParamFlat?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/plainMatrixParamFlat${this.configuration.encodeParam({name: "plainParamFlat", value: plainParamFlat, in: "path", style: "matrix", explode: false, dataType: "string", dataFormat: undefined})}`;
return this.httpClient.put<any>(`${this.configuration.basePath}${localVarPath}`,
null,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* @param dateTimeParamFlat
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public plainMatrixParamFlat_1(dateTimeParamFlat?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public plainMatrixParamFlat_1(dateTimeParamFlat?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public plainMatrixParamFlat_1(dateTimeParamFlat?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public plainMatrixParamFlat_1(dateTimeParamFlat?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/date-timeMatrixParamFlat${this.configuration.encodeParam({name: "dateTimeParamFlat", value: dateTimeParamFlat, in: "path", style: "matrix", explode: false, dataType: "string", dataFormat: "date-time"})}`;
return this.httpClient.put<any>(`${this.configuration.basePath}${localVarPath}`,
null,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
}

View File

@ -0,0 +1,166 @@
import { HttpParameterCodec } from '@angular/common/http';
import { Param } from './param';
export interface ConfigurationParameters {
/**
* @deprecated Since 5.0. Use credentials instead
*/
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* Override the default method for encoding path parameters in various
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam?: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'.
*/
credentials?: {[ key: string ]: string | (() => string | undefined)};
}
export class Configuration {
/**
* @deprecated Since 5.0. Use credentials instead
*/
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* Encoding of various path parameter
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'.
*/
credentials: {[ key: string ]: string | (() => string | undefined)};
constructor(configurationParameters: ConfigurationParameters = {}) {
this.apiKeys = configurationParameters.apiKeys;
this.username = configurationParameters.username;
this.password = configurationParameters.password;
this.accessToken = configurationParameters.accessToken;
this.basePath = configurationParameters.basePath;
this.withCredentials = configurationParameters.withCredentials;
this.encoder = configurationParameters.encoder;
if (configurationParameters.encodeParam) {
this.encodeParam = configurationParameters.encodeParam;
}
else {
this.encodeParam = param => this.defaultEncodeParam(param);
}
if (configurationParameters.credentials) {
this.credentials = configurationParameters.credentials;
}
else {
this.credentials = {};
}
}
/**
* Select the correct content-type to use for a request.
* Uses {@link Configuration#isJsonMime} to determine the correct content-type.
* If no content type is found return the first found type if the contentTypes is not empty
* @param contentTypes - the array of content types that are available for selection
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderContentType (contentTypes: string[]): string | undefined {
if (contentTypes.length === 0) {
return undefined;
}
const type = contentTypes.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return contentTypes[0];
}
return type;
}
/**
* Select the correct accept content-type to use for a request.
* Uses {@link Configuration#isJsonMime} to determine the correct accept content-type.
* If no content type is found return the first found type if the contentTypes is not empty
* @param accepts - the array of content types that are available for selection.
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderAccept(accepts: string[]): string | undefined {
if (accepts.length === 0) {
return undefined;
}
const type = accepts.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return accepts[0];
}
return type;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
public isJsonMime(mime: string): boolean {
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
}
public lookupCredential(key: string): string | undefined {
const value = this.credentials[key];
return typeof value === 'function'
? value()
: value;
}
private defaultEncodeParam(param: Param): string {
// This implementation exists as fallback for missing configuration
// and for backwards compatibility to older typescript-angular generator versions.
// It only works for the 'simple' parameter style.
// Date-handling only works for the 'date-time' format.
// All other styles and Date-formats are probably handled incorrectly.
//
// But: if that's all you need (i.e.: the most common use-case): no need for customization!
const value = param.dataFormat === 'date-time'
? (param.value as Date).toISOString()
: param.value;
return encodeURIComponent(String(value));
}
}

View File

@ -0,0 +1,20 @@
import { HttpParameterCodec } from '@angular/common/http';
/**
* Custom HttpParameterCodec
* Workaround for https://github.com/angular/angular/issues/18261
*/
export class CustomHttpParameterCodec implements HttpParameterCodec {
encodeKey(k: string): string {
return encodeURIComponent(k);
}
encodeValue(v: string): string {
return encodeURIComponent(v);
}
decodeKey(k: string): string {
return decodeURIComponent(k);
}
decodeValue(v: string): string {
return decodeURIComponent(v);
}
}

View File

@ -0,0 +1,57 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host=""
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id=""
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id=""
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note=""
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=$(git remote)
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,6 @@
export * from './api/api';
export * from './model/models';
export * from './variables';
export * from './configuration';
export * from './api.module';
export * from './param';

View File

@ -0,0 +1,18 @@
/**
* Path Parameter Stuff
* This API shows the usage of various path parameter styles
*
* 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 interface ComplexParams {
key?: string;
value?: number;
}

View File

@ -0,0 +1,6 @@
{
"$schema": "./node_modules/ng-packagr/ng-package.schema.json",
"lib": {
"entryFile": "index.ts"
}
}

View File

@ -0,0 +1,34 @@
{
"name": "custom-path-params-integration-test",
"version": "1.0.3",
"description": "OpenAPI client for custom-path-params-integration-test",
"author": "OpenAPI-Generator Contributors",
"repository": {
"type": "git",
"url": "https:////.git"
},
"keywords": [
"openapi-client",
"openapi-generator"
],
"license": "Unlicense",
"scripts": {
"build": "ng-packagr -p ng-package.json"
},
"peerDependencies": {
"@angular/core": "^14.0.5",
"rxjs": "^7.5.5"
},
"devDependencies": {
"@angular/common": "^14.0.5",
"@angular/compiler": "^14.0.5",
"@angular/compiler-cli": "^14.0.5",
"@angular/core": "^14.0.5",
"@angular/platform-browser": "^14.0.5",
"ng-packagr": "^14.0.2",
"reflect-metadata": "^0.1.3",
"rxjs": "^7.5.5",
"tsickle": "^0.46.3",
"typescript": ">=4.6.0 <=4.8.0",
"zone.js": "^0.11.5"
}}

View File

@ -0,0 +1,69 @@
/**
* Standard parameter styles defined by OpenAPI spec
*/
export type StandardParamStyle =
| 'matrix'
| 'label'
| 'form'
| 'simple'
| 'spaceDelimited'
| 'pipeDelimited'
| 'deepObject'
;
/**
* The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user.
*/
export type ParamStyle = StandardParamStyle | string;
/**
* Standard parameter locations defined by OpenAPI spec
*/
export type ParamLocation = 'query' | 'header' | 'path' | 'cookie';
/**
* Standard types as defined in <a href="https://swagger.io/specification/#data-types">OpenAPI Specification: Data Types</a>
*/
export type StandardDataType =
| "integer"
| "number"
| "boolean"
| "string"
| "object"
| "array"
;
/**
* Standard {@link DataType}s plus your own types/classes.
*/
export type DataType = StandardDataType | string;
/**
* Standard formats as defined in <a href="https://swagger.io/specification/#data-types">OpenAPI Specification: Data Types</a>
*/
export type StandardDataFormat =
| "int32"
| "int64"
| "float"
| "double"
| "byte"
| "binary"
| "date"
| "date-time"
| "password"
;
export type DataFormat = StandardDataFormat | string;
/**
* The parameter to encode.
*/
export interface Param {
name: string;
value: unknown;
in: ParamLocation;
style: ParamStyle,
explode: boolean;
dataType: DataType;
dataFormat: DataFormat | undefined;
}

View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true,
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"removeComments": true,
"sourceMap": true,
"outDir": "./dist",
"noLib": false,
"declaration": true,
"lib": [ "es6", "dom" ],
"typeRoots": [
"node_modules/@types"
]
},
"exclude": [
"node_modules",
"dist"
],
"filesGlob": [
"./model/*.ts",
"./api/*.ts"
]
}

View File

@ -0,0 +1,9 @@
import { InjectionToken } from '@angular/core';
export const BASE_PATH = new InjectionToken<string>('basePath');
export const COLLECTION_FORMATS = {
'csv': ',',
'tsv': ' ',
'ssv': ' ',
'pipes': '|'
}

View File

@ -0,0 +1,129 @@
{
"openapi": "3.0.1",
"info": {
"title": "Path Parameter Stuff",
"description": "This API shows the usage of various path parameter styles",
"version": "1.0.0"
},
"paths": {
"/complexMatrixParamExploded{matrixParamExploded}": {
"parameters": [
{
"name": "matrixParamExploded",
"in": "path",
"style": "matrix",
"explode": true,
"required": false,
"schema": {
"$ref": "#/components/schemas/ComplexParams"
}
}
],
"put": {
"tags": [
"MatrixParams"
],
"operationId": "complexMatrixParamExploded",
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/complexMatrixParamFlat{matrixParamFlat}": {
"parameters": [
{
"name": "matrixParamFlat",
"in": "path",
"style": "matrix",
"explode": false,
"required": false,
"schema": {
"$ref": "#/components/schemas/ComplexParams"
}
}
],
"put": {
"tags": [
"MatrixParams"
],
"operationId": "complexMatrixParamFlat",
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/plainMatrixParamFlat{plainParamFlat}": {
"parameters": [
{
"name": "plainParamFlat",
"in": "path",
"style": "matrix",
"explode": false,
"required": false,
"schema": {
"$ref": "#/components/schemas/PlainParam"
}
}
],
"put": {
"tags": [
"MatrixParams"
],
"operationId": "plainMatrixParamFlat",
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/date-timeMatrixParamFlat{dateTimeParamFlat}": {
"parameters": [
{
"name": "dateTimeParamFlat",
"in": "path",
"style": "matrix",
"explode": false,
"required": false,
"schema": {
"type": "string",
"format": "date-time"
}
}
],
"put": {
"tags": [
"MatrixParams"
],
"operationId": "plainMatrixParamFlat",
"responses": {
"200": {
"description": "OK"
}
}
}
}
},
"components": {
"schemas": {
"PlainParam": {
"type": "string"
},
"ComplexParams": {
"properties": {
"key": {
"type": "string"
},
"value": {
"type": "number",
"format": "int64"
}
}
}
}
}
}

View File

@ -1,3 +1,4 @@
wwwroot/*.js
node_modules
typings
dist

View File

@ -1,23 +0,0 @@
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# 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 Swagger Codegen 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

View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -2,7 +2,7 @@
### Building
To build and compile the typescript sources to javascript use:
To install the required dependencies and to build the typescript sources run:
```
npm install
npm run build
@ -10,11 +10,11 @@ npm run build
### publishing
First build the package than run ```npm publish```
First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!)
### consuming
navigate to the folder of your consuming project and run one of next commando's.
Navigate to the folder of your consuming project and run one of next commands.
_published:_
@ -22,23 +22,205 @@ _published:_
npm install petstore-integration-test@1.0.3 --save
```
_unPublished (not recommended):_
_without publishing (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save
npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save
```
In your angular2 project:
_It's important to take the tgz file, otherwise you'll get trouble with links on windows_
_using `npm link`:_
In PATH_TO_GENERATED_PACKAGE/dist:
```
npm link
```
In your project:
```
npm link petstore-integration-test
```
__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages.
Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround.
Published packages are not effected by this issue.
#### General usage
In your Angular project:
```
// without configuring providers
import { ApiModule } from 'petstore-integration-test';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
ApiModule,
// make sure to import the HttpClientModule in the AppModule only,
// see https://github.com/angular/angular/issues/20575
HttpClientModule
],
declarations: [ AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
```
// configuring providers
import { ApiModule, Configuration, ConfigurationParameters } from 'petstore-integration-test';
export function apiConfigFactory (): Configuration {
const params: ConfigurationParameters = {
// set configuration parameters here.
}
return new Configuration(params);
}
@NgModule({
imports: [ ApiModule.forRoot(apiConfigFactory) ],
declarations: [ AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
```
// configuring providers with an authentication service that manages your access tokens
import { ApiModule, Configuration } from 'petstore-integration-test';
@NgModule({
imports: [ ApiModule ],
declarations: [ AppComponent ],
providers: [
{
provide: Configuration,
useFactory: (authService: AuthService) => new Configuration(
{
basePath: environment.apiUrl,
accessToken: authService.getAccessToken.bind(authService)
}
),
deps: [AuthService],
multi: false
}
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
```
import { DefaultApi } from 'petstore-integration-test';
export class AppComponent {
constructor(private apiGateway: DefaultApi) { }
}
```
Note: The ApiModule is restricted to being instantiated once app wide.
This is to ensure that all services are treated as singletons.
#### Using multiple OpenAPI files / APIs / ApiModules
In order to use multiple `ApiModules` generated from different OpenAPI files,
you can create an alias name when importing the modules
in order to avoid naming conflicts:
```
import { ApiModule } from 'my-api-path';
import { ApiModule as OtherApiModule } from 'my-other-api-path';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
ApiModule,
OtherApiModule,
// make sure to import the HttpClientModule in the AppModule only,
// see https://github.com/angular/angular/issues/20575
HttpClientModule
]
})
export class AppModule {
}
```
TODO: paste example.
### Set service base path
If different than the generated base path, during app bootstrap, you can provide the base path to your service.
```
import { BASE_PATH } from './path-to-swagger-gen-service/index';
import { BASE_PATH } from 'petstore-integration-test';
bootstrap(AppComponent, [
{ provide: BASE_PATH, useValue: 'https://your-web-service.com' },
]);
```
or
```
import { BASE_PATH } from 'petstore-integration-test';
@NgModule({
imports: [],
declarations: [ AppComponent ],
providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
#### Using @angular/cli
First extend your `src/environments/*.ts` files by adding the corresponding base path:
```
export const environment = {
production: false,
API_BASE_PATH: 'http://127.0.0.1:8080'
};
```
In the src/app/app.module.ts:
```
import { BASE_PATH } from 'petstore-integration-test';
import { environment } from '../environments/environment';
@NgModule({
declarations: [
AppComponent
],
imports: [ ],
providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }],
bootstrap: [ AppComponent ]
})
export class AppModule { }
```
### Customizing path parameter encoding
Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple'
and Dates for format 'date-time' are encoded correctly.
Other styles (e.g. "matrix") are not that easy to encode
and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]).
To implement your own parameter encoding (or call another library),
pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object
(see [General Usage](#general-usage) above).
Example value for use in your Configuration-Provider:
```typescript
new Configuration({
encodeParam: (param: Param) => myFancyParamEncoder(param),
})
```
[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations
[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values
[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander

View File

@ -1,23 +1,33 @@
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core';
import { Configuration } from './configuration';
import { HttpClient } from '@angular/common/http';
import { PetService } from './api/pet.service';
import { StoreService } from './api/store.service';
import { UserService } from './api/user.service';
@NgModule({
imports: [ CommonModule, HttpModule ],
imports: [],
declarations: [],
exports: [],
providers: [ PetService, StoreService, UserService ]
providers: []
})
export class ApiModule {
public static forConfig(configuration: Configuration): ModuleWithProviders {
public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders<ApiModule> {
return {
ngModule: ApiModule,
providers: [ {provide: Configuration, useValue: configuration}]
providers: [ { provide: Configuration, useFactory: configurationFactory } ]
};
}
constructor( @Optional() @SkipSelf() parentModule: ApiModule,
@Optional() http: HttpClient) {
if (parentModule) {
throw new Error('ApiModule is already loaded. Import in your base AppModule only.');
}
if (!http) {
throw new Error('You need to import the HttpClientModule in your AppModule! \n' +
'See also https://github.com/angular/angular/issues/20575');
}
}
}

Some files were not shown because too many files have changed in this diff Show More