diff --git a/src/client/interfaces/Model.d.ts b/src/client/interfaces/Model.d.ts index 093d7d62..60eb6744 100644 --- a/src/client/interfaces/Model.d.ts +++ b/src/client/interfaces/Model.d.ts @@ -1,14 +1,5 @@ -import { ModelProperty } from './ModelProperty'; -import { ModelEnum } from './ModelEnum'; +import { Schema } from './Schema'; -export interface Model { - name: string; - base: string; - type: string; - template: string | null; - description?: string; - extends: string[]; - imports: string[]; - properties: ModelProperty[]; - enums: ModelEnum[]; +export interface Model extends Schema { + noop?: any; } diff --git a/src/client/interfaces/Schema.d.ts b/src/client/interfaces/Schema.d.ts index edd7cf80..c52b4470 100644 --- a/src/client/interfaces/Schema.d.ts +++ b/src/client/interfaces/Schema.d.ts @@ -1,4 +1,4 @@ -import { Dictionary } from '../../utils/types'; +import { SchemaProperty } from './SchemaProperty'; export interface Schema { type: string; @@ -11,5 +11,5 @@ export interface Schema { readOnly: boolean; extends: string[]; imports: string[]; - properties: Dictionary; + properties: Map; } diff --git a/src/client/interfaces/SchemaProperty.d.ts b/src/client/interfaces/SchemaProperty.d.ts new file mode 100644 index 00000000..e703d479 --- /dev/null +++ b/src/client/interfaces/SchemaProperty.d.ts @@ -0,0 +1,13 @@ +export interface SchemaProperty { + name: string; + type: string; + base: string; + template: string | null; + description?: string; + required: boolean; + nullable: boolean; + readOnly: boolean; + extends: string[]; + imports: string[]; + properties: Map; +} diff --git a/src/client/interfaces/SchemaReference.d.ts b/src/client/interfaces/SchemaReference.d.ts new file mode 100644 index 00000000..3b184c20 --- /dev/null +++ b/src/client/interfaces/SchemaReference.d.ts @@ -0,0 +1,6 @@ +export interface SchemaReference { + type: string; + base: string; + template: string | null; + imports: string[]; +} diff --git a/src/index.ts b/src/index.ts index 35cee087..c550fd7d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -32,12 +32,12 @@ export function generate(input: string, output: string, language: Language = Lan const inputPath: string = path.resolve(process.cwd(), input); const outputPath: string = path.resolve(process.cwd(), output); - // console.log(chalk.bold.green('Generate:')); - // console.log(chalk.grey(' Input:'), input); - // console.log(chalk.grey(' Output:'), output); - // console.log(chalk.grey(' Language:'), language); - // console.log(chalk.grey(' HTTP client:'), httpClient); - // console.log(os.EOL); + console.log(chalk.bold.green('Generate:')); + console.log(chalk.grey(' Input:'), input); + console.log(chalk.grey(' Output:'), output); + console.log(chalk.grey(' Language:'), language); + console.log(chalk.grey(' HTTP client:'), httpClient); + console.log(os.EOL); try { // Load the specification, read the OpenAPI version and load the diff --git a/src/openApi/v2/parser/getArrayType.ts b/src/openApi/v2/parser/getArrayType.ts index e3bcab8d..d0e9b1e2 100644 --- a/src/openApi/v2/parser/getArrayType.ts +++ b/src/openApi/v2/parser/getArrayType.ts @@ -15,22 +15,20 @@ export function getArrayType(items: OpenApiItems): ArrayType { // If the parameter has a type than it can be a basic or generic type. if (items.type) { - const itemsData: Type = getType(items.type); - result.type = itemsData.type; - result.base = itemsData.base; - result.template = itemsData.template; - result.imports.push(...itemsData.imports); + const itemsType: Type = getType(items.type); + result.type = itemsType.type; + result.base = itemsType.base; + result.template = itemsType.template; + result.imports.push(...itemsType.imports); // If the parameter is an Array type, we check for the child type, // so we can create a typed array, otherwise this will be a "any[]". if (items.type === 'array' && items.items) { - console.log('templated array', items.items); - // Parse the child types and create a correct Array type, for example "string[]" or "ActivityData[]" - // const child: ParsedProperty = parseProperty(parameter.items, template); - // parameterType = `${child.type}[]`; - // parameterBase = child.base; - // parameterTemplate = child.template; - // parameterImports.push(...child.imports); + const arrayType: ArrayType = getArrayType(items.items); + result.type = `${arrayType.type}[]`; + result.base = arrayType.base; + result.template = arrayType.template; + result.imports.push(...arrayType.imports); } } diff --git a/src/openApi/v2/parser/getEnumType.ts b/src/openApi/v2/parser/getEnumType.ts index bdad0698..e1690c5b 100644 --- a/src/openApi/v2/parser/getEnumType.ts +++ b/src/openApi/v2/parser/getEnumType.ts @@ -4,7 +4,9 @@ export function getEnumType(values?: string[], addParentheses = false): string { // Plus make sure we put quotes around strings! const entries: string[] = values .filter(name => name) - .filter((name, index, arr) => arr.indexOf(name) === index) + .filter((name: string, index: number, arr: string[]) => { + return arr.indexOf(name) === index; + }) .map(value => `'${String(value)}'`); // Add grouping parentheses if needed. This can be handy if enum values diff --git a/src/openApi/v2/parser/getEnumTypeFromDescription.ts b/src/openApi/v2/parser/getEnumTypeFromDescription.ts index d1054b82..aa2ebc10 100644 --- a/src/openApi/v2/parser/getEnumTypeFromDescription.ts +++ b/src/openApi/v2/parser/getEnumTypeFromDescription.ts @@ -6,7 +6,7 @@ export function getEnumTypeFromDescription(description: string, addParentheses: if (matches) { // Grab the values from the description const values: number[] = []; - matches.forEach(match => { + matches.forEach((match: string): void => { const value = parseInt(match.split('=')[1].replace(/[^0-9]/g, '')); if (Number.isInteger(value)) { values.push(value); @@ -16,7 +16,9 @@ export function getEnumTypeFromDescription(description: string, addParentheses: // Filter and sort the values const entries: string[] = values .sort() - .filter((name, index, arr) => arr.indexOf(name) === index) + .filter((name: number, index: number, arr: number[]) => { + return arr.indexOf(name) === index; + }) .map(value => String(value)); // Add grouping parentheses if needed. This can be handy if enum values diff --git a/src/openApi/v2/parser/getModelProperty.ts b/src/openApi/v2/parser/getModelProperty.ts deleted file mode 100644 index 18166dfc..00000000 --- a/src/openApi/v2/parser/getModelProperty.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { ModelProperty } from '../../../client/interfaces/ModelProperty'; -import { OpenApiSchema } from '../interfaces/OpenApiSchema'; -import { OpenApiReference } from '../interfaces/OpenApiReference'; -import { getType } from './getType'; - -export function getModelProperty(name: string, schema: OpenApiSchema & OpenApiReference): ModelProperty { - /** - $ref?: string; - format?: 'int32' | 'int64' | 'float' | 'double' | 'string' | 'boolean' | 'byte' | 'binary' | 'date' | 'date-time' | 'password'; - title?: string; - description?: string; - default?: any; - multipleOf?: number; - maximum?: number; - exclusiveMaximum?: boolean; - minimum?: number; - exclusiveMinimum?: boolean; - maxLength?: number; - minLength?: number; - pattern?: string; - maxItems?: number; - minItems?: number; - uniqueItems?: number; - maxProperties?: number; - minProperties?: number; - required?: string[]; - enum?: string[] | number[]; - type?: string; - items?: OpenApiReference | OpenApiSchema; - allOf?: OpenApiReference[] | OpenApiSchema[]; - properties?: Dictionary; - additionalProperties?: boolean | OpenApiReference | OpenApiSchema; - discriminator?: string; - readOnly?: boolean; - xml?: OpenApiXml; - externalDocs?: OpenApiExternalDocs; - example?: any; - */ - - const prop: ModelProperty = { - name: name, - type: '', - base: '', - template: '', - description: schema.description, - default: schema.default, - required: false, - nullable: false, - readOnly: schema.readOnly || false, - imports: [], - extends: [], - properties: [], - }; - - if (schema.$ref) { - // console.log('parse $ref?'); - } - - if (schema.properties || schema.type === 'object') { - prop.type = 'interface'; - // type is interface!? - } - - if (schema.enum) { - prop.type = 'enum'; - // type is enum! - } - - // console.log('propertyName:', schema); - // console.log('format:', schema.format); - // console.log('type:', schema.type); - - const properties = schema.properties; - for (const propertyName in properties) { - if (properties.hasOwnProperty(propertyName)) { - const property = properties[propertyName]; - /// console.log('propertyName', propertyName); - // getModelProperty(propertyName, property); - } - } - - if (schema.allOf) { - schema.allOf.forEach(parent => { - if (parent.$ref) { - const extend = getType(parent.$ref); - prop.extends.push(extend.type); - prop.imports.push(extend.base); - } - if (parent.properties) { - // console.log(parent.properties); - // const properties: ParsedModelProperties = parseModelProperties(modelClass, definition.allOf[1].properties as SwaggerDefinitions, required); - // model.imports.push(...properties.imports); - // model.properties.push(...properties.properties); - // model.enums.push(...properties.enums); - } - }); - } - - return prop; -} diff --git a/src/openApi/v2/parser/getModels.ts b/src/openApi/v2/parser/getModels.ts index 38683211..1c319752 100644 --- a/src/openApi/v2/parser/getModels.ts +++ b/src/openApi/v2/parser/getModels.ts @@ -1,5 +1,11 @@ import { Model } from '../../../client/interfaces/Model'; import { OpenApi } from '../interfaces/OpenApi'; +import { OpenApiSchema } from '../interfaces/OpenApiSchema'; +import { getSchema } from './getSchema'; +import { Schema } from '../../../client/interfaces/Schema'; +import { Type } from '../../../client/interfaces/Type'; +import { getType } from '../../v3/parser/getType'; +import { getModelTemplate } from './getModelTemplate'; /** * Get the OpenAPI models. @@ -8,38 +14,22 @@ export function getModels(openApi: OpenApi): Map { const models: Map = new Map(); // Iterate over the definitions - const { definitions } = openApi; - for (const definitionName in definitions) { - if (definitions.hasOwnProperty(definitionName)) { - // const definition: OpenApiSchema = openApi.definitions[definitionName]; - // const required: string[] = definition.required || []; - // const modelClass: Type = getType(definitionName); - // Check if we haven't already parsed the model - // if (!models.has(modelClass.base)) { - // // Create a new model object - // const model: Model = { - // name: modelClass.base, - // base: modelClass.base, - // type: modelClass.type, - // template: getModelTemplate(modelClass), - // description: null, - // extends: [], - // imports: [], - // properties: [], - // enums: [], - // }; - // - // const properties = definition.properties; - // for (const propertyName in properties) { - // if (properties.hasOwnProperty(propertyName)) { - // const property = properties[propertyName]; - // const propertyRequired = required.includes(propertyName); - // getModelProperty(propertyName, property); - // } - // } - // - // models.set(modelClass.base, model); - // } + for (const definitionName in openApi.definitions) { + if (openApi.definitions.hasOwnProperty(definitionName)) { + const definition: OpenApiSchema = openApi.definitions[definitionName]; + const definitionSchema: Schema = getSchema(openApi, definition); + const modelClass: Type = getType(definitionName); + const modelTemplate: string = getModelTemplate(modelClass); + + if (models.has(modelClass.base)) { + continue; + } + + definitionSchema.base = modelClass.base; + definitionSchema.type = modelClass.type; + definitionSchema.template = modelTemplate; + + models.set(modelClass.base, definitionSchema); } } diff --git a/src/openApi/v2/parser/getOperationErrors.ts b/src/openApi/v2/parser/getOperationErrors.ts index 94f24c65..51906e28 100644 --- a/src/openApi/v2/parser/getOperationErrors.ts +++ b/src/openApi/v2/parser/getOperationErrors.ts @@ -3,9 +3,13 @@ import { OperationError } from '../../../client/interfaces/OperationError'; export function getOperationErrors(responses: OperationResponse[]): OperationError[] { return responses - .filter((response: OperationResponse): boolean => response.code >= 300 && response.text !== undefined && response.text !== '') - .map(response => ({ - code: response.code, - text: response.text, - })); + .filter((response: OperationResponse): boolean => { + return response.code >= 300 && response.text !== undefined && response.text !== ''; + }) + .map( + (response: OperationResponse): OperationError => ({ + code: response.code, + text: response.text, + }) + ); } diff --git a/src/openApi/v2/parser/getOperationParameters.ts b/src/openApi/v2/parser/getOperationParameters.ts index ed6bb97b..a5140619 100644 --- a/src/openApi/v2/parser/getOperationParameters.ts +++ b/src/openApi/v2/parser/getOperationParameters.ts @@ -10,7 +10,7 @@ function sortByRequired(a: Parameter, b: Parameter): number { return a.required && !b.required ? -1 : !a.required && b.required ? 1 : 0; } -export function getOperationParameters(openApi: OpenApi, parametersOrReferences: (OpenApiParameter & OpenApiReference)[]): OperationParameters { +export function getOperationParameters(openApi: OpenApi, parameters: (OpenApiParameter & OpenApiReference)[]): OperationParameters { const result: OperationParameters = { imports: [], parameters: [], @@ -22,9 +22,9 @@ export function getOperationParameters(openApi: OpenApi, parametersOrReferences: }; // Iterate over the parameters - parametersOrReferences.forEach(parameterOrReference => { - const parameter: OpenApiParameter = getRef(openApi, parameterOrReference); - const param: Parameter = getParameter(openApi, parameter); + parameters.forEach(parameter => { + const paramRef: OpenApiParameter = getRef(openApi, parameter); + const param: Parameter = getParameter(openApi, paramRef); // We ignore the "api-version" param, since we do not want to add this // as the first / default parameter for each of the service calls. diff --git a/src/openApi/v2/parser/getOperationResponse.ts b/src/openApi/v2/parser/getOperationResponse.ts index 89a3f34f..76941090 100644 --- a/src/openApi/v2/parser/getOperationResponse.ts +++ b/src/openApi/v2/parser/getOperationResponse.ts @@ -12,7 +12,6 @@ export function getOperationResponse(responses: OperationResponse[]): OperationR // Fetch the first valid (2XX range) response code and return that type. const result: OperationResponse | undefined = responses.find(response => response.code && response.code >= 200 && response.code < 300); - if (result) { response.code = result.code; response.text = result.text; diff --git a/src/openApi/v2/parser/getOperationResponses.ts b/src/openApi/v2/parser/getOperationResponses.ts index 5c7b9c7e..140ef2d2 100644 --- a/src/openApi/v2/parser/getOperationResponses.ts +++ b/src/openApi/v2/parser/getOperationResponses.ts @@ -5,11 +5,8 @@ import { OpenApiResponse } from '../interfaces/OpenApiResponse'; import { OpenApiReference } from '../interfaces/OpenApiReference'; import { getRef } from './getRef'; import { OpenApi } from '../interfaces/OpenApi'; -import { getType } from './getType'; -import { Type } from '../../../client/interfaces/Type'; -import { Schema } from '../../../client/interfaces/Schema'; -import { getSchema } from './getSchema'; -import { OpenApiSchema } from '../interfaces/OpenApiSchema'; +import { getSchemaReference } from './getSchemaReference'; +import { SchemaReference } from '../../../client/interfaces/SchemaReference'; export function getOperationResponses(openApi: OpenApi, responses: OpenApiResponses): OperationResponse[] { const results: OperationResponse[] = []; @@ -21,6 +18,10 @@ export function getOperationResponses(openApi: OpenApi, responses: OpenApiRespon const responseOrReference: OpenApiResponse & OpenApiReference = responses[code]; const response: OpenApiResponse = getRef(openApi, responseOrReference); const responseCode: number | null = getOperationResponseCode(code); + + // If there is a response code then we check what data we get back, + // if there is no typed data, we just return so the user is still + // free to do their own casting if needed. if (responseCode) { const result: OperationResponse = { code: responseCode, @@ -31,20 +32,16 @@ export function getOperationResponses(openApi: OpenApi, responses: OpenApiRespon imports: [], }; + // If this response has a schema, then we need to check two things: + // if this is a reference then the parameter is just the 'name' of + // this reference type. Otherwise it might be a complex schema and + // then we need to parse the schema! if (response.schema) { - if (response.schema.$ref) { - const schemaReference: Type = getType(response.schema.$ref); - result.type = schemaReference.type; - result.base = schemaReference.base; - result.template = schemaReference.template; - result.imports.push(...schemaReference.imports); - } else { - const schema: Schema = getSchema(openApi, response.schema as OpenApiSchema); - result.type = schema.type; - result.base = schema.base; - result.template = schema.template; - result.imports.push(...schema.imports); - } + const responseSchema: SchemaReference = getSchemaReference(openApi, response.schema); + result.type = responseSchema.type; + result.base = responseSchema.base; + result.template = responseSchema.template; + result.imports.push(...responseSchema.imports); } results.push(result); diff --git a/src/openApi/v2/parser/getParameter.ts b/src/openApi/v2/parser/getParameter.ts index faa4714f..a373b7e2 100644 --- a/src/openApi/v2/parser/getParameter.ts +++ b/src/openApi/v2/parser/getParameter.ts @@ -9,9 +9,8 @@ import { ArrayType } from '../../../client/interfaces/ArrayType'; import { getEnumType } from './getEnumType'; import { getEnumTypeFromDescription } from './getEnumTypeFromDescription'; import { getComment } from './getComment'; -import { getSchema } from './getSchema'; -import { Schema } from '../../../client/interfaces/Schema'; -import { OpenApiSchema } from '../interfaces/OpenApiSchema'; +import { SchemaReference } from '../../../client/interfaces/SchemaReference'; +import { getSchemaReference } from './getSchemaReference'; export function getParameter(openApi: OpenApi, parameter: OpenApiParameter): Parameter { const result: Parameter = { @@ -30,11 +29,11 @@ export function getParameter(openApi: OpenApi, parameter: OpenApiParameter): Par // If the parameter has a type than it can be a basic or generic type. if (parameter.type) { - const parameterData: Type = getType(parameter.type); - result.type = parameterData.type; - result.base = parameterData.base; - result.template = parameterData.template; - result.imports.push(...parameterData.imports); + const parameterType: Type = getType(parameter.type); + result.type = parameterType.type; + result.base = parameterType.base; + result.template = parameterType.template; + result.imports.push(...parameterType.imports); // If the parameter is an Array type, we check for the child type, // so we can create a typed array, otherwise this will be a "any[]". @@ -52,19 +51,11 @@ export function getParameter(openApi: OpenApi, parameter: OpenApiParameter): Par // this reference type. Otherwise it might be a complex schema and // then we need to parse the schema! if (parameter.schema) { - if (parameter.schema.$ref) { - const schemaReference: Type = getType(parameter.schema.$ref); - result.type = schemaReference.type; - result.base = schemaReference.base; - result.template = schemaReference.template; - result.imports.push(...schemaReference.imports); - } else { - const schema: Schema = getSchema(openApi, parameter.schema as OpenApiSchema); - result.type = schema.type; - result.base = schema.base; - result.template = schema.template; - result.imports.push(...schema.imports); - } + const parameterSchema: SchemaReference = getSchemaReference(openApi, parameter.schema); + result.type = parameterSchema.type; + result.base = parameterSchema.base; + result.template = parameterSchema.template; + result.imports.push(...parameterSchema.imports); } // If the param is a enum then return the values as an inline type. diff --git a/src/openApi/v2/parser/getRef.ts b/src/openApi/v2/parser/getRef.ts index acb67124..fa624691 100644 --- a/src/openApi/v2/parser/getRef.ts +++ b/src/openApi/v2/parser/getRef.ts @@ -13,7 +13,7 @@ export function getRef(openApi: OpenApi, item: T & OpenApiReference): T { // Try to find the reference by walking down the path, // if we cannot find it, then we throw an error. let result: any = openApi; - paths.forEach(path => { + paths.forEach((path: string): void => { if (result.hasOwnProperty(path)) { result = result[path]; } else { diff --git a/src/openApi/v2/parser/getSchema.ts b/src/openApi/v2/parser/getSchema.ts index 21b04e90..4317c2c8 100644 --- a/src/openApi/v2/parser/getSchema.ts +++ b/src/openApi/v2/parser/getSchema.ts @@ -6,76 +6,46 @@ import { getComment } from './getComment'; import { Type } from '../../../client/interfaces/Type'; import { getEnumType } from './getEnumType'; import { getEnumTypeFromDescription } from './getEnumTypeFromDescription'; -import { Dictionary } from '../../../utils/types'; import { OpenApiReference } from '../interfaces/OpenApiReference'; -import { getRef } from './getRef'; +import { SchemaReference } from '../../../client/interfaces/SchemaReference'; +import { getSchemaReference } from './getSchemaReference'; +import { SchemaProperty } from '../../../client/interfaces/SchemaProperty'; +import { getSchemaProperty } from './getSchemaProperty'; -export function getSchema(openApi: OpenApi, schema: OpenApiSchema, required: boolean = false): Schema { - /** - format?: 'int32' | 'int64' | 'float' | 'double' | 'string' | 'boolean' | 'byte' | 'binary' | 'date' | 'date-time' | 'password'; - title?: string; - description?: string; - default?: any; - multipleOf?: number; - maximum?: number; - exclusiveMaximum?: boolean; - minimum?: number; - exclusiveMinimum?: boolean; - maxLength?: number; - minLength?: number; - pattern?: string; - maxItems?: number; - minItems?: number; - uniqueItems?: number; - maxProperties?: number; - minProperties?: number; - required?: string[]; - enum?: string[]; - type?: string; - items?: OpenApiSchema & OpenApiReference; - allOf?: (OpenApiSchema & OpenApiReference)[]; - properties?: Dictionary; - additionalProperties?: boolean | (OpenApiSchema & OpenApiReference); - discriminator?: string; - readOnly?: boolean; - xml?: OpenApiXml; - externalDocs?: OpenApiExternalDocs; - example?: any; - */ - - // TODO: Does this need a name? +// TODO: I think we can convert this into getModel and getModelProperties +// but we need to think about what will happen when a simple type is used as a model +// needs a test case +export function getSchema(openApi: OpenApi, schema: OpenApiSchema): Schema { const result: Schema = { type: 'any', base: 'any', template: null, description: getComment(schema.description), - default: schema.default, - required: required, - nullable: false, - readOnly: schema.readOnly || false, + default: schema.default, // TODO: Unused? + required: false, // TODO: Unused? + nullable: false, // TODO: Unused? + readOnly: schema.readOnly || false, // TODO: Unused? extends: [], imports: [], - properties: {}, + properties: new Map(), }; // If the schema has a type than it can be a basic or generic type. if (schema.type) { - const schemaData: Type = getType(schema.type); - result.type = schemaData.type; - result.base = schemaData.base; - result.template = schemaData.template; - result.imports.push(...schemaData.imports); + const schemaType: Type = getType(schema.type); + result.type = schemaType.type; + result.base = schemaType.base; + result.template = schemaType.template; + result.imports.push(...schemaType.imports); // If the schema is an Array type, we check for the child type, // so we can create a typed array, otherwise this will be a "any[]". if (schema.type === 'array' && schema.items) { - const itemsOrReference: OpenApiSchema & OpenApiReference = schema.items; - const items: OpenApiSchema = getRef(openApi, itemsOrReference); - const itemsSchema: Schema = getSchema(openApi, items); - result.type = `${itemsSchema.type}[]`; - result.base = itemsSchema.base; - result.template = itemsSchema.template; - result.imports.push(...itemsSchema.imports); + const arrayType: SchemaReference = getSchemaReference(openApi, schema.items); + result.type = `${arrayType.type}[]`; + result.base = arrayType.base; + result.template = arrayType.template; + result.imports.push(...arrayType.imports); } } @@ -98,41 +68,33 @@ export function getSchema(openApi: OpenApi, schema: OpenApiSchema, required: boo // Check if this model extends other models if (schema.allOf) { - schema.allOf.forEach(parent => { - if (parent.$ref) { - const extend: Type = getType(parent.$ref); - result.extends.push(extend.type); - result.imports.push(extend.base); - } + schema.allOf.forEach((parent: OpenApiSchema & OpenApiReference): void => { + const parentSchema: SchemaReference = getSchemaReference(openApi, parent); + result.extends.push(parentSchema.type); + result.imports.push(parentSchema.base); // Merge properties of other models if (parent.properties) { - const properties: Dictionary | undefined = schema.properties; - for (const propertyName in properties) { - if (properties.hasOwnProperty(propertyName)) { - const propertyOrReference: OpenApiSchema & OpenApiReference = properties[propertyName]; - const property: OpenApiSchema = getRef(openApi, propertyOrReference); - const propertySchema: Schema = getSchema(openApi, property); - console.log('propertyName 2', propertyName, propertySchema); - // model.imports.push(...properties.imports); - // model.properties.push(...properties.properties); - // model.enums.push(...properties.enums); + for (const propertyName in schema.properties) { + if (schema.properties.hasOwnProperty(propertyName)) { + const propertyRef: OpenApiSchema & OpenApiReference = schema.properties[propertyName]; + const propertyRequired: boolean = (schema.required && schema.required.includes(propertyName)) || false; + const property: SchemaProperty = getSchemaProperty(openApi, propertyRef, propertyName, propertyRequired); + result.imports.push(...property.imports); + result.properties.set(propertyName, property); } } } }); } - const properties: Dictionary | undefined = schema.properties; - for (const propertyName in properties) { - if (properties.hasOwnProperty(propertyName)) { - const propertyOrReference: OpenApiSchema & OpenApiReference = properties[propertyName]; - const property: OpenApiSchema = getRef(openApi, propertyOrReference); - const propertySchema: Schema = getSchema(openApi, property); - console.log('propertyName 1', propertyName, propertySchema); - // console.log('property??', property); - // console.log('propertyName', propertyName); - // getModelProperty(propertyName, property); + for (const propertyName in schema.properties) { + if (schema.properties.hasOwnProperty(propertyName)) { + const propertyRef: OpenApiSchema & OpenApiReference = schema.properties[propertyName]; + const propertyRequired: boolean = (schema.required && schema.required.includes(propertyName)) || false; + const property: SchemaProperty = getSchemaProperty(openApi, propertyRef, propertyName, propertyRequired); + result.imports.push(...property.imports); + result.properties.set(propertyName, property); } } diff --git a/src/openApi/v2/parser/getSchemaProperty.ts b/src/openApi/v2/parser/getSchemaProperty.ts new file mode 100644 index 00000000..557788aa --- /dev/null +++ b/src/openApi/v2/parser/getSchemaProperty.ts @@ -0,0 +1,30 @@ +import { OpenApiSchema } from '../interfaces/OpenApiSchema'; +import { OpenApiReference } from '../interfaces/OpenApiReference'; +import { OpenApi } from '../interfaces/OpenApi'; +import { SchemaProperty } from '../../../client/interfaces/SchemaProperty'; +import { getComment } from './getComment'; + +export function getSchemaProperty(openApi: OpenApi, property: OpenApiSchema & OpenApiReference, name: string, required: boolean): SchemaProperty { + const result: SchemaProperty = { + name: name, + type: 'any', + base: 'any', + template: null, + description: getComment(property.description), + required: required, + nullable: false, + readOnly: property.readOnly || false, + extends: [], + imports: [], + properties: new Map(), + }; + + // console.log(name, property); + + // const property: OpenApiSchema & OpenApiReference = schema.properties[propertyName]; + // const propertySchema: SchemaReference = getSchemaReference(openApi, property); + // result.imports.push(...propertySchema.imports); + // result.properties.set(propertyName, propertySchema); + + return result; +} diff --git a/src/openApi/v2/parser/getSchemaReference.ts b/src/openApi/v2/parser/getSchemaReference.ts new file mode 100644 index 00000000..4c166a69 --- /dev/null +++ b/src/openApi/v2/parser/getSchemaReference.ts @@ -0,0 +1,35 @@ +import { getType } from './getType'; +import { Type } from '../../../client/interfaces/Type'; +import { OpenApiSchema } from '../interfaces/OpenApiSchema'; +import { OpenApiReference } from '../interfaces/OpenApiReference'; +import { getRef } from './getRef'; +import { Schema } from '../../../client/interfaces/Schema'; +import { getSchema } from './getSchema'; +import { SchemaReference } from '../../../client/interfaces/SchemaReference'; +import { OpenApi } from '../interfaces/OpenApi'; + +export function getSchemaReference(openApi: OpenApi, schema: OpenApiSchema & OpenApiReference): SchemaReference { + const result: SchemaReference = { + type: 'any', + base: 'any', + template: null, + imports: [], + }; + + if (schema.$ref) { + const itemSchemaType: Type = getType(schema.$ref); + result.type = itemSchemaType.type; + result.base = itemSchemaType.base; + result.template = itemSchemaType.template; + result.imports.push(...itemSchemaType.imports); + } else { + const item: OpenApiSchema = getRef(openApi, schema); + const itemSchema: Schema = getSchema(openApi, item); + result.type = itemSchema.type; + result.base = itemSchema.base; + result.template = itemSchema.template; + result.imports.push(...itemSchema.imports); + } + + return result; +} diff --git a/src/openApi/v2/parser/getServiceVersion.ts b/src/openApi/v2/parser/getServiceVersion.ts index 9986f1af..34777afc 100644 --- a/src/openApi/v2/parser/getServiceVersion.ts +++ b/src/openApi/v2/parser/getServiceVersion.ts @@ -3,6 +3,6 @@ * This basically removes any "v" prefix from the version string. * @param version */ -export function getServiceVersion(version = '1.0'): string { +export function getServiceVersion(version: string = '1.0'): string { return version.replace(/^v/gi, ''); } diff --git a/src/openApi/v2/parser/getServices.ts b/src/openApi/v2/parser/getServices.ts index a7fb28ae..16ee8ac3 100644 --- a/src/openApi/v2/parser/getServices.ts +++ b/src/openApi/v2/parser/getServices.ts @@ -11,10 +11,9 @@ import { Operation } from '../../../client/interfaces/Operation'; export function getServices(openApi: OpenApi): Map { const services: Map = new Map(); - const { paths } = openApi; - for (const url in paths) { - if (paths.hasOwnProperty(url)) { - const path: OpenApiPath = paths[url]; + for (const url in openApi.paths) { + if (openApi.paths.hasOwnProperty(url)) { + const path: OpenApiPath = openApi.paths[url]; for (const method in path) { if (path.hasOwnProperty(method)) { // Check supported methods diff --git a/src/openApi/v2/parser/getType.ts b/src/openApi/v2/parser/getType.ts index 62a663fb..53e12c75 100644 --- a/src/openApi/v2/parser/getType.ts +++ b/src/openApi/v2/parser/getType.ts @@ -21,7 +21,7 @@ export function getType(value: string | undefined, template: string | null = nul // Check of we have an Array type or generic type, for instance: "Link[Model]". if (/\[.*\]$/g.test(valueClean)) { const matches: RegExpMatchArray | null = valueClean.match(/(.*?)\[(.*)\]$/); - if (matches) { + if (matches && matches.length) { // Both of the types can be complex types so parse each of them. const match1: Type = getType(matches[1]); const match2: Type = getType(matches[2]); diff --git a/src/templates/javascript/service.hbs b/src/templates/javascript/service.hbs index f702af53..ef5197a6 100644 --- a/src/templates/javascript/service.hbs +++ b/src/templates/javascript/service.hbs @@ -30,8 +30,9 @@ export class {{{name}}} { {{#if parameters}} {{#each parameters}} - yup.schema.validate(); + {{#if required}} isValidRequiredParam({{{name}}}, '{{{name}}}'); + {{/if}} {{/each}} {{/if}} diff --git a/src/templates/typescript/model.hbs b/src/templates/typescript/model.hbs index 58d7aa79..10fcbd3b 100644 --- a/src/templates/typescript/model.hbs +++ b/src/templates/typescript/model.hbs @@ -16,6 +16,7 @@ import * as yup from 'yup'; * {{{description}}} */ {{/if}} +{{#if properties}} export interface {{{base}}}{{{template}}}{{#if extend}} extends {{{extend}}}{{/if}} { {{#each properties}} {{#if description}} @@ -27,6 +28,7 @@ export interface {{{base}}}{{{template}}}{{#if extend}} extends {{{extend}}}{{/i {{/each}} } +{{/if}} export namespace {{{base}}} { {{#each enums}} diff --git a/src/templates/typescript/service.hbs b/src/templates/typescript/service.hbs index 4a232f92..cafd7338 100644 --- a/src/templates/typescript/service.hbs +++ b/src/templates/typescript/service.hbs @@ -38,7 +38,9 @@ export class {{{name}}} { {{#if parameters}} {{#each parameters}} + {{#if required}} isValidRequiredParam({{{name}}}, '{{{name}}}'); + {{/if}} {{/each}} {{/if}} diff --git a/src/utils/cleanupServices.ts b/src/utils/cleanupServices.ts new file mode 100644 index 00000000..35008246 --- /dev/null +++ b/src/utils/cleanupServices.ts @@ -0,0 +1,31 @@ +import { Service } from '../client/interfaces/Service'; +import { getSortedImports } from './getSortedImports'; +import { Operation } from '../client/interfaces/Operation'; + +export function cleanupServices(services: Map): Map { + services.forEach((service: Service): void => { + const names: Map = new Map(); + + service.imports = getSortedImports(service.imports); + + // Append postfix number to duplicate operation names and sort them. + service.operations = service.operations + .map( + (operation: Operation): Operation => { + const name: string = operation.name; + const index: number = names.get(name) || 0; + if (index > 0) { + operation.name = `${name}${index}`; + } + names.set(name, index + 1); + return operation; + } + ) + .sort((a: Operation, b: Operation): number => { + const nameA: string = a.name.toLowerCase(); + const nameB: string = b.name.toLowerCase(); + return nameA.localeCompare(nameB); + }); + }); + return services; +} diff --git a/src/utils/getSortedImports.ts b/src/utils/getSortedImports.ts index ba1a6cd9..b1236f4a 100644 --- a/src/utils/getSortedImports.ts +++ b/src/utils/getSortedImports.ts @@ -6,7 +6,9 @@ export function getSortedImports(imports: string[]): string[] { return imports .filter(name => name) .filter(name => name.trim()) - .filter((name, index, arr) => arr.indexOf(name) === index) + .filter((name: string, index: number, arr: string[]) => { + return arr.indexOf(name) === index; + }) .sort((a, b) => { const nameA: string = a.toLowerCase(); const nameB: string = b.toLowerCase(); diff --git a/src/utils/writeClient.ts b/src/utils/writeClient.ts index 1d8ec250..c07edc63 100644 --- a/src/utils/writeClient.ts +++ b/src/utils/writeClient.ts @@ -12,6 +12,7 @@ import { Language } from '../index'; import * as fs from 'fs'; import { getFileName } from './getFileName'; import * as glob from 'glob'; +import { cleanupServices } from './cleanupServices'; /** * Write our OpenAPI client, using the given templates at the given output path @@ -55,9 +56,10 @@ export function writeClient(client: Client, language: Language, templates: Templ // Write the client files try { + // TODO: Cleanup models writeClientIndex(client, language, templates.index, outputPath); writeClientModels(getSortedModels(client.models), language, templates.model, outputPathModels); - writeClientServices(getSortedServices(client.services), language, templates.service, outputPathServices); + writeClientServices(getSortedServices(cleanupServices(client.services)), language, templates.service, outputPathServices); } catch (e) { throw e; } diff --git a/src/utils/writeClientModels.ts b/src/utils/writeClientModels.ts index 3fe7cbea..d6ef7c3e 100644 --- a/src/utils/writeClientModels.ts +++ b/src/utils/writeClientModels.ts @@ -14,9 +14,15 @@ import { getFileName } from './getFileName'; */ export function writeClientModels(models: Model[], language: Language, template: handlebars.TemplateDelegate, outputPath: string): void { models.forEach(model => { - const fileName: string = getFileName(model.name, language); + const fileName: string = getFileName(model.base, language); try { - fs.writeFileSync(path.resolve(outputPath, fileName), template(model)); + fs.writeFileSync( + path.resolve(outputPath, fileName), + template({ + ...model, + properties: Array.from(model.properties.values()), // TODO in cleanup? + }) + ); } catch (e) { throw new Error(`Could not write model: "${fileName}"`); } diff --git a/test/generated-clients/typescript-angular/.gitignore b/test/generated-clients/typescript-angular/.gitignore new file mode 100644 index 00000000..149b5765 --- /dev/null +++ b/test/generated-clients/typescript-angular/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/test/generated-clients/typescript-angular/.swagger-codegen-ignore b/test/generated-clients/typescript-angular/.swagger-codegen-ignore new file mode 100644 index 00000000..c5fa491b --- /dev/null +++ b/test/generated-clients/typescript-angular/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# 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 Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/test/generated-clients/typescript-angular/.swagger-codegen/VERSION b/test/generated-clients/typescript-angular/.swagger-codegen/VERSION new file mode 100644 index 00000000..752a79ef --- /dev/null +++ b/test/generated-clients/typescript-angular/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.8 \ No newline at end of file diff --git a/test/generated-clients/typescript-angular/README.md b/test/generated-clients/typescript-angular/README.md new file mode 100644 index 00000000..9c7753a4 --- /dev/null +++ b/test/generated-clients/typescript-angular/README.md @@ -0,0 +1,178 @@ +## @ + +### Building + +To install the required dependencies and to build the typescript sources run: +``` +npm install +npm run build +``` + +### publishing + +First build the package than run ```npm publish``` + +### consuming + +Navigate to the folder of your consuming project and run one of next commands. + +_published:_ + +``` +npm install @ --save +``` + +_without publishing (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE --save +``` + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE: +``` +npm link +``` + +In your project: +``` +npm link +``` + +__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 ''; +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 ''; + +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 {} +``` + +``` +import { DefaultApi } from ''; + +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 swagger files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different swagger 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 ''; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from ''; + +@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 ''; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` \ No newline at end of file diff --git a/test/generated-clients/typescript-angular/api.module.ts b/test/generated-clients/typescript-angular/api.module.ts new file mode 100644 index 00000000..8487243a --- /dev/null +++ b/test/generated-clients/typescript-angular/api.module.ts @@ -0,0 +1,37 @@ +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: [], + declarations: [], + exports: [], + providers: [ + PetService, + StoreService, + UserService ] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } + } +} diff --git a/test/generated-clients/typescript-angular/api/api.ts b/test/generated-clients/typescript-angular/api/api.ts new file mode 100644 index 00000000..8e44b640 --- /dev/null +++ b/test/generated-clients/typescript-angular/api/api.ts @@ -0,0 +1,7 @@ +export * from './pet.service'; +import { PetService } from './pet.service'; +export * from './store.service'; +import { StoreService } from './store.service'; +export * from './user.service'; +import { UserService } from './user.service'; +export const APIS = [PetService, StoreService, UserService]; diff --git a/test/generated-clients/typescript-angular/api/pet.service.ts b/test/generated-clients/typescript-angular/api/pet.service.ts new file mode 100644 index 00000000..3ca8c526 --- /dev/null +++ b/test/generated-clients/typescript-angular/api/pet.service.ts @@ -0,0 +1,542 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * 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 } from '@angular/common/http'; +import { CustomHttpUrlEncodingCodec } from '../encoder'; + +import { Observable } from 'rxjs/Observable'; + +import { ApiResponse } from '../model/apiResponse'; +import { Pet } from '../model/pet'; + +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + +@Injectable() +export class PetService { + + protected basePath = 'https://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (basePath) { + this.basePath = basePath; + } + if (configuration) { + this.configuration = configuration; + this.basePath = basePath || configuration.basePath || this.basePath; + } + } + + /** + * @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; + } + + + /** + * Add a new pet to the store + * + * @param body Pet 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 addPet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling addPet.'); + } + + let headers = this.defaultHeaders; + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers = headers.set('Authorization', 'Bearer ' + accessToken); + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + return this.httpClient.post(`${this.basePath}/pet`, + body, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @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 deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + + let headers = this.defaultHeaders; + if (apiKey !== undefined && apiKey !== null) { + headers = headers.set('api_key', String(apiKey)); + } + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers = headers.set('Authorization', 'Bearer ' + accessToken); + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + + return this.httpClient.delete(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter + * @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 findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); + if (status) { + status.forEach((element) => { + queryParameters = queryParameters.append('status', element); + }) + } + + let headers = this.defaultHeaders; + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers = headers.set('Authorization', 'Bearer ' + accessToken); + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + + return this.httpClient.get>(`${this.basePath}/pet/findByStatus`, + { + params: queryParameters, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @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 findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); + if (tags) { + tags.forEach((element) => { + queryParameters = queryParameters.append('tags', element); + }) + } + + let headers = this.defaultHeaders; + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers = headers.set('Authorization', 'Bearer ' + accessToken); + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + + return this.httpClient.get>(`${this.basePath}/pet/findByTags`, + { + params: queryParameters, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @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 getPetById(petId: number, observe?: 'body', reportProgress?: boolean): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + let headers = this.defaultHeaders; + + // authentication (api_key) required + if (this.configuration.apiKeys["api_key"]) { + headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Update an existing pet + * + * @param body Pet 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 updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updatePet.'); + } + + let headers = this.defaultHeaders; + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers = headers.set('Authorization', 'Bearer ' + accessToken); + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + return this.httpClient.put(`${this.basePath}/pet`, + body, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @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 updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + + + let headers = this.defaultHeaders; + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers = headers.set('Authorization', 'Bearer ' + accessToken); + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): void; }; + let useForm = false; + let convertFormParamsToString = false; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); + } + + if (name !== undefined) { + formParams = formParams.append('name', name) || formParams; + } + if (status !== undefined) { + formParams = formParams.append('status', status) || formParams; + } + + return this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, + convertFormParamsToString ? formParams.toString() : formParams, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @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 uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + + + let headers = this.defaultHeaders; + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers = headers.set('Authorization', 'Bearer ' + accessToken); + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'multipart/form-data' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): void; }; + let useForm = false; + let convertFormParamsToString = 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 + useForm = canConsumeForm; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); + } + + if (additionalMetadata !== undefined) { + formParams = formParams.append('additionalMetadata', additionalMetadata) || formParams; + } + if (file !== undefined) { + formParams = formParams.append('file', file) || formParams; + } + + return this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, + convertFormParamsToString ? formParams.toString() : formParams, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/test/generated-clients/typescript-angular/api/store.service.ts b/test/generated-clients/typescript-angular/api/store.service.ts new file mode 100644 index 00000000..80cab0fb --- /dev/null +++ b/test/generated-clients/typescript-angular/api/store.service.ts @@ -0,0 +1,231 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * 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 } from '@angular/common/http'; +import { CustomHttpUrlEncodingCodec } from '../encoder'; + +import { Observable } from 'rxjs/Observable'; + +import { Order } from '../model/order'; + +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + +@Injectable() +export class StoreService { + + protected basePath = 'https://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (basePath) { + this.basePath = basePath; + } + if (configuration) { + this.configuration = configuration; + this.basePath = basePath || configuration.basePath || this.basePath; + } + } + + /** + * @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; + } + + + /** + * Delete purchase order by ID + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * @param orderId ID of the order that needs to be deleted + * @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 deleteOrder(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; + public deleteOrder(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; + public deleteOrder(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; + public deleteOrder(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + + return this.httpClient.delete(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @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 getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + + let headers = this.defaultHeaders; + + // authentication (api_key) required + if (this.configuration.apiKeys["api_key"]) { + headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + + return this.httpClient.get<{ [key: string]: number; }>(`${this.basePath}/store/inventory`, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @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 getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @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 placeOrder(body: Order, observe?: 'body', reportProgress?: boolean): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling placeOrder.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + return this.httpClient.post(`${this.basePath}/store/order`, + body, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/test/generated-clients/typescript-angular/api/user.service.ts b/test/generated-clients/typescript-angular/api/user.service.ts new file mode 100644 index 00000000..32be450f --- /dev/null +++ b/test/generated-clients/typescript-angular/api/user.service.ts @@ -0,0 +1,429 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * 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 } from '@angular/common/http'; +import { CustomHttpUrlEncodingCodec } from '../encoder'; + +import { Observable } from 'rxjs/Observable'; + +import { User } from '../model/user'; + +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + +@Injectable() +export class UserService { + + protected basePath = 'https://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (basePath) { + this.basePath = basePath; + } + if (configuration) { + this.configuration = configuration; + this.basePath = basePath || configuration.basePath || this.basePath; + } + } + + /** + * @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; + } + + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @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 createUser(body: User, observe?: 'body', reportProgress?: boolean): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUser.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + return this.httpClient.post(`${this.basePath}/user`, + body, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @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 createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + return this.httpClient.post(`${this.basePath}/user/createWithArray`, + body, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @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 createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + return this.httpClient.post(`${this.basePath}/user/createWithList`, + body, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @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 deleteUser(username: string, observe?: 'body', reportProgress?: boolean): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + + return this.httpClient.delete(`${this.basePath}/user/${encodeURIComponent(String(username))}`, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @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 getUserByName(username: string, observe?: 'body', reportProgress?: boolean): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/user/${encodeURIComponent(String(username))}`, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @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 loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); + if (username !== undefined && username !== null) { + queryParameters = queryParameters.set('username', username); + } + if (password !== undefined && password !== null) { + queryParameters = queryParameters.set('password', password); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/user/login`, + { + params: queryParameters, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs out current logged in user session + * + * @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 logoutUser(observe?: 'body', reportProgress?: boolean): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + + return this.httpClient.get(`${this.basePath}/user/logout`, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be updated + * @param body Updated user object + * @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(username: string, body: User, observe?: 'body', reportProgress?: boolean): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updateUser.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + return this.httpClient.put(`${this.basePath}/user/${encodeURIComponent(String(username))}`, + body, + { + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/test/generated-clients/typescript-angular/configuration.ts b/test/generated-clients/typescript-angular/configuration.ts new file mode 100644 index 00000000..82e8458f --- /dev/null +++ b/test/generated-clients/typescript-angular/configuration.ts @@ -0,0 +1,79 @@ +export interface ConfigurationParameters { + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; +} + +export class Configuration { + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + + 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; + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length == 0) { + return undefined; + } + + let type = contentTypes.find(x => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length == 0) { + return undefined; + } + + let type = accepts.find(x => 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'); + } +} diff --git a/test/generated-clients/typescript-angular/encoder.ts b/test/generated-clients/typescript-angular/encoder.ts new file mode 100644 index 00000000..f1c6b78c --- /dev/null +++ b/test/generated-clients/typescript-angular/encoder.ts @@ -0,0 +1,18 @@ + import { HttpUrlEncodingCodec } from '@angular/common/http'; + +/** +* CustomHttpUrlEncodingCodec +* Fix plus sign (+) not encoding, so sent as blank space +* See: https://github.com/angular/angular/issues/11058#issuecomment-247367318 +*/ +export class CustomHttpUrlEncodingCodec extends HttpUrlEncodingCodec { + encodeKey(k: string): string { + k = super.encodeKey(k); + return k.replace(/\+/gi, '%2B'); + } + encodeValue(v: string): string { + v = super.encodeValue(v); + return v.replace(/\+/gi, '%2B'); + } +} + diff --git a/test/generated-clients/typescript-angular/git_push.sh b/test/generated-clients/typescript-angular/git_push.sh new file mode 100644 index 00000000..ae01b182 --- /dev/null +++ b/test/generated-clients/typescript-angular/git_push.sh @@ -0,0 +1,52 @@ +#!/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" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +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://github.com/${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 + fi + +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" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/test/generated-clients/typescript-angular/index.ts b/test/generated-clients/typescript-angular/index.ts new file mode 100644 index 00000000..c312b70f --- /dev/null +++ b/test/generated-clients/typescript-angular/index.ts @@ -0,0 +1,5 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; \ No newline at end of file diff --git a/test/generated-clients/typescript-angular/model/apiResponse.ts b/test/generated-clients/typescript-angular/model/apiResponse.ts new file mode 100644 index 00000000..fda53fa6 --- /dev/null +++ b/test/generated-clients/typescript-angular/model/apiResponse.ts @@ -0,0 +1,18 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} diff --git a/test/generated-clients/typescript-angular/model/category.ts b/test/generated-clients/typescript-angular/model/category.ts new file mode 100644 index 00000000..ce6c6530 --- /dev/null +++ b/test/generated-clients/typescript-angular/model/category.ts @@ -0,0 +1,17 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export interface Category { + id?: number; + name?: string; +} diff --git a/test/generated-clients/typescript-angular/model/models.ts b/test/generated-clients/typescript-angular/model/models.ts new file mode 100644 index 00000000..8607c5da --- /dev/null +++ b/test/generated-clients/typescript-angular/model/models.ts @@ -0,0 +1,6 @@ +export * from './apiResponse'; +export * from './category'; +export * from './order'; +export * from './pet'; +export * from './tag'; +export * from './user'; diff --git a/test/generated-clients/typescript-angular/model/order.ts b/test/generated-clients/typescript-angular/model/order.ts new file mode 100644 index 00000000..d79b8b8f --- /dev/null +++ b/test/generated-clients/typescript-angular/model/order.ts @@ -0,0 +1,32 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: Date; + /** + * Order Status + */ + status?: Order.StatusEnum; + complete?: boolean; +} +export namespace Order { + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + }; +} diff --git a/test/generated-clients/typescript-angular/model/pet.ts b/test/generated-clients/typescript-angular/model/pet.ts new file mode 100644 index 00000000..37f8f303 --- /dev/null +++ b/test/generated-clients/typescript-angular/model/pet.ts @@ -0,0 +1,34 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ +import { Category } from './category'; +import { Tag } from './tag'; + + +export interface Pet { + id?: number; + category?: Category; + name: string; + photoUrls: Array; + tags?: Array; + /** + * pet status in the store + */ + status?: Pet.StatusEnum; +} +export namespace Pet { + export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + }; +} diff --git a/test/generated-clients/typescript-angular/model/tag.ts b/test/generated-clients/typescript-angular/model/tag.ts new file mode 100644 index 00000000..f4f97406 --- /dev/null +++ b/test/generated-clients/typescript-angular/model/tag.ts @@ -0,0 +1,17 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export interface Tag { + id?: number; + name?: string; +} diff --git a/test/generated-clients/typescript-angular/model/user.ts b/test/generated-clients/typescript-angular/model/user.ts new file mode 100644 index 00000000..9e5f119a --- /dev/null +++ b/test/generated-clients/typescript-angular/model/user.ts @@ -0,0 +1,26 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} diff --git a/test/generated-clients/typescript-angular/variables.ts b/test/generated-clients/typescript-angular/variables.ts new file mode 100644 index 00000000..6fe58549 --- /dev/null +++ b/test/generated-clients/typescript-angular/variables.ts @@ -0,0 +1,9 @@ +import { InjectionToken } from '@angular/core'; + +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/test/generated-clients/typescript-angularjs/.gitignore b/test/generated-clients/typescript-angularjs/.gitignore new file mode 100644 index 00000000..35e2fb2b --- /dev/null +++ b/test/generated-clients/typescript-angularjs/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/test/generated-clients/typescript-angularjs/.swagger-codegen-ignore b/test/generated-clients/typescript-angularjs/.swagger-codegen-ignore new file mode 100644 index 00000000..c5fa491b --- /dev/null +++ b/test/generated-clients/typescript-angularjs/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# 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 Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/test/generated-clients/typescript-angularjs/.swagger-codegen/VERSION b/test/generated-clients/typescript-angularjs/.swagger-codegen/VERSION new file mode 100644 index 00000000..752a79ef --- /dev/null +++ b/test/generated-clients/typescript-angularjs/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.8 \ No newline at end of file diff --git a/test/generated-clients/typescript-angularjs/api.module.ts b/test/generated-clients/typescript-angularjs/api.module.ts new file mode 100644 index 00000000..825758a0 --- /dev/null +++ b/test/generated-clients/typescript-angularjs/api.module.ts @@ -0,0 +1,9 @@ +import * as api from './api/api'; +import * as angular from 'angular'; + +const apiModule = angular.module('api', []) +.service('PetApi', api.PetApi) +.service('StoreApi', api.StoreApi) +.service('UserApi', api.UserApi) + +export default apiModule; diff --git a/test/generated-clients/typescript-angularjs/api/PetApi.ts b/test/generated-clients/typescript-angularjs/api/PetApi.ts new file mode 100644 index 00000000..1344894c --- /dev/null +++ b/test/generated-clients/typescript-angularjs/api/PetApi.ts @@ -0,0 +1,292 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from '../model/models'; + +/* tslint:disable:no-unused-variable member-ordering */ + +export class PetApi { + protected basePath = 'https://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; + + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { + if (basePath !== undefined) { + this.basePath = basePath; + } + } + + /** + * + * @summary Add a new pet to the store + * @param body Pet object that needs to be added to the store + */ + public addPet (body: models.Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling addPet.'); + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * + * @summary Deletes a pet + * @param petId Pet id to delete + * @param apiKey + */ + public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + headerParams['api_key'] = apiKey; + + let httpRequestParams: ng.IRequestConfig = { + method: 'DELETE', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Multiple status values can be provided with comma separated strings + * @summary Finds Pets by status + * @param status Status values that need to be considered for filter + */ + public findPetsByStatus (status: Array<'available' | 'pending' | 'sold'>, extraHttpRequestParams?: any ) : ng.IHttpPromise> { + const localVarPath = this.basePath + '/pet/findByStatus'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'status' is not null or undefined + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + if (status !== undefined) { + queryParameters['status'] = status; + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @summary Finds Pets by tags + * @param tags Tags to filter by + */ + public findPetsByTags (tags: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { + const localVarPath = this.basePath + '/pet/findByTags'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'tags' is not null or undefined + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + if (tags !== undefined) { + queryParameters['tags'] = tags; + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Returns a single pet + * @summary Find pet by ID + * @param petId ID of pet to return + */ + public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * + * @summary Update an existing pet + * @param body Pet object that needs to be added to the store + */ + public updatePet (body: models.Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updatePet.'); + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'PUT', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * + * @summary Updates a pet in the store with form data + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + public updatePetWithForm (petId: number, name?: string, status?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let formParams: any = {}; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['name'] = name; + + formParams['status'] = status; + + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: this.$httpParamSerializer(formParams), + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * + * @summary uploads an image + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/pet/{petId}/uploadImage' + .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let formParams: any = {}; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['additionalMetadata'] = additionalMetadata; + + formParams['file'] = file; + + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: this.$httpParamSerializer(formParams), + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } +} diff --git a/test/generated-clients/typescript-angularjs/api/StoreApi.ts b/test/generated-clients/typescript-angularjs/api/StoreApi.ts new file mode 100644 index 00000000..e952b5f4 --- /dev/null +++ b/test/generated-clients/typescript-angularjs/api/StoreApi.ts @@ -0,0 +1,138 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from '../model/models'; + +/* tslint:disable:no-unused-variable member-ordering */ + +export class StoreApi { + protected basePath = 'https://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; + + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { + if (basePath !== undefined) { + this.basePath = basePath; + } + } + + /** + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * @summary Delete purchase order by ID + * @param orderId ID of the order that needs to be deleted + */ + public deleteOrder (orderId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'DELETE', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Returns a map of status codes to quantities + * @summary Returns pet inventories by status + */ + public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise<{ [key: string]: number; }> { + const localVarPath = this.basePath + '/store/inventory'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * @summary Find purchase order by ID + * @param orderId ID of pet that needs to be fetched + */ + public getOrderById (orderId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * + * @summary Place an order for a pet + * @param body order placed for purchasing the pet + */ + public placeOrder (body: models.Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/store/order'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling placeOrder.'); + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } +} diff --git a/test/generated-clients/typescript-angularjs/api/UserApi.ts b/test/generated-clients/typescript-angularjs/api/UserApi.ts new file mode 100644 index 00000000..6777f2ea --- /dev/null +++ b/test/generated-clients/typescript-angularjs/api/UserApi.ts @@ -0,0 +1,274 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from '../model/models'; + +/* tslint:disable:no-unused-variable member-ordering */ + +export class UserApi { + protected basePath = 'https://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; + + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { + if (basePath !== undefined) { + this.basePath = basePath; + } + } + + /** + * This can only be done by the logged in user. + * @summary Create user + * @param body Created user object + */ + public createUser (body: models.User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUser.'); + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * + * @summary Creates list of users with given input array + * @param body List of user object + */ + public createUsersWithArrayInput (body: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user/createWithArray'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * + * @summary Creates list of users with given input array + * @param body List of user object + */ + public createUsersWithListInput (body: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user/createWithList'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * This can only be done by the logged in user. + * @summary Delete user + * @param username The name that needs to be deleted + */ + public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', encodeURIComponent(String(username))); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'DELETE', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * + * @summary Get user by user name + * @param username The name that needs to be fetched. Use user1 for testing. + */ + public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', encodeURIComponent(String(username))); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * + * @summary Logs user into the system + * @param username The user name for login + * @param password The password for login in clear text + */ + public loginUser (username: string, password: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/user/login'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + + // verify required parameter 'password' is not null or undefined + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + if (username !== undefined) { + queryParameters['username'] = username; + } + + if (password !== undefined) { + queryParameters['password'] = password; + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * + * @summary Logs out current logged in user session + */ + public logoutUser (extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user/logout'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * This can only be done by the logged in user. + * @summary Updated user + * @param username name that need to be updated + * @param body Updated user object + */ + public updateUser (username: string, body: models.User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', encodeURIComponent(String(username))); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updateUser.'); + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'PUT', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } +} diff --git a/test/generated-clients/typescript-angularjs/api/api.ts b/test/generated-clients/typescript-angularjs/api/api.ts new file mode 100644 index 00000000..4ddd9e29 --- /dev/null +++ b/test/generated-clients/typescript-angularjs/api/api.ts @@ -0,0 +1,7 @@ +export * from './PetApi'; +import { PetApi } from './PetApi'; +export * from './StoreApi'; +import { StoreApi } from './StoreApi'; +export * from './UserApi'; +import { UserApi } from './UserApi'; +export const APIS = [PetApi, StoreApi, UserApi]; diff --git a/test/generated-clients/typescript-angularjs/git_push.sh b/test/generated-clients/typescript-angularjs/git_push.sh new file mode 100644 index 00000000..ae01b182 --- /dev/null +++ b/test/generated-clients/typescript-angularjs/git_push.sh @@ -0,0 +1,52 @@ +#!/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" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +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://github.com/${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 + fi + +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" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/test/generated-clients/typescript-angularjs/index.ts b/test/generated-clients/typescript-angularjs/index.ts new file mode 100644 index 00000000..55736551 --- /dev/null +++ b/test/generated-clients/typescript-angularjs/index.ts @@ -0,0 +1,2 @@ +export * from './api/api'; +export * from './model/models'; \ No newline at end of file diff --git a/test/generated-clients/typescript-angularjs/model/ApiResponse.ts b/test/generated-clients/typescript-angularjs/model/ApiResponse.ts new file mode 100644 index 00000000..a3203381 --- /dev/null +++ b/test/generated-clients/typescript-angularjs/model/ApiResponse.ts @@ -0,0 +1,20 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from './models'; + +export interface ApiResponse { + "code"?: number; + "type"?: string; + "message"?: string; +} + diff --git a/test/generated-clients/typescript-angularjs/model/Category.ts b/test/generated-clients/typescript-angularjs/model/Category.ts new file mode 100644 index 00000000..4d4300d4 --- /dev/null +++ b/test/generated-clients/typescript-angularjs/model/Category.ts @@ -0,0 +1,19 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from './models'; + +export interface Category { + "id"?: number; + "name"?: string; +} + diff --git a/test/generated-clients/typescript-angularjs/model/Order.ts b/test/generated-clients/typescript-angularjs/model/Order.ts new file mode 100644 index 00000000..f9b2c2fd --- /dev/null +++ b/test/generated-clients/typescript-angularjs/model/Order.ts @@ -0,0 +1,33 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from './models'; + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + /** + * Order Status + */ + "status"?: Order.StatusEnum; + "complete"?: boolean; +} + +export namespace Order { + export enum StatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' + } +} diff --git a/test/generated-clients/typescript-angularjs/model/Pet.ts b/test/generated-clients/typescript-angularjs/model/Pet.ts new file mode 100644 index 00000000..8774d817 --- /dev/null +++ b/test/generated-clients/typescript-angularjs/model/Pet.ts @@ -0,0 +1,33 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from './models'; + +export interface Pet { + "id"?: number; + "category"?: models.Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + /** + * pet status in the store + */ + "status"?: Pet.StatusEnum; +} + +export namespace Pet { + export enum StatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' + } +} diff --git a/test/generated-clients/typescript-angularjs/model/Tag.ts b/test/generated-clients/typescript-angularjs/model/Tag.ts new file mode 100644 index 00000000..e5eacca0 --- /dev/null +++ b/test/generated-clients/typescript-angularjs/model/Tag.ts @@ -0,0 +1,19 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from './models'; + +export interface Tag { + "id"?: number; + "name"?: string; +} + diff --git a/test/generated-clients/typescript-angularjs/model/User.ts b/test/generated-clients/typescript-angularjs/model/User.ts new file mode 100644 index 00000000..ce4f66ef --- /dev/null +++ b/test/generated-clients/typescript-angularjs/model/User.ts @@ -0,0 +1,28 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from './models'; + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + /** + * User Status + */ + "userStatus"?: number; +} + diff --git a/test/generated-clients/typescript-angularjs/model/models.ts b/test/generated-clients/typescript-angularjs/model/models.ts new file mode 100644 index 00000000..f53c1dd4 --- /dev/null +++ b/test/generated-clients/typescript-angularjs/model/models.ts @@ -0,0 +1,6 @@ +export * from './ApiResponse'; +export * from './Category'; +export * from './Order'; +export * from './Pet'; +export * from './Tag'; +export * from './User'; diff --git a/test/generated-clients/typescript-aurelia/.gitignore b/test/generated-clients/typescript-aurelia/.gitignore new file mode 100644 index 00000000..35e2fb2b --- /dev/null +++ b/test/generated-clients/typescript-aurelia/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/test/generated-clients/typescript-aurelia/.swagger-codegen-ignore b/test/generated-clients/typescript-aurelia/.swagger-codegen-ignore new file mode 100644 index 00000000..c5fa491b --- /dev/null +++ b/test/generated-clients/typescript-aurelia/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# 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 Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/test/generated-clients/typescript-aurelia/.swagger-codegen/VERSION b/test/generated-clients/typescript-aurelia/.swagger-codegen/VERSION new file mode 100644 index 00000000..752a79ef --- /dev/null +++ b/test/generated-clients/typescript-aurelia/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.8 \ No newline at end of file diff --git a/test/generated-clients/typescript-aurelia/Api.ts b/test/generated-clients/typescript-aurelia/Api.ts new file mode 100644 index 00000000..a4b275c2 --- /dev/null +++ b/test/generated-clients/typescript-aurelia/Api.ts @@ -0,0 +1,76 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import { HttpClient } from 'aurelia-http-client'; +import { AuthStorage } from './AuthStorage'; + +const BASE_PATH = 'https://petstore.swagger.io/v2'.replace(/\/+$/, ''); + +export class Api { + basePath: string; + httpClient: HttpClient; + authStorage: AuthStorage; + + constructor(httpClient: HttpClient, authStorage: AuthStorage, basePath: string = BASE_PATH) { + this.basePath = basePath; + this.httpClient = httpClient; + this.authStorage = authStorage; + } + + /** + * Encodes a query string. + * + * @param params The params to encode. + * @return An encoded query string. + */ + protected queryString(params: { [key: string]: any }): string { + const queries = []; + for (let key in params) { + const value = this.toString(params[key]); + if (value != null) { + queries.push(`${key}=${encodeURIComponent(value)}`); + } + } + + return queries.join('&'); + } + + /** + * Converts a value to string. + * + * @param value The value to convert. + */ + protected toString(value: any): string | null { + if (value === null) { + return null; + } + switch (typeof value) { + case 'undefined': return null; + case 'boolean': return value ? 'true' : 'false'; + case 'string': return value; + default: return '' + value; + } + } + + /** + * Ensures that a given parameter is set. + * + * @param context A name for the callee's context. + * @param params The parameters being set. + * @param paramName The required parameter to check. + */ + protected ensureParamIsSet(context: string, params: T, paramName: keyof T): void { + if (null === params[paramName]) { + throw new Error(`Missing required parameter ${paramName} when calling ${context}`); + } + } +} diff --git a/test/generated-clients/typescript-aurelia/AuthStorage.ts b/test/generated-clients/typescript-aurelia/AuthStorage.ts new file mode 100644 index 00000000..f72cf3a4 --- /dev/null +++ b/test/generated-clients/typescript-aurelia/AuthStorage.ts @@ -0,0 +1,72 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +/** + * Class to storage authentication data + */ +export class AuthStorage { + private storage: Map; + + constructor() { + this.storage = new Map(); + } + + /** + * Sets the api_key auth method value. + * + * @param value The new value to set for api_key. + */ + setapi_key(value: string): this { + this.storage.set('api_key', value); + return this; + } + + /** + * Removes the api_key auth method value. + */ + removeapi_key(): this { + this.storage.delete('api_key'); + return this; + } + + /** + * Gets the api_key auth method value. + */ + getapi_key(): null | string { + return this.storage.get('api_key') || null; + } + + /** + * Sets the petstore_auth auth method value. + * + * @param value The new value to set for petstore_auth. + */ + setpetstore_auth(value: string): this { + this.storage.set('petstore_auth', value); + return this; + } + + /** + * Removes the petstore_auth auth method value. + */ + removepetstore_auth(): this { + this.storage.delete('petstore_auth'); + return this; + } + + /** + * Gets the petstore_auth auth method value. + */ + getpetstore_auth(): null | string { + return this.storage.get('petstore_auth') || null; + } +} diff --git a/test/generated-clients/typescript-aurelia/PetApi.ts b/test/generated-clients/typescript-aurelia/PetApi.ts new file mode 100644 index 00000000..a8c37b43 --- /dev/null +++ b/test/generated-clients/typescript-aurelia/PetApi.ts @@ -0,0 +1,360 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import { autoinject } from 'aurelia-framework'; +import { HttpClient } from 'aurelia-http-client'; +import { Api } from './Api'; +import { AuthStorage } from './AuthStorage'; +import { + Pet, + ApiResponse, +} from './models'; + +/** + * addPet - parameters interface + */ +export interface IAddPetParams { + body: Pet; +} + +/** + * deletePet - parameters interface + */ +export interface IDeletePetParams { + petId: number; + apiKey?: string; +} + +/** + * findPetsByStatus - parameters interface + */ +export interface IFindPetsByStatusParams { + status: Array<'available' | 'pending' | 'sold'>; +} + +/** + * findPetsByTags - parameters interface + */ +export interface IFindPetsByTagsParams { + tags: Array; +} + +/** + * getPetById - parameters interface + */ +export interface IGetPetByIdParams { + petId: number; +} + +/** + * updatePet - parameters interface + */ +export interface IUpdatePetParams { + body: Pet; +} + +/** + * updatePetWithForm - parameters interface + */ +export interface IUpdatePetWithFormParams { + petId: number; + name?: string; + status?: string; +} + +/** + * uploadFile - parameters interface + */ +export interface IUploadFileParams { + petId: number; + additionalMetadata?: string; + file?: any; +} + +/** + * PetApi - API class + */ +@autoinject() +export class PetApi extends Api { + + /** + * Creates a new PetApi class. + * + * @param httpClient The Aurelia HTTP client to be injected. + * @param authStorage A storage for authentication data. + */ + constructor(httpClient: HttpClient, authStorage: AuthStorage) { + super(httpClient, authStorage); + } + + /** + * Add a new pet to the store + * + * @param params.body Pet object that needs to be added to the store + */ + async addPet(params: IAddPetParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('addPet', params, 'body'); + + // Create URL to call + const url = `${this.basePath}/pet`; + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asPost() + // Encode body parameter + .withHeader('content-type', 'application/json') + .withContent(JSON.stringify(params['body'] || {})) + + // Authentication 'petstore_auth' required + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Deletes a pet + * + * @param params.petId Pet id to delete + * @param params.apiKey + */ + async deletePet(params: IDeletePetParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('deletePet', params, 'petId'); + + // Create URL to call + const url = `${this.basePath}/pet/{petId}` + .replace(`{${'petId'}}`, encodeURIComponent(`${params['petId']}`)); + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asDelete() + .withHeader('api_key', params['apiKey']) + // Authentication 'petstore_auth' required + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param params.status Status values that need to be considered for filter + */ + async findPetsByStatus(params: IFindPetsByStatusParams): Promise> { + // Verify required parameters are set + this.ensureParamIsSet('findPetsByStatus', params, 'status'); + + // Create URL to call + const url = `${this.basePath}/pet/findByStatus`; + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asGet() + // Set query parameters + .withParams({ + 'status': params['status'], + }) + + // Authentication 'petstore_auth' required + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param params.tags Tags to filter by + */ + async findPetsByTags(params: IFindPetsByTagsParams): Promise> { + // Verify required parameters are set + this.ensureParamIsSet('findPetsByTags', params, 'tags'); + + // Create URL to call + const url = `${this.basePath}/pet/findByTags`; + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asGet() + // Set query parameters + .withParams({ + 'tags': params['tags'], + }) + + // Authentication 'petstore_auth' required + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Find pet by ID + * Returns a single pet + * @param params.petId ID of pet to return + */ + async getPetById(params: IGetPetByIdParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('getPetById', params, 'petId'); + + // Create URL to call + const url = `${this.basePath}/pet/{petId}` + .replace(`{${'petId'}}`, encodeURIComponent(`${params['petId']}`)); + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asGet() + + // Authentication 'api_key' required + .withHeader('api_key', this.authStorage.getapi_key()) + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Update an existing pet + * + * @param params.body Pet object that needs to be added to the store + */ + async updatePet(params: IUpdatePetParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('updatePet', params, 'body'); + + // Create URL to call + const url = `${this.basePath}/pet`; + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asPut() + // Encode body parameter + .withHeader('content-type', 'application/json') + .withContent(JSON.stringify(params['body'] || {})) + + // Authentication 'petstore_auth' required + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Updates a pet in the store with form data + * + * @param params.petId ID of pet that needs to be updated + * @param params.name Updated name of the pet + * @param params.status Updated status of the pet + */ + async updatePetWithForm(params: IUpdatePetWithFormParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('updatePetWithForm', params, 'petId'); + + // Create URL to call + const url = `${this.basePath}/pet/{petId}` + .replace(`{${'petId'}}`, encodeURIComponent(`${params['petId']}`)); + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asPost() + // Encode form parameters + .withHeader('content-type', 'application/x-www-form-urlencoded') + .withContent(this.queryString({ + 'name': params['name'], + 'status': params['status'], + })) + + // Authentication 'petstore_auth' required + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * uploads an image + * + * @param params.petId ID of pet to update + * @param params.additionalMetadata Additional data to pass to server + * @param params.file file to upload + */ + async uploadFile(params: IUploadFileParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('uploadFile', params, 'petId'); + + // Create URL to call + const url = `${this.basePath}/pet/{petId}/uploadImage` + .replace(`{${'petId'}}`, encodeURIComponent(`${params['petId']}`)); + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asPost() + // Encode form parameters + .withHeader('content-type', 'application/x-www-form-urlencoded') + .withContent(this.queryString({ + 'additionalMetadata': params['additionalMetadata'], + 'file': params['file'], + })) + + // Authentication 'petstore_auth' required + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + +} + diff --git a/test/generated-clients/typescript-aurelia/README.md b/test/generated-clients/typescript-aurelia/README.md new file mode 100644 index 00000000..1796b7e1 --- /dev/null +++ b/test/generated-clients/typescript-aurelia/README.md @@ -0,0 +1,55 @@ +# TypeScript-Aurelia + +This generator creates TypeScript/JavaScript client that is injectable by [Aurelia](http://aurelia.io/). +The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink every time you deploy that project. + +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. + +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` + +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('./symlinkDir')'; +``` diff --git a/test/generated-clients/typescript-aurelia/StoreApi.ts b/test/generated-clients/typescript-aurelia/StoreApi.ts new file mode 100644 index 00000000..ac5a11bf --- /dev/null +++ b/test/generated-clients/typescript-aurelia/StoreApi.ts @@ -0,0 +1,178 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import { autoinject } from 'aurelia-framework'; +import { HttpClient } from 'aurelia-http-client'; +import { Api } from './Api'; +import { AuthStorage } from './AuthStorage'; +import { + Order, +} from './models'; + +/** + * deleteOrder - parameters interface + */ +export interface IDeleteOrderParams { + orderId: number; +} + +/** + * getInventory - parameters interface + */ +export interface IGetInventoryParams { +} + +/** + * getOrderById - parameters interface + */ +export interface IGetOrderByIdParams { + orderId: number; +} + +/** + * placeOrder - parameters interface + */ +export interface IPlaceOrderParams { + body: Order; +} + +/** + * StoreApi - API class + */ +@autoinject() +export class StoreApi extends Api { + + /** + * Creates a new StoreApi class. + * + * @param httpClient The Aurelia HTTP client to be injected. + * @param authStorage A storage for authentication data. + */ + constructor(httpClient: HttpClient, authStorage: AuthStorage) { + super(httpClient, authStorage); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * @param params.orderId ID of the order that needs to be deleted + */ + async deleteOrder(params: IDeleteOrderParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('deleteOrder', params, 'orderId'); + + // Create URL to call + const url = `${this.basePath}/store/order/{orderId}` + .replace(`{${'orderId'}}`, encodeURIComponent(`${params['orderId']}`)); + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asDelete() + + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + async getInventory(): Promise<{ [key: string]: number; }> { + // Verify required parameters are set + + // Create URL to call + const url = `${this.basePath}/store/inventory`; + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asGet() + + // Authentication 'api_key' required + .withHeader('api_key', this.authStorage.getapi_key()) + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * @param params.orderId ID of pet that needs to be fetched + */ + async getOrderById(params: IGetOrderByIdParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('getOrderById', params, 'orderId'); + + // Create URL to call + const url = `${this.basePath}/store/order/{orderId}` + .replace(`{${'orderId'}}`, encodeURIComponent(`${params['orderId']}`)); + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asGet() + + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Place an order for a pet + * + * @param params.body order placed for purchasing the pet + */ + async placeOrder(params: IPlaceOrderParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('placeOrder', params, 'body'); + + // Create URL to call + const url = `${this.basePath}/store/order`; + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asPost() + // Encode body parameter + .withHeader('content-type', 'application/json') + .withContent(JSON.stringify(params['body'] || {})) + + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + +} + diff --git a/test/generated-clients/typescript-aurelia/UserApi.ts b/test/generated-clients/typescript-aurelia/UserApi.ts new file mode 100644 index 00000000..479c6edc --- /dev/null +++ b/test/generated-clients/typescript-aurelia/UserApi.ts @@ -0,0 +1,333 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import { autoinject } from 'aurelia-framework'; +import { HttpClient } from 'aurelia-http-client'; +import { Api } from './Api'; +import { AuthStorage } from './AuthStorage'; +import { + User, +} from './models'; + +/** + * createUser - parameters interface + */ +export interface ICreateUserParams { + body: User; +} + +/** + * createUsersWithArrayInput - parameters interface + */ +export interface ICreateUsersWithArrayInputParams { + body: Array; +} + +/** + * createUsersWithListInput - parameters interface + */ +export interface ICreateUsersWithListInputParams { + body: Array; +} + +/** + * deleteUser - parameters interface + */ +export interface IDeleteUserParams { + username: string; +} + +/** + * getUserByName - parameters interface + */ +export interface IGetUserByNameParams { + username: string; +} + +/** + * loginUser - parameters interface + */ +export interface ILoginUserParams { + username: string; + password: string; +} + +/** + * logoutUser - parameters interface + */ +export interface ILogoutUserParams { +} + +/** + * updateUser - parameters interface + */ +export interface IUpdateUserParams { + username: string; + body: User; +} + +/** + * UserApi - API class + */ +@autoinject() +export class UserApi extends Api { + + /** + * Creates a new UserApi class. + * + * @param httpClient The Aurelia HTTP client to be injected. + * @param authStorage A storage for authentication data. + */ + constructor(httpClient: HttpClient, authStorage: AuthStorage) { + super(httpClient, authStorage); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param params.body Created user object + */ + async createUser(params: ICreateUserParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('createUser', params, 'body'); + + // Create URL to call + const url = `${this.basePath}/user`; + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asPost() + // Encode body parameter + .withHeader('content-type', 'application/json') + .withContent(JSON.stringify(params['body'] || {})) + + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Creates list of users with given input array + * + * @param params.body List of user object + */ + async createUsersWithArrayInput(params: ICreateUsersWithArrayInputParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('createUsersWithArrayInput', params, 'body'); + + // Create URL to call + const url = `${this.basePath}/user/createWithArray`; + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asPost() + // Encode body parameter + .withHeader('content-type', 'application/json') + .withContent(JSON.stringify(params['body'] || {})) + + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Creates list of users with given input array + * + * @param params.body List of user object + */ + async createUsersWithListInput(params: ICreateUsersWithListInputParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('createUsersWithListInput', params, 'body'); + + // Create URL to call + const url = `${this.basePath}/user/createWithList`; + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asPost() + // Encode body parameter + .withHeader('content-type', 'application/json') + .withContent(JSON.stringify(params['body'] || {})) + + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param params.username The name that needs to be deleted + */ + async deleteUser(params: IDeleteUserParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('deleteUser', params, 'username'); + + // Create URL to call + const url = `${this.basePath}/user/{username}` + .replace(`{${'username'}}`, encodeURIComponent(`${params['username']}`)); + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asDelete() + + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Get user by user name + * + * @param params.username The name that needs to be fetched. Use user1 for testing. + */ + async getUserByName(params: IGetUserByNameParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('getUserByName', params, 'username'); + + // Create URL to call + const url = `${this.basePath}/user/{username}` + .replace(`{${'username'}}`, encodeURIComponent(`${params['username']}`)); + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asGet() + + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Logs user into the system + * + * @param params.username The user name for login + * @param params.password The password for login in clear text + */ + async loginUser(params: ILoginUserParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('loginUser', params, 'username'); + this.ensureParamIsSet('loginUser', params, 'password'); + + // Create URL to call + const url = `${this.basePath}/user/login`; + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asGet() + // Set query parameters + .withParams({ + 'username': params['username'], + 'password': params['password'], + }) + + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Logs out current logged in user session + * + */ + async logoutUser(): Promise { + // Verify required parameters are set + + // Create URL to call + const url = `${this.basePath}/user/logout`; + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asGet() + + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param params.username name that need to be updated + * @param params.body Updated user object + */ + async updateUser(params: IUpdateUserParams): Promise { + // Verify required parameters are set + this.ensureParamIsSet('updateUser', params, 'username'); + this.ensureParamIsSet('updateUser', params, 'body'); + + // Create URL to call + const url = `${this.basePath}/user/{username}` + .replace(`{${'username'}}`, encodeURIComponent(`${params['username']}`)); + + const response = await this.httpClient.createRequest(url) + // Set HTTP method + .asPut() + // Encode body parameter + .withHeader('content-type', 'application/json') + .withContent(JSON.stringify(params['body'] || {})) + + // Send the request + .send(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw new Error(response.content); + } + + // Extract the content + return response.content; + } + +} + diff --git a/test/generated-clients/typescript-aurelia/git_push.sh b/test/generated-clients/typescript-aurelia/git_push.sh new file mode 100644 index 00000000..ae01b182 --- /dev/null +++ b/test/generated-clients/typescript-aurelia/git_push.sh @@ -0,0 +1,52 @@ +#!/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" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +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://github.com/${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 + fi + +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" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/test/generated-clients/typescript-aurelia/index.ts b/test/generated-clients/typescript-aurelia/index.ts new file mode 100644 index 00000000..6d355f2b --- /dev/null +++ b/test/generated-clients/typescript-aurelia/index.ts @@ -0,0 +1,25 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +export { Api } from './Api'; +export { AuthStorage } from './AuthStorage'; +export { PetApi } from './PetApi'; +export { StoreApi } from './StoreApi'; +export { UserApi } from './UserApi'; +export { + ApiResponse, + Category, + Order, + Pet, + Tag, + User, +} from './models'; diff --git a/test/generated-clients/typescript-aurelia/models.ts b/test/generated-clients/typescript-aurelia/models.ts new file mode 100644 index 00000000..819ce27d --- /dev/null +++ b/test/generated-clients/typescript-aurelia/models.ts @@ -0,0 +1,76 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} + +export interface Category { + id?: number; + name?: string; +} + +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: Date; + /** + * Order Status + */ + status?: OrderStatusEnum; + complete?: boolean; +} + +/** + * Enum for the status property. + */ +export type OrderStatusEnum = 'placed' | 'approved' | 'delivered'; + +export interface Pet { + id?: number; + category?: Category; + name: string; + photoUrls: Array; + tags?: Array; + /** + * pet status in the store + */ + status?: PetStatusEnum; +} + +/** + * Enum for the status property. + */ +export type PetStatusEnum = 'available' | 'pending' | 'sold'; + +export interface Tag { + id?: number; + name?: string; +} + +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} + diff --git a/test/generated-clients/typescript-aurelia/package.json b/test/generated-clients/typescript-aurelia/package.json new file mode 100644 index 00000000..0204e3c3 --- /dev/null +++ b/test/generated-clients/typescript-aurelia/package.json @@ -0,0 +1,21 @@ +{ + "name": "typescript-fetch-api", + "version": "0.0.0", + "license": "Unlicense", + "main": "./dist/api.js", + "browser": "./dist/api.js", + "typings": "./dist/api.d.ts", + "dependencies": { + "core-js": "^2.4.0", + "isomorphic-fetch": "^2.2.1" + }, + "scripts" : { + "prepublish" : "typings install && tsc", + "test": "tslint api.ts" + }, + "devDependencies": { + "tslint": "^3.15.1", + "typescript": "^1.8.10", + "typings": "^1.0.4" + } +} diff --git a/test/generated-clients/typescript-aurelia/tsconfig.json b/test/generated-clients/typescript-aurelia/tsconfig.json new file mode 100644 index 00000000..1a36def5 --- /dev/null +++ b/test/generated-clients/typescript-aurelia/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "es5", + "module": "commonjs", + "noImplicitAny": true, + "outDir": "dist", + "rootDir": "." + }, + "exclude": [ + "dist", + "node_modules" + ] +} diff --git a/test/generated-clients/typescript-aurelia/tslint.json b/test/generated-clients/typescript-aurelia/tslint.json new file mode 100644 index 00000000..6eb02ace --- /dev/null +++ b/test/generated-clients/typescript-aurelia/tslint.json @@ -0,0 +1,101 @@ +{ + "jsRules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-duplicate-variable": true, + "no-eval": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + }, + "rules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-eval": true, + "no-internal-module": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "no-var-keyword": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + } +} diff --git a/test/generated-clients/typescript-fetch/.gitignore b/test/generated-clients/typescript-fetch/.gitignore new file mode 100644 index 00000000..35e2fb2b --- /dev/null +++ b/test/generated-clients/typescript-fetch/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/test/generated-clients/typescript-fetch/.swagger-codegen-ignore b/test/generated-clients/typescript-fetch/.swagger-codegen-ignore new file mode 100644 index 00000000..c5fa491b --- /dev/null +++ b/test/generated-clients/typescript-fetch/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# 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 Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/test/generated-clients/typescript-fetch/.swagger-codegen/VERSION b/test/generated-clients/typescript-fetch/.swagger-codegen/VERSION new file mode 100644 index 00000000..752a79ef --- /dev/null +++ b/test/generated-clients/typescript-fetch/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.8 \ No newline at end of file diff --git a/test/generated-clients/typescript-fetch/api.ts b/test/generated-clients/typescript-fetch/api.ts new file mode 100644 index 00000000..880abb21 --- /dev/null +++ b/test/generated-clients/typescript-fetch/api.ts @@ -0,0 +1,1991 @@ +/// +// tslint:disable +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +import * as url from "url"; +import * as portableFetch from "portable-fetch"; +import { Configuration } from "./configuration"; + +const BASE_PATH = "https://petstore.swagger.io/v2".replace(/\/+$/, ""); + +/** + * + * @export + */ +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +/** + * + * @export + * @interface FetchAPI + */ +export interface FetchAPI { + (url: string, init?: any): Promise; +} + +/** + * + * @export + * @interface FetchArgs + */ +export interface FetchArgs { + url: string; + options: any; +} + +/** + * + * @export + * @class BaseAPI + */ +export class BaseAPI { + protected configuration: Configuration; + + constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = portableFetch) { + if (configuration) { + this.configuration = configuration; + this.basePath = configuration.basePath || this.basePath; + } + } +}; + +/** + * + * @export + * @class RequiredError + * @extends {Error} + */ +export class RequiredError extends Error { + name: "RequiredError" + constructor(public field: string, msg?: string) { + super(msg); + } +} + +/** + * + * @export + * @interface ApiResponse + */ +export interface ApiResponse { + /** + * + * @type {number} + * @memberof ApiResponse + */ + code?: number; + /** + * + * @type {string} + * @memberof ApiResponse + */ + type?: string; + /** + * + * @type {string} + * @memberof ApiResponse + */ + message?: string; +} + +/** + * + * @export + * @interface Category + */ +export interface Category { + /** + * + * @type {number} + * @memberof Category + */ + id?: number; + /** + * + * @type {string} + * @memberof Category + */ + name?: string; +} + +/** + * + * @export + * @interface Order + */ +export interface Order { + /** + * + * @type {number} + * @memberof Order + */ + id?: number; + /** + * + * @type {number} + * @memberof Order + */ + petId?: number; + /** + * + * @type {number} + * @memberof Order + */ + quantity?: number; + /** + * + * @type {Date} + * @memberof Order + */ + shipDate?: Date; + /** + * Order Status + * @type {string} + * @memberof Order + */ + status?: Order.StatusEnum; + /** + * + * @type {boolean} + * @memberof Order + */ + complete?: boolean; +} + +/** + * @export + * @namespace Order + */ +export namespace Order { + /** + * @export + * @enum {string} + */ + export enum StatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' + } +} + +/** + * + * @export + * @interface Pet + */ +export interface Pet { + /** + * + * @type string + * @memberof Pet + */ + id?: number; + /** + * + * @type {Category} + * @memberof Pet + */ + category?: Category; + /** + * + * @type {string} + * @memberof Pet + */ + name: string; + /** + * + * @type {Array} + * @memberof Pet + */ + photoUrls: Array; + /** + * + * @type {Array} + * @memberof Pet + */ + tags?: Array; + /** + * pet status in the store + * @type {string} + * @memberof Pet + */ + status?: Pet.StatusEnum; +} + +/** + * @export + * @namespace Pet + */ +export namespace Pet { + /** + * @export + * @enum {string} + */ + export enum StatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' + } +} + +/** + * + * @export + * @interface Tag + */ +export interface Tag { + /** + * + * @type {number} + * @memberof Tag + */ + id?: number; + /** + * + * @type {string} + * @memberof Tag + */ + name?: string; +} + +/** + * + * @export + * @interface User + */ +export interface User { + /** + * + * @type {number} + * @memberof User + */ + id?: number; + /** + * + * @type {string} + * @memberof User + */ + username?: string; + /** + * + * @type {string} + * @memberof User + */ + firstName?: string; + /** + * + * @type {string} + * @memberof User + */ + lastName?: string; + /** + * + * @type {string} + * @memberof User + */ + email?: string; + /** + * + * @type {string} + * @memberof User + */ + password?: string; + /** + * + * @type {string} + * @memberof User + */ + phone?: string; + /** + * User Status + * @type {number} + * @memberof User + */ + userStatus?: number; +} + + +/** + * PetApi - fetch parameter creator + * @export + */ +export const PetApiFetchParamCreator = function (configuration?: Configuration) { + return { + /** + * + * @summary Add a new pet to the store + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + addPet(body: Pet, options: any = {}): FetchArgs { + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling addPet.'); + } + const localVarPath = `/pet`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("Pet" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Deletes a pet + * @param {number} petId Pet id to delete + * @param {string} [apiKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deletePet(petId: number, apiKey?: string, options: any = {}): FetchArgs { + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError('petId','Required parameter petId was null or undefined when calling deletePet.'); + } + const localVarPath = `/pet/{petId}` + .replace(`{${"petId"}}`, encodeURIComponent(String(petId))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'DELETE' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + if (apiKey !== undefined && apiKey !== null) { + localVarHeaderParameter['api_key'] = String(apiKey); + } + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Multiple status values can be provided with comma separated strings + * @summary Finds Pets by status + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options: any = {}): FetchArgs { + // verify required parameter 'status' is not null or undefined + if (status === null || status === undefined) { + throw new RequiredError('status','Required parameter status was null or undefined when calling findPetsByStatus.'); + } + const localVarPath = `/pet/findByStatus`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + if (status) { + localVarQueryParameter['status'] = status; + } + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @summary Finds Pets by tags + * @param {Array} tags Tags to filter by + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + findPetsByTags(tags: Array, options: any = {}): FetchArgs { + // verify required parameter 'tags' is not null or undefined + if (tags === null || tags === undefined) { + throw new RequiredError('tags','Required parameter tags was null or undefined when calling findPetsByTags.'); + } + const localVarPath = `/pet/findByTags`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + if (tags) { + localVarQueryParameter['tags'] = tags; + } + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Returns a single pet + * @summary Find pet by ID + * @param {number} petId ID of pet to return + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getPetById(petId: number, options: any = {}): FetchArgs { + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError('petId','Required parameter petId was null or undefined when calling getPetById.'); + } + const localVarPath = `/pet/{petId}` + .replace(`{${"petId"}}`, encodeURIComponent(String(petId))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication api_key required + if (configuration && configuration.apiKey) { + const localVarApiKeyValue = typeof configuration.apiKey === 'function' + ? configuration.apiKey("api_key") + : configuration.apiKey; + localVarHeaderParameter["api_key"] = localVarApiKeyValue; + } + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Update an existing pet + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updatePet(body: Pet, options: any = {}): FetchArgs { + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling updatePet.'); + } + const localVarPath = `/pet`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'PUT' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("Pet" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Updates a pet in the store with form data + * @param {number} petId ID of pet that needs to be updated + * @param {string} [name] Updated name of the pet + * @param {string} [status] Updated status of the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updatePetWithForm(petId: number, name?: string, status?: string, options: any = {}): FetchArgs { + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError('petId','Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + const localVarPath = `/pet/{petId}` + .replace(`{${"petId"}}`, encodeURIComponent(String(petId))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + const localVarFormParams = new url.URLSearchParams(); + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + if (name !== undefined) { + localVarFormParams.set('name', name as any); + } + + if (status !== undefined) { + localVarFormParams.set('status', status as any); + } + + localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = localVarFormParams.toString(); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary uploads an image + * @param {number} petId ID of pet to update + * @param {string} [additionalMetadata] Additional data to pass to server + * @param {any} [file] file to upload + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + uploadFile(petId: number, additionalMetadata?: string, file?: any, options: any = {}): FetchArgs { + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError('petId','Required parameter petId was null or undefined when calling uploadFile.'); + } + const localVarPath = `/pet/{petId}/uploadImage` + .replace(`{${"petId"}}`, encodeURIComponent(String(petId))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + const localVarFormParams = new url.URLSearchParams(); + + // authentication petstore_auth required + // oauth required + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; + localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; + } + + if (additionalMetadata !== undefined) { + localVarFormParams.set('additionalMetadata', additionalMetadata as any); + } + + if (file !== undefined) { + localVarFormParams.set('file', file as any); + } + + localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + localVarRequestOptions.body = localVarFormParams.toString(); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * PetApi - functional programming interface + * @export + */ +export const PetApiFp = function(configuration?: Configuration) { + return { + /** + * + * @summary Add a new pet to the store + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + addPet(body: Pet, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).addPet(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Deletes a pet + * @param {number} petId Pet id to delete + * @param {string} [apiKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deletePet(petId: number, apiKey?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).deletePet(petId, apiKey, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Multiple status values can be provided with comma separated strings + * @summary Finds Pets by status + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise> { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).findPetsByStatus(status, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @summary Finds Pets by tags + * @param {Array} tags Tags to filter by + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + findPetsByTags(tags: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise> { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).findPetsByTags(tags, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Returns a single pet + * @summary Find pet by ID + * @param {number} petId ID of pet to return + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getPetById(petId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).getPetById(petId, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Update an existing pet + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updatePet(body: Pet, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).updatePet(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Updates a pet in the store with form data + * @param {number} petId ID of pet that needs to be updated + * @param {string} [name] Updated name of the pet + * @param {string} [status] Updated status of the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updatePetWithForm(petId: number, name?: string, status?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).updatePetWithForm(petId, name, status, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary uploads an image + * @param {number} petId ID of pet to update + * @param {string} [additionalMetadata] Additional data to pass to server + * @param {any} [file] file to upload + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = PetApiFetchParamCreator(configuration).uploadFile(petId, additionalMetadata, file, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + } +}; + +/** + * PetApi - factory interface + * @export + */ +export const PetApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { + return { + /** + * + * @summary Add a new pet to the store + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + addPet(body: Pet, options?: any) { + return PetApiFp(configuration).addPet(body, options)(fetch, basePath); + }, + /** + * + * @summary Deletes a pet + * @param {number} petId Pet id to delete + * @param {string} [apiKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deletePet(petId: number, apiKey?: string, options?: any) { + return PetApiFp(configuration).deletePet(petId, apiKey, options)(fetch, basePath); + }, + /** + * Multiple status values can be provided with comma separated strings + * @summary Finds Pets by status + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: any) { + return PetApiFp(configuration).findPetsByStatus(status, options)(fetch, basePath); + }, + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @summary Finds Pets by tags + * @param {Array} tags Tags to filter by + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + findPetsByTags(tags: Array, options?: any) { + return PetApiFp(configuration).findPetsByTags(tags, options)(fetch, basePath); + }, + /** + * Returns a single pet + * @summary Find pet by ID + * @param {number} petId ID of pet to return + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getPetById(petId: number, options?: any) { + return PetApiFp(configuration).getPetById(petId, options)(fetch, basePath); + }, + /** + * + * @summary Update an existing pet + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updatePet(body: Pet, options?: any) { + return PetApiFp(configuration).updatePet(body, options)(fetch, basePath); + }, + /** + * + * @summary Updates a pet in the store with form data + * @param {number} petId ID of pet that needs to be updated + * @param {string} [name] Updated name of the pet + * @param {string} [status] Updated status of the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updatePetWithForm(petId: number, name?: string, status?: string, options?: any) { + return PetApiFp(configuration).updatePetWithForm(petId, name, status, options)(fetch, basePath); + }, + /** + * + * @summary uploads an image + * @param {number} petId ID of pet to update + * @param {string} [additionalMetadata] Additional data to pass to server + * @param {any} [file] file to upload + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any) { + return PetApiFp(configuration).uploadFile(petId, additionalMetadata, file, options)(fetch, basePath); + }, + }; +}; + +/** + * PetApi - object-oriented interface + * @export + * @class PetApi + * @extends {BaseAPI} + */ +export class PetApi extends BaseAPI { + /** + * + * @summary Add a new pet to the store + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public addPet(body: Pet, options?: any) { + return PetApiFp(this.configuration).addPet(body, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Deletes a pet + * @param {number} petId Pet id to delete + * @param {string} [apiKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public deletePet(petId: number, apiKey?: string, options?: any) { + return PetApiFp(this.configuration).deletePet(petId, apiKey, options)(this.fetch, this.basePath); + } + + /** + * Multiple status values can be provided with comma separated strings + * @summary Finds Pets by status + * @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: any) { + return PetApiFp(this.configuration).findPetsByStatus(status, options)(this.fetch, this.basePath); + } + + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @summary Finds Pets by tags + * @param {Array} tags Tags to filter by + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public findPetsByTags(tags: Array, options?: any) { + return PetApiFp(this.configuration).findPetsByTags(tags, options)(this.fetch, this.basePath); + } + + /** + * Returns a single pet + * @summary Find pet by ID + * @param {number} petId ID of pet to return + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public getPetById(petId: number, options?: any) { + return PetApiFp(this.configuration).getPetById(petId, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Update an existing pet + * @param {Pet} body Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public updatePet(body: Pet, options?: any) { + return PetApiFp(this.configuration).updatePet(body, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Updates a pet in the store with form data + * @param {number} petId ID of pet that needs to be updated + * @param {string} [name] Updated name of the pet + * @param {string} [status] Updated status of the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public updatePetWithForm(petId: number, name?: string, status?: string, options?: any) { + return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options)(this.fetch, this.basePath); + } + + /** + * + * @summary uploads an image + * @param {number} petId ID of pet to update + * @param {string} [additionalMetadata] Additional data to pass to server + * @param {any} [file] file to upload + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PetApi + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any) { + return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options)(this.fetch, this.basePath); + } + +} + +/** + * StoreApi - fetch parameter creator + * @export + */ +export const StoreApiFetchParamCreator = function (configuration?: Configuration) { + return { + /** + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * @summary Delete purchase order by ID + * @param {number} orderId ID of the order that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deleteOrder(orderId: number, options: any = {}): FetchArgs { + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new RequiredError('orderId','Required parameter orderId was null or undefined when calling deleteOrder.'); + } + const localVarPath = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, encodeURIComponent(String(orderId))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'DELETE' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Returns a map of status codes to quantities + * @summary Returns pet inventories by status + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getInventory(options: any = {}): FetchArgs { + const localVarPath = `/store/inventory`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication api_key required + if (configuration && configuration.apiKey) { + const localVarApiKeyValue = typeof configuration.apiKey === 'function' + ? configuration.apiKey("api_key") + : configuration.apiKey; + localVarHeaderParameter["api_key"] = localVarApiKeyValue; + } + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * @summary Find purchase order by ID + * @param {number} orderId ID of pet that needs to be fetched + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getOrderById(orderId: number, options: any = {}): FetchArgs { + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new RequiredError('orderId','Required parameter orderId was null or undefined when calling getOrderById.'); + } + const localVarPath = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, encodeURIComponent(String(orderId))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Place an order for a pet + * @param {Order} body order placed for purchasing the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + placeOrder(body: Order, options: any = {}): FetchArgs { + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling placeOrder.'); + } + const localVarPath = `/store/order`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("Order" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * StoreApi - functional programming interface + * @export + */ +export const StoreApiFp = function(configuration?: Configuration) { + return { + /** + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * @summary Delete purchase order by ID + * @param {number} orderId ID of the order that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deleteOrder(orderId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = StoreApiFetchParamCreator(configuration).deleteOrder(orderId, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Returns a map of status codes to quantities + * @summary Returns pet inventories by status + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getInventory(options?: any): (fetch?: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const localVarFetchArgs = StoreApiFetchParamCreator(configuration).getInventory(options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * @summary Find purchase order by ID + * @param {number} orderId ID of pet that needs to be fetched + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getOrderById(orderId: number, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = StoreApiFetchParamCreator(configuration).getOrderById(orderId, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Place an order for a pet + * @param {Order} body order placed for purchasing the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + placeOrder(body: Order, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = StoreApiFetchParamCreator(configuration).placeOrder(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + } +}; + +/** + * StoreApi - factory interface + * @export + */ +export const StoreApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { + return { + /** + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * @summary Delete purchase order by ID + * @param {number} orderId ID of the order that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deleteOrder(orderId: number, options?: any) { + return StoreApiFp(configuration).deleteOrder(orderId, options)(fetch, basePath); + }, + /** + * Returns a map of status codes to quantities + * @summary Returns pet inventories by status + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getInventory(options?: any) { + return StoreApiFp(configuration).getInventory(options)(fetch, basePath); + }, + /** + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * @summary Find purchase order by ID + * @param {number} orderId ID of pet that needs to be fetched + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getOrderById(orderId: number, options?: any) { + return StoreApiFp(configuration).getOrderById(orderId, options)(fetch, basePath); + }, + /** + * + * @summary Place an order for a pet + * @param {Order} body order placed for purchasing the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + placeOrder(body: Order, options?: any) { + return StoreApiFp(configuration).placeOrder(body, options)(fetch, basePath); + }, + }; +}; + +/** + * StoreApi - object-oriented interface + * @export + * @class StoreApi + * @extends {BaseAPI} + */ +export class StoreApi extends BaseAPI { + /** + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * @summary Delete purchase order by ID + * @param {number} orderId ID of the order that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof StoreApi + */ + public deleteOrder(orderId: number, options?: any) { + return StoreApiFp(this.configuration).deleteOrder(orderId, options)(this.fetch, this.basePath); + } + + /** + * Returns a map of status codes to quantities + * @summary Returns pet inventories by status + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof StoreApi + */ + public getInventory(options?: any) { + return StoreApiFp(this.configuration).getInventory(options)(this.fetch, this.basePath); + } + + /** + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * @summary Find purchase order by ID + * @param {number} orderId ID of pet that needs to be fetched + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof StoreApi + */ + public getOrderById(orderId: number, options?: any) { + return StoreApiFp(this.configuration).getOrderById(orderId, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Place an order for a pet + * @param {Order} body order placed for purchasing the pet + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof StoreApi + */ + public placeOrder(body: Order, options?: any) { + return StoreApiFp(this.configuration).placeOrder(body, options)(this.fetch, this.basePath); + } + +} + +/** + * UserApi - fetch parameter creator + * @export + */ +export const UserApiFetchParamCreator = function (configuration?: Configuration) { + return { + /** + * This can only be done by the logged in user. + * @summary Create user + * @param {User} body Created user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUser(body: User, options: any = {}): FetchArgs { + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling createUser.'); + } + const localVarPath = `/user`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("User" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUsersWithArrayInput(body: Array, options: any = {}): FetchArgs { + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + const localVarPath = `/user/createWithArray`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("Array<User>" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUsersWithListInput(body: Array, options: any = {}): FetchArgs { + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + const localVarPath = `/user/createWithList`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'POST' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("Array<User>" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * This can only be done by the logged in user. + * @summary Delete user + * @param {string} username The name that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deleteUser(username: string, options: any = {}): FetchArgs { + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new RequiredError('username','Required parameter username was null or undefined when calling deleteUser.'); + } + const localVarPath = `/user/{username}` + .replace(`{${"username"}}`, encodeURIComponent(String(username))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'DELETE' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Get user by user name + * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getUserByName(username: string, options: any = {}): FetchArgs { + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new RequiredError('username','Required parameter username was null or undefined when calling getUserByName.'); + } + const localVarPath = `/user/{username}` + .replace(`{${"username"}}`, encodeURIComponent(String(username))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Logs user into the system + * @param {string} username The user name for login + * @param {string} password The password for login in clear text + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + loginUser(username: string, password: string, options: any = {}): FetchArgs { + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new RequiredError('username','Required parameter username was null or undefined when calling loginUser.'); + } + // verify required parameter 'password' is not null or undefined + if (password === null || password === undefined) { + throw new RequiredError('password','Required parameter password was null or undefined when calling loginUser.'); + } + const localVarPath = `/user/login`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (username !== undefined) { + localVarQueryParameter['username'] = username; + } + + if (password !== undefined) { + localVarQueryParameter['password'] = password; + } + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Logs out current logged in user session + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + logoutUser(options: any = {}): FetchArgs { + const localVarPath = `/user/logout`; + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'GET' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * This can only be done by the logged in user. + * @summary Updated user + * @param {string} username name that need to be updated + * @param {User} body Updated user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updateUser(username: string, body: User, options: any = {}): FetchArgs { + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new RequiredError('username','Required parameter username was null or undefined when calling updateUser.'); + } + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new RequiredError('body','Required parameter body was null or undefined when calling updateUser.'); + } + const localVarPath = `/user/{username}` + .replace(`{${"username"}}`, encodeURIComponent(String(username))); + const localVarUrlObj = url.parse(localVarPath, true); + const localVarRequestOptions = Object.assign({ method: 'PUT' }, options); + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); + // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 + delete localVarUrlObj.search; + localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); + const needsSerialization = ("User" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); + + return { + url: url.format(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * UserApi - functional programming interface + * @export + */ +export const UserApiFp = function(configuration?: Configuration) { + return { + /** + * This can only be done by the logged in user. + * @summary Create user + * @param {User} body Created user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUser(body: User, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUser(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUsersWithArrayInput(body: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUsersWithArrayInput(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUsersWithListInput(body: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).createUsersWithListInput(body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * This can only be done by the logged in user. + * @summary Delete user + * @param {string} username The name that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deleteUser(username: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).deleteUser(username, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Get user by user name + * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getUserByName(username: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).getUserByName(username, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Logs user into the system + * @param {string} username The user name for login + * @param {string} password The password for login in clear text + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + loginUser(username: string, password: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).loginUser(username, password, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * + * @summary Logs out current logged in user session + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + logoutUser(options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).logoutUser(options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * This can only be done by the logged in user. + * @summary Updated user + * @param {string} username name that need to be updated + * @param {User} body Updated user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updateUser(username: string, body: User, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = UserApiFetchParamCreator(configuration).updateUser(username, body, options); + return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + } +}; + +/** + * UserApi - factory interface + * @export + */ +export const UserApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { + return { + /** + * This can only be done by the logged in user. + * @summary Create user + * @param {User} body Created user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUser(body: User, options?: any) { + return UserApiFp(configuration).createUser(body, options)(fetch, basePath); + }, + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUsersWithArrayInput(body: Array, options?: any) { + return UserApiFp(configuration).createUsersWithArrayInput(body, options)(fetch, basePath); + }, + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createUsersWithListInput(body: Array, options?: any) { + return UserApiFp(configuration).createUsersWithListInput(body, options)(fetch, basePath); + }, + /** + * This can only be done by the logged in user. + * @summary Delete user + * @param {string} username The name that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + deleteUser(username: string, options?: any) { + return UserApiFp(configuration).deleteUser(username, options)(fetch, basePath); + }, + /** + * + * @summary Get user by user name + * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getUserByName(username: string, options?: any) { + return UserApiFp(configuration).getUserByName(username, options)(fetch, basePath); + }, + /** + * + * @summary Logs user into the system + * @param {string} username The user name for login + * @param {string} password The password for login in clear text + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + loginUser(username: string, password: string, options?: any) { + return UserApiFp(configuration).loginUser(username, password, options)(fetch, basePath); + }, + /** + * + * @summary Logs out current logged in user session + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + logoutUser(options?: any) { + return UserApiFp(configuration).logoutUser(options)(fetch, basePath); + }, + /** + * This can only be done by the logged in user. + * @summary Updated user + * @param {string} username name that need to be updated + * @param {User} body Updated user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updateUser(username: string, body: User, options?: any) { + return UserApiFp(configuration).updateUser(username, body, options)(fetch, basePath); + }, + }; +}; + +/** + * UserApi - object-oriented interface + * @export + * @class UserApi + * @extends {BaseAPI} + */ +export class UserApi extends BaseAPI { + /** + * This can only be done by the logged in user. + * @summary Create user + * @param {User} body Created user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public createUser(body: User, options?: any) { + return UserApiFp(this.configuration).createUser(body, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public createUsersWithArrayInput(body: Array, options?: any) { + return UserApiFp(this.configuration).createUsersWithArrayInput(body, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Creates list of users with given input array + * @param {Array} body List of user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public createUsersWithListInput(body: Array, options?: any) { + return UserApiFp(this.configuration).createUsersWithListInput(body, options)(this.fetch, this.basePath); + } + + /** + * This can only be done by the logged in user. + * @summary Delete user + * @param {string} username The name that needs to be deleted + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public deleteUser(username: string, options?: any) { + return UserApiFp(this.configuration).deleteUser(username, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Get user by user name + * @param {string} username The name that needs to be fetched. Use user1 for testing. + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public getUserByName(username: string, options?: any) { + return UserApiFp(this.configuration).getUserByName(username, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Logs user into the system + * @param {string} username The user name for login + * @param {string} password The password for login in clear text + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public loginUser(username: string, password: string, options?: any) { + return UserApiFp(this.configuration).loginUser(username, password, options)(this.fetch, this.basePath); + } + + /** + * + * @summary Logs out current logged in user session + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public logoutUser(options?: any) { + return UserApiFp(this.configuration).logoutUser(options)(this.fetch, this.basePath); + } + + /** + * This can only be done by the logged in user. + * @summary Updated user + * @param {string} username name that need to be updated + * @param {User} body Updated user object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof UserApi + */ + public updateUser(username: string, body: User, options?: any) { + return UserApiFp(this.configuration).updateUser(username, body, options)(this.fetch, this.basePath); + } + +} + diff --git a/test/generated-clients/typescript-fetch/configuration.ts b/test/generated-clients/typescript-fetch/configuration.ts new file mode 100644 index 00000000..786903cf --- /dev/null +++ b/test/generated-clients/typescript-fetch/configuration.ts @@ -0,0 +1,66 @@ +// tslint:disable +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export interface ConfigurationParameters { + apiKey?: string | ((name: string) => string); + username?: string; + password?: string; + accessToken?: string | ((name: string, scopes?: string[]) => string); + basePath?: string; +} + +export class Configuration { + /** + * parameter for apiKey security + * @param name security name + * @memberof Configuration + */ + apiKey?: string | ((name: string) => string); + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + username?: string; + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + password?: string; + /** + * parameter for oauth2 security + * @param name security name + * @param scopes oauth2 scope + * @memberof Configuration + */ + accessToken?: string | ((name: string, scopes?: string[]) => string); + /** + * override base path + * + * @type {string} + * @memberof Configuration + */ + basePath?: string; + + constructor(param: ConfigurationParameters = {}) { + this.apiKey = param.apiKey; + this.username = param.username; + this.password = param.password; + this.accessToken = param.accessToken; + this.basePath = param.basePath; + } +} diff --git a/test/generated-clients/typescript-fetch/custom.d.ts b/test/generated-clients/typescript-fetch/custom.d.ts new file mode 100644 index 00000000..9a5ceb35 --- /dev/null +++ b/test/generated-clients/typescript-fetch/custom.d.ts @@ -0,0 +1,2 @@ +declare module 'portable-fetch'; +declare module 'url'; \ No newline at end of file diff --git a/test/generated-clients/typescript-fetch/git_push.sh b/test/generated-clients/typescript-fetch/git_push.sh new file mode 100644 index 00000000..a1ff4c9b --- /dev/null +++ b/test/generated-clients/typescript-fetch/git_push.sh @@ -0,0 +1,51 @@ +#!/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" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +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://github.com/${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 + fi + +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" +git push origin master 2>&1 | grep -v 'To https' diff --git a/test/generated-clients/typescript-fetch/index.ts b/test/generated-clients/typescript-fetch/index.ts new file mode 100644 index 00000000..8c192040 --- /dev/null +++ b/test/generated-clients/typescript-fetch/index.ts @@ -0,0 +1,16 @@ +// tslint:disable +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export * from "./api"; +export * from "./configuration"; diff --git a/test/generated-clients/typescript-inversify/.swagger-codegen-ignore b/test/generated-clients/typescript-inversify/.swagger-codegen-ignore new file mode 100644 index 00000000..c5fa491b --- /dev/null +++ b/test/generated-clients/typescript-inversify/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# 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 Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/test/generated-clients/typescript-inversify/.swagger-codegen/VERSION b/test/generated-clients/typescript-inversify/.swagger-codegen/VERSION new file mode 100644 index 00000000..752a79ef --- /dev/null +++ b/test/generated-clients/typescript-inversify/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.8 \ No newline at end of file diff --git a/test/generated-clients/typescript-inversify/ApiServiceBinder.ts b/test/generated-clients/typescript-inversify/ApiServiceBinder.ts new file mode 100644 index 00000000..779a0871 --- /dev/null +++ b/test/generated-clients/typescript-inversify/ApiServiceBinder.ts @@ -0,0 +1,13 @@ +import {interfaces} from "inversify"; + +import { PetService } from './api/pet.service'; +import { StoreService } from './api/store.service'; +import { UserService } from './api/user.service'; + +export class ApiServiceBinder { + public static with(container: interfaces.Container) { + container.bind("PetService").to(PetService).inSingletonScope(); + container.bind("StoreService").to(StoreService).inSingletonScope(); + container.bind("UserService").to(UserService).inSingletonScope(); + } +} diff --git a/test/generated-clients/typescript-inversify/Headers.ts b/test/generated-clients/typescript-inversify/Headers.ts new file mode 100644 index 00000000..0fa7760e --- /dev/null +++ b/test/generated-clients/typescript-inversify/Headers.ts @@ -0,0 +1,3 @@ +export interface Headers { + [index:string]: string +} diff --git a/test/generated-clients/typescript-inversify/HttpClient.ts b/test/generated-clients/typescript-inversify/HttpClient.ts new file mode 100644 index 00000000..64fe12a3 --- /dev/null +++ b/test/generated-clients/typescript-inversify/HttpClient.ts @@ -0,0 +1,63 @@ +import IHttpClient from "./IHttpClient"; +import { Observable } from "rxjs/Observable"; +import "whatwg-fetch"; +import HttpResponse from "./HttpResponse"; +import {injectable} from "inversify"; +import "rxjs/add/observable/fromPromise"; +import { Headers } from "./Headers"; + +@injectable() +class HttpClient implements IHttpClient { + + get(url:string, headers?: Headers):Observable { + return this.performNetworkCall(url, "get", undefined, headers); + } + + post(url: string, body: {}|FormData, headers?: Headers): Observable { + return this.performNetworkCall(url, "post", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + put(url: string, body: {}, headers?: Headers): Observable { + return this.performNetworkCall(url, "put", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + delete(url: string, headers?: Headers): Observable { + return this.performNetworkCall(url, "delete", undefined, headers); + } + + private getJsonBody(body: {}|FormData) { + return !(body instanceof FormData) ? JSON.stringify(body) : body; + } + + private addJsonHeaders(headers: Headers) { + return Object.assign({}, { + "Accept": "application/json", + "Content-Type": "application/json" + }, headers); + }; + + private performNetworkCall(url: string, method: string, body?: any, headers?: Headers): Observable { + let promise = window.fetch(url, { + method: method, + body: body, + headers: headers + }).then(response => { + let headers: Headers = {}; + response.headers.forEach((value, name) => { + headers[name.toString().toLowerCase()] = value; + }); + return response.text().then(text => { + let contentType = headers["content-type"] || ""; + let payload = contentType.match("application/json") ? JSON.parse(text) : text; + let httpResponse = new HttpResponse(payload, response.status, headers); + + if (response.status >= 400) + throw httpResponse; + return httpResponse; + }); + }); + return Observable.fromPromise(promise); + } +} + +export default HttpClient \ No newline at end of file diff --git a/test/generated-clients/typescript-inversify/HttpResponse.ts b/test/generated-clients/typescript-inversify/HttpResponse.ts new file mode 100644 index 00000000..411240cd --- /dev/null +++ b/test/generated-clients/typescript-inversify/HttpResponse.ts @@ -0,0 +1,8 @@ +import { Headers } from "./Headers" + +class HttpResponse { + constructor(public response: T, public status:number, public headers?: Headers) { + } +} + +export default HttpResponse \ No newline at end of file diff --git a/test/generated-clients/typescript-inversify/IAPIConfiguration.ts b/test/generated-clients/typescript-inversify/IAPIConfiguration.ts new file mode 100644 index 00000000..2364e83e --- /dev/null +++ b/test/generated-clients/typescript-inversify/IAPIConfiguration.ts @@ -0,0 +1,8 @@ +export interface IAPIConfiguration { + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; +} \ No newline at end of file diff --git a/test/generated-clients/typescript-inversify/IHttpClient.ts b/test/generated-clients/typescript-inversify/IHttpClient.ts new file mode 100644 index 00000000..22d9e07c --- /dev/null +++ b/test/generated-clients/typescript-inversify/IHttpClient.ts @@ -0,0 +1,12 @@ +import { Observable } from "rxjs/Observable"; +import HttpResponse from "./HttpResponse"; +import { Headers } from "./Headers"; + +interface IHttpClient { + get(url:string, headers?: Headers):Observable + post(url:string, body:{}|FormData, headers?: Headers):Observable + put(url:string, body:{}, headers?: Headers):Observable + delete(url:string, headers?: Headers):Observable +} + +export default IHttpClient \ No newline at end of file diff --git a/test/generated-clients/typescript-inversify/api/pet.service.ts b/test/generated-clients/typescript-inversify/api/pet.service.ts new file mode 100644 index 00000000..2ec09054 --- /dev/null +++ b/test/generated-clients/typescript-inversify/api/pet.service.ts @@ -0,0 +1,319 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Observable } from "rxjs/Observable"; +import 'rxjs/add/operator/map'; +import 'rxjs/add/operator/toPromise'; +import IHttpClient from "../IHttpClient"; +import { inject, injectable } from "inversify"; +import { IAPIConfiguration } from "../IAPIConfiguration"; +import { Headers } from "../Headers"; +import HttpResponse from "../HttpResponse"; + +import { ApiResponse } from '../model/apiResponse'; +import { Pet } from '../model/pet'; + +import { COLLECTION_FORMATS } from '../variables'; + + + +@injectable() +export class PetService { + private basePath: string = 'https://petstore.swagger.io/v2'; + + constructor(@inject("IApiHttpClient") private httpClient: IHttpClient, + @inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) { + if(this.APIConfiguration.basePath) + this.basePath = this.APIConfiguration.basePath; + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + + */ + public addPet(body: Pet, observe?: 'body', headers?: Headers): Observable; + public addPet(body: Pet, observe?: 'response', headers?: Headers): Observable>; + public addPet(body: Pet, observe: any = 'body', headers: Headers = {}): Observable { + if (!body){ + throw new Error('Required parameter body was null or undefined when calling addPet.'); + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.post(`${this.basePath}/pet`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + + */ + public deletePet(petId: number, apiKey?: string, observe?: 'body', headers?: Headers): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', headers?: Headers): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!petId){ + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + if (apiKey) { + headers['api_key'] = String(apiKey); + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.delete(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter + + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', headers?: Headers): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', headers?: Headers): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', headers: Headers = {}): Observable { + if (!status){ + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + let queryParameters: string[] = []; + if (status) { + status.forEach((element) => { + queryParameters.push("status="+encodeURIComponent(String(status))); + }) + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/xml'; + + const response: Observable>> = this.httpClient.get(`${this.basePath}/pet/findByStatus?${queryParameters.join('&')}`, headers); + if (observe == 'body') { + return response.map(httpResponse => >(httpResponse.response)); + } + return response; + } + + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + + */ + public findPetsByTags(tags: Array, observe?: 'body', headers?: Headers): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', headers?: Headers): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', headers: Headers = {}): Observable { + if (!tags){ + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + let queryParameters: string[] = []; + if (tags) { + tags.forEach((element) => { + queryParameters.push("tags="+encodeURIComponent(String(tags))); + }) + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/xml'; + + const response: Observable>> = this.httpClient.get(`${this.basePath}/pet/findByTags?${queryParameters.join('&')}`, headers); + if (observe == 'body') { + return response.map(httpResponse => >(httpResponse.response)); + } + return response; + } + + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + + */ + public getPetById(petId: number, observe?: 'body', headers?: Headers): Observable; + public getPetById(petId: number, observe?: 'response', headers?: Headers): Observable>; + public getPetById(petId: number, observe: any = 'body', headers: Headers = {}): Observable { + if (!petId){ + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + // authentication (api_key) required + if (this.APIConfiguration.apiKeys["api_key"]) { + headers['api_key'] = this.APIConfiguration.apiKeys["api_key"]; + } + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + + */ + public updatePet(body: Pet, observe?: 'body', headers?: Headers): Observable; + public updatePet(body: Pet, observe?: 'response', headers?: Headers): Observable>; + public updatePet(body: Pet, observe: any = 'body', headers: Headers = {}): Observable { + if (!body){ + throw new Error('Required parameter body was null or undefined when calling updatePet.'); + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.put(`${this.basePath}/pet`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + + */ + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', headers?: Headers): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', headers?: Headers): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!petId){ + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/xml'; + + let formData: FormData = new FormData(); + headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; + if (name !== undefined) { + formData.append('name', name); + } + if (status !== undefined) { + formData.append('status', status); + } + + const response: Observable> = this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, body, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', headers?: Headers): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', headers?: Headers): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', headers: Headers = {}): Observable { + if (!petId){ + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + // authentication (petstore_auth) required + if (this.APIConfiguration.accessToken) { + let accessToken = typeof this.APIConfiguration.accessToken === 'function' + ? this.APIConfiguration.accessToken() + : this.APIConfiguration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + headers['Accept'] = 'application/json'; + + let formData: FormData = new FormData(); + headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; + if (additionalMetadata !== undefined) { + formData.append('additionalMetadata', additionalMetadata); + } + if (file !== undefined) { + formData.append('file', file); + } + + const response: Observable> = this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, body, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + +} diff --git a/test/generated-clients/typescript-inversify/api/store.service.ts b/test/generated-clients/typescript-inversify/api/store.service.ts new file mode 100644 index 00000000..93faed1a --- /dev/null +++ b/test/generated-clients/typescript-inversify/api/store.service.ts @@ -0,0 +1,130 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Observable } from "rxjs/Observable"; +import 'rxjs/add/operator/map'; +import 'rxjs/add/operator/toPromise'; +import IHttpClient from "../IHttpClient"; +import { inject, injectable } from "inversify"; +import { IAPIConfiguration } from "../IAPIConfiguration"; +import { Headers } from "../Headers"; +import HttpResponse from "../HttpResponse"; + +import { Order } from '../model/order'; + +import { COLLECTION_FORMATS } from '../variables'; + + + +@injectable() +export class StoreService { + private basePath: string = 'https://petstore.swagger.io/v2'; + + constructor(@inject("IApiHttpClient") private httpClient: IHttpClient, + @inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) { + if(this.APIConfiguration.basePath) + this.basePath = this.APIConfiguration.basePath; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * @param orderId ID of the order that needs to be deleted + + */ + public deleteOrder(orderId: number, observe?: 'body', headers?: Headers): Observable; + public deleteOrder(orderId: number, observe?: 'response', headers?: Headers): Observable>; + public deleteOrder(orderId: number, observe: any = 'body', headers: Headers = {}): Observable { + if (!orderId){ + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.delete(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + + */ + public getInventory(observe?: 'body', headers?: Headers): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', headers?: Headers): Observable>; + public getInventory(observe: any = 'body', headers: Headers = {}): Observable { + // authentication (api_key) required + if (this.APIConfiguration.apiKeys["api_key"]) { + headers['api_key'] = this.APIConfiguration.apiKeys["api_key"]; + } + headers['Accept'] = 'application/json'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/store/inventory`, headers); + if (observe == 'body') { + return response.map(httpResponse => <{ [key: string]: number; }>(httpResponse.response)); + } + return response; + } + + + /** + * Find purchase order by ID + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + + */ + public getOrderById(orderId: number, observe?: 'body', headers?: Headers): Observable; + public getOrderById(orderId: number, observe?: 'response', headers?: Headers): Observable>; + public getOrderById(orderId: number, observe: any = 'body', headers: Headers = {}): Observable { + if (!orderId){ + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + + */ + public placeOrder(body: Order, observe?: 'body', headers?: Headers): Observable; + public placeOrder(body: Order, observe?: 'response', headers?: Headers): Observable>; + public placeOrder(body: Order, observe: any = 'body', headers: Headers = {}): Observable { + if (!body){ + throw new Error('Required parameter body was null or undefined when calling placeOrder.'); + } + + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.post(`${this.basePath}/store/order`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + +} diff --git a/test/generated-clients/typescript-inversify/api/user.service.ts b/test/generated-clients/typescript-inversify/api/user.service.ts new file mode 100644 index 00000000..e2364cb3 --- /dev/null +++ b/test/generated-clients/typescript-inversify/api/user.service.ts @@ -0,0 +1,239 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Observable } from "rxjs/Observable"; +import 'rxjs/add/operator/map'; +import 'rxjs/add/operator/toPromise'; +import IHttpClient from "../IHttpClient"; +import { inject, injectable } from "inversify"; +import { IAPIConfiguration } from "../IAPIConfiguration"; +import { Headers } from "../Headers"; +import HttpResponse from "../HttpResponse"; + +import { User } from '../model/user'; + +import { COLLECTION_FORMATS } from '../variables'; + + + +@injectable() +export class UserService { + private basePath: string = 'https://petstore.swagger.io/v2'; + + constructor(@inject("IApiHttpClient") private httpClient: IHttpClient, + @inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) { + if(this.APIConfiguration.basePath) + this.basePath = this.APIConfiguration.basePath; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + + */ + public createUser(body: User, observe?: 'body', headers?: Headers): Observable; + public createUser(body: User, observe?: 'response', headers?: Headers): Observable>; + public createUser(body: User, observe: any = 'body', headers: Headers = {}): Observable { + if (!body){ + throw new Error('Required parameter body was null or undefined when calling createUser.'); + } + + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.post(`${this.basePath}/user`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Creates list of users with given input array + * + * @param body List of user object + + */ + public createUsersWithArrayInput(body: Array, observe?: 'body', headers?: Headers): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', headers?: Headers): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', headers: Headers = {}): Observable { + if (!body){ + throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.post(`${this.basePath}/user/createWithArray`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Creates list of users with given input array + * + * @param body List of user object + + */ + public createUsersWithListInput(body: Array, observe?: 'body', headers?: Headers): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', headers?: Headers): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', headers: Headers = {}): Observable { + if (!body){ + throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.post(`${this.basePath}/user/createWithList`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + + */ + public deleteUser(username: string, observe?: 'body', headers?: Headers): Observable; + public deleteUser(username: string, observe?: 'response', headers?: Headers): Observable>; + public deleteUser(username: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!username){ + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.delete(`${this.basePath}/user/${encodeURIComponent(String(username))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + + */ + public getUserByName(username: string, observe?: 'body', headers?: Headers): Observable; + public getUserByName(username: string, observe?: 'response', headers?: Headers): Observable>; + public getUserByName(username: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!username){ + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/user/${encodeURIComponent(String(username))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + + */ + public loginUser(username: string, password: string, observe?: 'body', headers?: Headers): Observable; + public loginUser(username: string, password: string, observe?: 'response', headers?: Headers): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!username){ + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + + if (!password){ + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + let queryParameters: string[] = []; + if (username !== undefined) { + queryParameters.push("username="+encodeURIComponent(String(username))); + } + if (password !== undefined) { + queryParameters.push("password="+encodeURIComponent(String(password))); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/user/login?${queryParameters.join('&')}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Logs out current logged in user session + * + + */ + public logoutUser(observe?: 'body', headers?: Headers): Observable; + public logoutUser(observe?: 'response', headers?: Headers): Observable>; + public logoutUser(observe: any = 'body', headers: Headers = {}): Observable { + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/user/logout`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be updated + * @param body Updated user object + + */ + public updateUser(username: string, body: User, observe?: 'body', headers?: Headers): Observable; + public updateUser(username: string, body: User, observe?: 'response', headers?: Headers): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', headers: Headers = {}): Observable { + if (!username){ + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + + if (!body){ + throw new Error('Required parameter body was null or undefined when calling updateUser.'); + } + + headers['Accept'] = 'application/xml'; + headers['Content-Type'] = 'application/json'; + + const response: Observable> = this.httpClient.put(`${this.basePath}/user/${encodeURIComponent(String(username))}`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + +} diff --git a/test/generated-clients/typescript-inversify/model/apiResponse.ts b/test/generated-clients/typescript-inversify/model/apiResponse.ts new file mode 100644 index 00000000..fda53fa6 --- /dev/null +++ b/test/generated-clients/typescript-inversify/model/apiResponse.ts @@ -0,0 +1,18 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} diff --git a/test/generated-clients/typescript-inversify/model/category.ts b/test/generated-clients/typescript-inversify/model/category.ts new file mode 100644 index 00000000..ce6c6530 --- /dev/null +++ b/test/generated-clients/typescript-inversify/model/category.ts @@ -0,0 +1,17 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export interface Category { + id?: number; + name?: string; +} diff --git a/test/generated-clients/typescript-inversify/model/order.ts b/test/generated-clients/typescript-inversify/model/order.ts new file mode 100644 index 00000000..fc1ab6d6 --- /dev/null +++ b/test/generated-clients/typescript-inversify/model/order.ts @@ -0,0 +1,32 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: Date; + /** + * Order Status + */ + status?: Order.StatusEnum; + complete?: boolean; +} +export namespace Order { + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + } +} diff --git a/test/generated-clients/typescript-inversify/model/pet.ts b/test/generated-clients/typescript-inversify/model/pet.ts new file mode 100644 index 00000000..5124b515 --- /dev/null +++ b/test/generated-clients/typescript-inversify/model/pet.ts @@ -0,0 +1,34 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ +import { Category } from './category'; +import { Tag } from './tag'; + + +export interface Pet { + id?: number; + category?: Category; + name: string; + photoUrls: Array; + tags?: Array; + /** + * pet status in the store + */ + status?: Pet.StatusEnum; +} +export namespace Pet { + export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + } +} diff --git a/test/generated-clients/typescript-inversify/model/tag.ts b/test/generated-clients/typescript-inversify/model/tag.ts new file mode 100644 index 00000000..f4f97406 --- /dev/null +++ b/test/generated-clients/typescript-inversify/model/tag.ts @@ -0,0 +1,17 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export interface Tag { + id?: number; + name?: string; +} diff --git a/test/generated-clients/typescript-inversify/model/user.ts b/test/generated-clients/typescript-inversify/model/user.ts new file mode 100644 index 00000000..9e5f119a --- /dev/null +++ b/test/generated-clients/typescript-inversify/model/user.ts @@ -0,0 +1,26 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} diff --git a/test/generated-clients/typescript-inversify/variables.ts b/test/generated-clients/typescript-inversify/variables.ts new file mode 100644 index 00000000..5d380525 --- /dev/null +++ b/test/generated-clients/typescript-inversify/variables.ts @@ -0,0 +1,6 @@ +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/test/generated-clients/typescript-jquery/.swagger-codegen-ignore b/test/generated-clients/typescript-jquery/.swagger-codegen-ignore new file mode 100644 index 00000000..c5fa491b --- /dev/null +++ b/test/generated-clients/typescript-jquery/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# 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 Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/test/generated-clients/typescript-jquery/.swagger-codegen/VERSION b/test/generated-clients/typescript-jquery/.swagger-codegen/VERSION new file mode 100644 index 00000000..752a79ef --- /dev/null +++ b/test/generated-clients/typescript-jquery/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.8 \ No newline at end of file diff --git a/test/generated-clients/typescript-jquery/api/PetApi.ts b/test/generated-clients/typescript-jquery/api/PetApi.ts new file mode 100644 index 00000000..3a025901 --- /dev/null +++ b/test/generated-clients/typescript-jquery/api/PetApi.ts @@ -0,0 +1,634 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +import * as $ from 'jquery'; +import * as models from '../model/models'; +import { COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + +/* tslint:disable:no-unused-variable member-ordering */ + + +export class PetApi { + protected basePath = 'https://petstore.swagger.io/v2'; + public defaultHeaders: Array = []; + public defaultExtraJQueryAjaxSettings?: JQueryAjaxSettings = null; + public configuration: Configuration = new Configuration(); + + constructor(basePath?: string, configuration?: Configuration, defaultExtraJQueryAjaxSettings?: JQueryAjaxSettings) { + if (basePath) { + this.basePath = basePath; + } + if (configuration) { + this.configuration = configuration; + } + if (defaultExtraJQueryAjaxSettings) { + this.defaultExtraJQueryAjaxSettings = defaultExtraJQueryAjaxSettings; + } + } + + private extendObj(objA: T2, objB: T2): T1|T2 { + for (let key in objB) { + if (objB.hasOwnProperty(key)) { + objA[key] = objB[key]; + } + } + return objA; + } + + /** + * + * @summary Add a new pet to the store + * @param body Pet object that needs to be added to the store + */ + public addPet(body: models.Pet, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body?: any; }> { + let localVarPath = this.basePath + '/pet'; + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling addPet.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + // authentication (petstore_auth) required + // oauth required + if (this.configuration.accessToken) { + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headerParams['Authorization'] = 'Bearer ' + accessToken; + } + + + headerParams['Content-Type'] = 'application/json'; + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'POST', + headers: headerParams, + processData: false + }; + + requestOptions.data = JSON.stringify(body); + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: any, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * + * @summary Deletes a pet + * @param petId Pet id to delete + * @param apiKey + */ + public deletePet(petId: number, apiKey?: string, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body?: any; }> { + let localVarPath = this.basePath + '/pet/{petId}'.replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + headerParams['api_key'] = String(apiKey); + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + // authentication (petstore_auth) required + // oauth required + if (this.configuration.accessToken) { + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headerParams['Authorization'] = 'Bearer ' + accessToken; + } + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'DELETE', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: any, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * Multiple status values can be provided with comma separated strings + * @summary Finds Pets by status + * @param status Status values that need to be considered for filter + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body: Array; }> { + let localVarPath = this.basePath + '/pet/findByStatus'; + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'status' is not null or undefined + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + if (status) { + status.forEach((element: any) => { + queryParameters['status'].push(element); + }); + } + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + // authentication (petstore_auth) required + // oauth required + if (this.configuration.accessToken) { + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headerParams['Authorization'] = 'Bearer ' + accessToken; + } + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'GET', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: Array, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @summary Finds Pets by tags + * @param tags Tags to filter by + */ + public findPetsByTags(tags: Array, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body: Array; }> { + let localVarPath = this.basePath + '/pet/findByTags'; + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'tags' is not null or undefined + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + if (tags) { + tags.forEach((element: any) => { + queryParameters['tags'].push(element); + }); + } + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + // authentication (petstore_auth) required + // oauth required + if (this.configuration.accessToken) { + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headerParams['Authorization'] = 'Bearer ' + accessToken; + } + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'GET', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: Array, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * Returns a single pet + * @summary Find pet by ID + * @param petId ID of pet to return + */ + public getPetById(petId: number, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body: models.Pet; }> { + let localVarPath = this.basePath + '/pet/{petId}'.replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + // authentication (api_key) required + if (this.configuration.apiKey) { + headerParams['api_key'] = this.configuration.apiKey; + } + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'GET', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: models.Pet, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * + * @summary Update an existing pet + * @param body Pet object that needs to be added to the store + */ + public updatePet(body: models.Pet, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body?: any; }> { + let localVarPath = this.basePath + '/pet'; + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updatePet.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + // authentication (petstore_auth) required + // oauth required + if (this.configuration.accessToken) { + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headerParams['Authorization'] = 'Bearer ' + accessToken; + } + + + headerParams['Content-Type'] = 'application/json'; + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'PUT', + headers: headerParams, + processData: false + }; + + requestOptions.data = JSON.stringify(body); + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: any, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * + * @summary Updates a pet in the store with form data + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + public updatePetWithForm(petId: number, name?: string, status?: string, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body?: any; }> { + let localVarPath = this.basePath + '/pet/{petId}'.replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + + let queryParameters: any = {}; + let headerParams: any = {}; + let formParams = new FormData(); + let reqHasFile = false; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + if (name !== null && name !== undefined) { + formParams.append('name', name); + } + if (status !== null && status !== undefined) { + formParams.append('status', status); + } + // to determine the Content-Type header + let consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + // authentication (petstore_auth) required + // oauth required + if (this.configuration.accessToken) { + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headerParams['Authorization'] = 'Bearer ' + accessToken; + } + + if (!reqHasFile) { + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + } + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'POST', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + requestOptions.data = formParams; + if (reqHasFile) { + requestOptions.contentType = false; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: any, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * + * @summary uploads an image + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: any, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body: models.ApiResponse; }> { + let localVarPath = this.basePath + '/pet/{petId}/uploadImage'.replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + + let queryParameters: any = {}; + let headerParams: any = {}; + let formParams = new FormData(); + let reqHasFile = false; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + if (additionalMetadata !== null && additionalMetadata !== undefined) { + formParams.append('additionalMetadata', additionalMetadata); + } + reqHasFile = true; + formParams.append("file", file); + // to determine the Content-Type header + let consumes: string[] = [ + 'multipart/form-data' + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json' + ]; + + // authentication (petstore_auth) required + // oauth required + if (this.configuration.accessToken) { + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headerParams['Authorization'] = 'Bearer ' + accessToken; + } + + if (!reqHasFile) { + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + } + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'POST', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + requestOptions.data = formParams; + if (reqHasFile) { + requestOptions.contentType = false; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: models.ApiResponse, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + +} diff --git a/test/generated-clients/typescript-jquery/api/StoreApi.ts b/test/generated-clients/typescript-jquery/api/StoreApi.ts new file mode 100644 index 00000000..ef466151 --- /dev/null +++ b/test/generated-clients/typescript-jquery/api/StoreApi.ts @@ -0,0 +1,278 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +import * as $ from 'jquery'; +import * as models from '../model/models'; +import { COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + +/* tslint:disable:no-unused-variable member-ordering */ + + +export class StoreApi { + protected basePath = 'https://petstore.swagger.io/v2'; + public defaultHeaders: Array = []; + public defaultExtraJQueryAjaxSettings?: JQueryAjaxSettings = null; + public configuration: Configuration = new Configuration(); + + constructor(basePath?: string, configuration?: Configuration, defaultExtraJQueryAjaxSettings?: JQueryAjaxSettings) { + if (basePath) { + this.basePath = basePath; + } + if (configuration) { + this.configuration = configuration; + } + if (defaultExtraJQueryAjaxSettings) { + this.defaultExtraJQueryAjaxSettings = defaultExtraJQueryAjaxSettings; + } + } + + private extendObj(objA: T2, objB: T2): T1|T2 { + for (let key in objB) { + if (objB.hasOwnProperty(key)) { + objA[key] = objB[key]; + } + } + return objA; + } + + /** + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * @summary Delete purchase order by ID + * @param orderId ID of the order that needs to be deleted + */ + public deleteOrder(orderId: number, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body?: any; }> { + let localVarPath = this.basePath + '/store/order/{orderId}'.replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'DELETE', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: any, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * Returns a map of status codes to quantities + * @summary Returns pet inventories by status + */ + public getInventory(extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body: { [key: string]: number; }; }> { + let localVarPath = this.basePath + '/store/inventory'; + + let queryParameters: any = {}; + let headerParams: any = {}; + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json' + ]; + + // authentication (api_key) required + if (this.configuration.apiKey) { + headerParams['api_key'] = this.configuration.apiKey; + } + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'GET', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: { [key: string]: number; }, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * @summary Find purchase order by ID + * @param orderId ID of pet that needs to be fetched + */ + public getOrderById(orderId: number, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body: models.Order; }> { + let localVarPath = this.basePath + '/store/order/{orderId}'.replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'GET', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: models.Order, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * + * @summary Place an order for a pet + * @param body order placed for purchasing the pet + */ + public placeOrder(body: models.Order, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body: models.Order; }> { + let localVarPath = this.basePath + '/store/order'; + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling placeOrder.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + + headerParams['Content-Type'] = 'application/json'; + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'POST', + headers: headerParams, + processData: false + }; + + requestOptions.data = JSON.stringify(body); + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: models.Order, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + +} diff --git a/test/generated-clients/typescript-jquery/api/UserApi.ts b/test/generated-clients/typescript-jquery/api/UserApi.ts new file mode 100644 index 00000000..b1f500dd --- /dev/null +++ b/test/generated-clients/typescript-jquery/api/UserApi.ts @@ -0,0 +1,529 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +import * as $ from 'jquery'; +import * as models from '../model/models'; +import { COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + +/* tslint:disable:no-unused-variable member-ordering */ + + +export class UserApi { + protected basePath = 'https://petstore.swagger.io/v2'; + public defaultHeaders: Array = []; + public defaultExtraJQueryAjaxSettings?: JQueryAjaxSettings = null; + public configuration: Configuration = new Configuration(); + + constructor(basePath?: string, configuration?: Configuration, defaultExtraJQueryAjaxSettings?: JQueryAjaxSettings) { + if (basePath) { + this.basePath = basePath; + } + if (configuration) { + this.configuration = configuration; + } + if (defaultExtraJQueryAjaxSettings) { + this.defaultExtraJQueryAjaxSettings = defaultExtraJQueryAjaxSettings; + } + } + + private extendObj(objA: T2, objB: T2): T1|T2 { + for (let key in objB) { + if (objB.hasOwnProperty(key)) { + objA[key] = objB[key]; + } + } + return objA; + } + + /** + * This can only be done by the logged in user. + * @summary Create user + * @param body Created user object + */ + public createUser(body: models.User, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body?: any; }> { + let localVarPath = this.basePath + '/user'; + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUser.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + + headerParams['Content-Type'] = 'application/json'; + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'POST', + headers: headerParams, + processData: false + }; + + requestOptions.data = JSON.stringify(body); + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: any, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * + * @summary Creates list of users with given input array + * @param body List of user object + */ + public createUsersWithArrayInput(body: Array, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body?: any; }> { + let localVarPath = this.basePath + '/user/createWithArray'; + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + + headerParams['Content-Type'] = 'application/json'; + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'POST', + headers: headerParams, + processData: false + }; + + requestOptions.data = JSON.stringify(body); + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: any, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * + * @summary Creates list of users with given input array + * @param body List of user object + */ + public createUsersWithListInput(body: Array, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body?: any; }> { + let localVarPath = this.basePath + '/user/createWithList'; + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + + headerParams['Content-Type'] = 'application/json'; + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'POST', + headers: headerParams, + processData: false + }; + + requestOptions.data = JSON.stringify(body); + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: any, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * This can only be done by the logged in user. + * @summary Delete user + * @param username The name that needs to be deleted + */ + public deleteUser(username: string, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body?: any; }> { + let localVarPath = this.basePath + '/user/{username}'.replace('{' + 'username' + '}', encodeURIComponent(String(username))); + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'DELETE', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: any, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * + * @summary Get user by user name + * @param username The name that needs to be fetched. Use user1 for testing. + */ + public getUserByName(username: string, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body: models.User; }> { + let localVarPath = this.basePath + '/user/{username}'.replace('{' + 'username' + '}', encodeURIComponent(String(username))); + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'GET', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: models.User, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * + * @summary Logs user into the system + * @param username The user name for login + * @param password The password for login in clear text + */ + public loginUser(username: string, password: string, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body: string; }> { + let localVarPath = this.basePath + '/user/login'; + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + + // verify required parameter 'password' is not null or undefined + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + if (username !== null && username !== undefined) { + queryParameters['username'] = username; + } + if (password !== null && password !== undefined) { + queryParameters['password'] = password; + } + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'GET', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: string, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * + * @summary Logs out current logged in user session + */ + public logoutUser(extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body?: any; }> { + let localVarPath = this.basePath + '/user/logout'; + + let queryParameters: any = {}; + let headerParams: any = {}; + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'GET', + headers: headerParams, + processData: false + }; + + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: any, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + + /** + * This can only be done by the logged in user. + * @summary Updated user + * @param username name that need to be updated + * @param body Updated user object + */ + public updateUser(username: string, body: models.User, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQueryPromise<{ response: JQueryXHR; body?: any; }> { + let localVarPath = this.basePath + '/user/{username}'.replace('{' + 'username' + '}', encodeURIComponent(String(username))); + + let queryParameters: any = {}; + let headerParams: any = {}; + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updateUser.'); + } + + + localVarPath = localVarPath + "?" + $.param(queryParameters); + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/xml', + 'application/json' + ]; + + + headerParams['Content-Type'] = 'application/json'; + + let requestOptions: JQueryAjaxSettings = { + url: localVarPath, + type: 'PUT', + headers: headerParams, + processData: false + }; + + requestOptions.data = JSON.stringify(body); + if (headerParams['Content-Type']) { + requestOptions.contentType = headerParams['Content-Type']; + } + + if (extraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, extraJQueryAjaxSettings); + } + + if (this.defaultExtraJQueryAjaxSettings) { + requestOptions = (Object).assign(requestOptions, this.defaultExtraJQueryAjaxSettings); + } + + let dfd = $.Deferred(); + $.ajax(requestOptions).then( + (data: any, textStatus: string, jqXHR: JQueryXHR) => + dfd.resolve(jqXHR, data), + (xhr: JQueryXHR, textStatus: string, errorThrown: string) => + dfd.reject(xhr, errorThrown) + ); + return dfd.promise(); + } + +} diff --git a/test/generated-clients/typescript-jquery/api/api.ts b/test/generated-clients/typescript-jquery/api/api.ts new file mode 100644 index 00000000..4ddd9e29 --- /dev/null +++ b/test/generated-clients/typescript-jquery/api/api.ts @@ -0,0 +1,7 @@ +export * from './PetApi'; +import { PetApi } from './PetApi'; +export * from './StoreApi'; +import { StoreApi } from './StoreApi'; +export * from './UserApi'; +import { UserApi } from './UserApi'; +export const APIS = [PetApi, StoreApi, UserApi]; diff --git a/test/generated-clients/typescript-jquery/configuration.ts b/test/generated-clients/typescript-jquery/configuration.ts new file mode 100644 index 00000000..a566a180 --- /dev/null +++ b/test/generated-clients/typescript-jquery/configuration.ts @@ -0,0 +1,6 @@ +export class Configuration { + apiKey: string; + username: string; + password: string; + accessToken: string | (() => string); +} \ No newline at end of file diff --git a/test/generated-clients/typescript-jquery/git_push.sh b/test/generated-clients/typescript-jquery/git_push.sh new file mode 100644 index 00000000..ae01b182 --- /dev/null +++ b/test/generated-clients/typescript-jquery/git_push.sh @@ -0,0 +1,52 @@ +#!/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" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +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://github.com/${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 + fi + +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" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/test/generated-clients/typescript-jquery/index.ts b/test/generated-clients/typescript-jquery/index.ts new file mode 100644 index 00000000..d097c728 --- /dev/null +++ b/test/generated-clients/typescript-jquery/index.ts @@ -0,0 +1,4 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; \ No newline at end of file diff --git a/test/generated-clients/typescript-jquery/model/ApiResponse.ts b/test/generated-clients/typescript-jquery/model/ApiResponse.ts new file mode 100644 index 00000000..8e21c889 --- /dev/null +++ b/test/generated-clients/typescript-jquery/model/ApiResponse.ts @@ -0,0 +1,22 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from './models'; + +export interface ApiResponse { + code?: number; + + type?: string; + + message?: string; + +} diff --git a/test/generated-clients/typescript-jquery/model/Category.ts b/test/generated-clients/typescript-jquery/model/Category.ts new file mode 100644 index 00000000..848c7b46 --- /dev/null +++ b/test/generated-clients/typescript-jquery/model/Category.ts @@ -0,0 +1,20 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from './models'; + +export interface Category { + id?: number; + + name?: string; + +} diff --git a/test/generated-clients/typescript-jquery/model/Order.ts b/test/generated-clients/typescript-jquery/model/Order.ts new file mode 100644 index 00000000..bffb6feb --- /dev/null +++ b/test/generated-clients/typescript-jquery/model/Order.ts @@ -0,0 +1,38 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from './models'; + +export interface Order { + id?: number; + + petId?: number; + + quantity?: number; + + shipDate?: Date; + + /** + * Order Status + */ + status?: Order.StatusEnum; + + complete?: boolean; + +} +export namespace Order { + export enum StatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' + } +} diff --git a/test/generated-clients/typescript-jquery/model/Pet.ts b/test/generated-clients/typescript-jquery/model/Pet.ts new file mode 100644 index 00000000..85642d62 --- /dev/null +++ b/test/generated-clients/typescript-jquery/model/Pet.ts @@ -0,0 +1,38 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from './models'; + +export interface Pet { + id?: number; + + category?: models.Category; + + name: string; + + photoUrls: Array; + + tags?: Array; + + /** + * pet status in the store + */ + status?: Pet.StatusEnum; + +} +export namespace Pet { + export enum StatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' + } +} diff --git a/test/generated-clients/typescript-jquery/model/Tag.ts b/test/generated-clients/typescript-jquery/model/Tag.ts new file mode 100644 index 00000000..5ae152eb --- /dev/null +++ b/test/generated-clients/typescript-jquery/model/Tag.ts @@ -0,0 +1,20 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from './models'; + +export interface Tag { + id?: number; + + name?: string; + +} diff --git a/test/generated-clients/typescript-jquery/model/User.ts b/test/generated-clients/typescript-jquery/model/User.ts new file mode 100644 index 00000000..d5921fe8 --- /dev/null +++ b/test/generated-clients/typescript-jquery/model/User.ts @@ -0,0 +1,35 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from './models'; + +export interface User { + id?: number; + + username?: string; + + firstName?: string; + + lastName?: string; + + email?: string; + + password?: string; + + phone?: string; + + /** + * User Status + */ + userStatus?: number; + +} diff --git a/test/generated-clients/typescript-jquery/model/models.ts b/test/generated-clients/typescript-jquery/model/models.ts new file mode 100644 index 00000000..f53c1dd4 --- /dev/null +++ b/test/generated-clients/typescript-jquery/model/models.ts @@ -0,0 +1,6 @@ +export * from './ApiResponse'; +export * from './Category'; +export * from './Order'; +export * from './Pet'; +export * from './Tag'; +export * from './User'; diff --git a/test/generated-clients/typescript-jquery/variables.ts b/test/generated-clients/typescript-jquery/variables.ts new file mode 100644 index 00000000..505ce935 --- /dev/null +++ b/test/generated-clients/typescript-jquery/variables.ts @@ -0,0 +1,7 @@ + +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} \ No newline at end of file diff --git a/test/generated-clients/typescript-node/.gitignore b/test/generated-clients/typescript-node/.gitignore new file mode 100644 index 00000000..35e2fb2b --- /dev/null +++ b/test/generated-clients/typescript-node/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/test/generated-clients/typescript-node/.swagger-codegen-ignore b/test/generated-clients/typescript-node/.swagger-codegen-ignore new file mode 100644 index 00000000..c5fa491b --- /dev/null +++ b/test/generated-clients/typescript-node/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# 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 Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/test/generated-clients/typescript-node/.swagger-codegen/VERSION b/test/generated-clients/typescript-node/.swagger-codegen/VERSION new file mode 100644 index 00000000..752a79ef --- /dev/null +++ b/test/generated-clients/typescript-node/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.8 \ No newline at end of file diff --git a/test/generated-clients/typescript-node/api.ts b/test/generated-clients/typescript-node/api.ts new file mode 100644 index 00000000..50a3e378 --- /dev/null +++ b/test/generated-clients/typescript-node/api.ts @@ -0,0 +1,1754 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.2 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import localVarRequest = require('request'); +import http = require('http'); +import Promise = require('bluebird'); + +let defaultBasePath = 'https://petstore.swagger.io/v2'; + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +/* tslint:disable:no-unused-variable */ +let primitives = [ + "string", + "boolean", + "double", + "integer", + "long", + "float", + "number", + "any" + ]; + +class ObjectSerializer { + + public static findCorrectType(data: any, expectedType: string) { + if (data == undefined) { + return expectedType; + } else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) { + return expectedType; + } else if (expectedType === "Date") { + return expectedType; + } else { + if (enumsMap[expectedType]) { + return expectedType; + } + + if (!typeMap[expectedType]) { + return expectedType; // w/e we don't know the type + } + + // Check the discriminator + let discriminatorProperty = typeMap[expectedType].discriminator; + if (discriminatorProperty == null) { + return expectedType; // the type does not have a discriminator. use it. + } else { + if (data[discriminatorProperty]) { + return data[discriminatorProperty]; // use the type given in the discriminator + } else { + return expectedType; // discriminator was not present (or an empty string) + } + } + } + } + + public static serialize(data: any, type: string) { + if (data == undefined) { + return data; + } else if (primitives.indexOf(type.toLowerCase()) !== -1) { + return data; + } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 + let subType: string = type.replace("Array<", ""); // Array => Type> + subType = subType.substring(0, subType.length - 1); // Type> => Type + let transformedData: any[] = []; + for (let index in data) { + let date = data[index]; + transformedData.push(ObjectSerializer.serialize(date, subType)); + } + return transformedData; + } else if (type === "Date") { + return data.toString(); + } else { + if (enumsMap[type]) { + return data; + } + if (!typeMap[type]) { // in case we dont know the type + return data; + } + + // get the map for the correct type. + let attributeTypes = typeMap[type].getAttributeTypeMap(); + let instance: {[index: string]: any} = {}; + for (let index in attributeTypes) { + let attributeType = attributeTypes[index]; + instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type); + } + return instance; + } + } + + public static deserialize(data: any, type: string) { + // polymorphism may change the actual type. + type = ObjectSerializer.findCorrectType(data, type); + if (data == undefined) { + return data; + } else if (primitives.indexOf(type.toLowerCase()) !== -1) { + return data; + } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 + let subType: string = type.replace("Array<", ""); // Array => Type> + subType = subType.substring(0, subType.length - 1); // Type> => Type + let transformedData: any[] = []; + for (let index in data) { + let date = data[index]; + transformedData.push(ObjectSerializer.deserialize(date, subType)); + } + return transformedData; + } else if (type === "Date") { + return new Date(data); + } else { + if (enumsMap[type]) {// is Enum + return data; + } + + if (!typeMap[type]) { // dont know the type + return data; + } + let instance = new typeMap[type](); + let attributeTypes = typeMap[type].getAttributeTypeMap(); + for (let index in attributeTypes) { + let attributeType = attributeTypes[index]; + instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type); + } + return instance; + } + } +} + +export class ApiResponse { + 'code'?: number; + 'type'?: string; + 'message'?: string; + + static discriminator: string | undefined = undefined; + + static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ + { + "name": "code", + "baseName": "code", + "type": "number" + }, + { + "name": "type", + "baseName": "type", + "type": "string" + }, + { + "name": "message", + "baseName": "message", + "type": "string" + } ]; + + static getAttributeTypeMap() { + return ApiResponse.attributeTypeMap; + } +} + +export class Category { + 'id'?: number; + 'name'?: string; + + static discriminator: string | undefined = undefined; + + static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ + { + "name": "id", + "baseName": "id", + "type": "number" + }, + { + "name": "name", + "baseName": "name", + "type": "string" + } ]; + + static getAttributeTypeMap() { + return Category.attributeTypeMap; + } +} + +export class Order { + 'id'?: number; + 'petId'?: number; + 'quantity'?: number; + 'shipDate'?: Date; + /** + * Order Status + */ + 'status'?: Order.StatusEnum; + 'complete'?: boolean; + + static discriminator: string | undefined = undefined; + + static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ + { + "name": "id", + "baseName": "id", + "type": "number" + }, + { + "name": "petId", + "baseName": "petId", + "type": "number" + }, + { + "name": "quantity", + "baseName": "quantity", + "type": "number" + }, + { + "name": "shipDate", + "baseName": "shipDate", + "type": "Date" + }, + { + "name": "status", + "baseName": "status", + "type": "Order.StatusEnum" + }, + { + "name": "complete", + "baseName": "complete", + "type": "boolean" + } ]; + + static getAttributeTypeMap() { + return Order.attributeTypeMap; + } +} + +export namespace Order { + export enum StatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' + } +} +export class Pet { + 'id'?: number; + 'category'?: Category; + 'name': string; + 'photoUrls': Array; + 'tags'?: Array; + /** + * pet status in the store + */ + 'status'?: Pet.StatusEnum; + + static discriminator: string | undefined = undefined; + + static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ + { + "name": "id", + "baseName": "id", + "type": "number" + }, + { + "name": "category", + "baseName": "category", + "type": "Category" + }, + { + "name": "name", + "baseName": "name", + "type": "string" + }, + { + "name": "photoUrls", + "baseName": "photoUrls", + "type": "Array" + }, + { + "name": "tags", + "baseName": "tags", + "type": "Array" + }, + { + "name": "status", + "baseName": "status", + "type": "Pet.StatusEnum" + } ]; + + static getAttributeTypeMap() { + return Pet.attributeTypeMap; + } +} + +export namespace Pet { + export enum StatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' + } +} +export class Tag { + 'id'?: number; + 'name'?: string; + + static discriminator: string | undefined = undefined; + + static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ + { + "name": "id", + "baseName": "id", + "type": "number" + }, + { + "name": "name", + "baseName": "name", + "type": "string" + } ]; + + static getAttributeTypeMap() { + return Tag.attributeTypeMap; + } +} + +export class User { + 'id'?: number; + 'username'?: string; + 'firstName'?: string; + 'lastName'?: string; + 'email'?: string; + 'password'?: string; + 'phone'?: string; + /** + * User Status + */ + 'userStatus'?: number; + + static discriminator: string | undefined = undefined; + + static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ + { + "name": "id", + "baseName": "id", + "type": "number" + }, + { + "name": "username", + "baseName": "username", + "type": "string" + }, + { + "name": "firstName", + "baseName": "firstName", + "type": "string" + }, + { + "name": "lastName", + "baseName": "lastName", + "type": "string" + }, + { + "name": "email", + "baseName": "email", + "type": "string" + }, + { + "name": "password", + "baseName": "password", + "type": "string" + }, + { + "name": "phone", + "baseName": "phone", + "type": "string" + }, + { + "name": "userStatus", + "baseName": "userStatus", + "type": "number" + } ]; + + static getAttributeTypeMap() { + return User.attributeTypeMap; + } +} + + +let enumsMap: {[index: string]: any} = { + "Order.StatusEnum": Order.StatusEnum, + "Pet.StatusEnum": Pet.StatusEnum, +} + +let typeMap: {[index: string]: any} = { + "ApiResponse": ApiResponse, + "Category": Category, + "Order": Order, + "Pet": Pet, + "Tag": Tag, + "User": User, +} + +export interface Authentication { + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: localVarRequest.Options): void; +} + +export class HttpBasicAuth implements Authentication { + public username: string = ''; + public password: string = ''; + + applyToRequest(requestOptions: localVarRequest.Options): void { + requestOptions.auth = { + username: this.username, password: this.password + } + } +} + +export class ApiKeyAuth implements Authentication { + public apiKey: string = ''; + + constructor(private location: string, private paramName: string) { + } + + applyToRequest(requestOptions: localVarRequest.Options): void { + if (this.location == "query") { + (requestOptions.qs)[this.paramName] = this.apiKey; + } else if (this.location == "header" && requestOptions && requestOptions.headers) { + requestOptions.headers[this.paramName] = this.apiKey; + } + } +} + +export class OAuth implements Authentication { + public accessToken: string = ''; + + applyToRequest(requestOptions: localVarRequest.Options): void { + if (requestOptions && requestOptions.headers) { + requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + } + } +} + +export class VoidAuth implements Authentication { + public username: string = ''; + public password: string = ''; + + applyToRequest(_: localVarRequest.Options): void { + // Do nothing + } +} + +export enum PetApiApiKeys { + api_key, +} + +export class PetApi { + protected _basePath = defaultBasePath; + protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; + + protected authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } + + constructor(basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + + set basePath(basePath: string) { + this._basePath = basePath; + } + + get basePath() { + return this._basePath; + } + + public setDefaultAuthentication(auth: Authentication) { + this.authentications.default = auth; + } + + public setApiKey(key: PetApiApiKeys, value: string) { + (this.authentications as any)[PetApiApiKeys[key]].apiKey = value; + } + + set accessToken(token: string) { + this.authentications.petstore_auth.accessToken = token; + } + /** + * + * @summary Add a new pet to the store + * @param body Pet object that needs to be added to the store + * @param {*} [options] Override http request options. + */ + public addPet (body: Pet, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/pet'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling addPet.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'POST', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + body: ObjectSerializer.serialize(body, "Pet") + }; + + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * + * @summary Deletes a pet + * @param petId Pet id to delete + * @param apiKey + * @param {*} [options] Override http request options. + */ + public deletePet (petId: number, apiKey?: string, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + localVarHeaderParams['api_key'] = ObjectSerializer.serialize(apiKey, "string"); + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'DELETE', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * Multiple status values can be provided with comma separated strings + * @summary Finds Pets by status + * @param status Status values that need to be considered for filter + * @param {*} [options] Override http request options. + */ + public findPetsByStatus (status: Array<'available' | 'pending' | 'sold'>, options: any = {}) : Promise<{ response: http.ClientResponse; body: Array; }> { + const localVarPath = this.basePath + '/pet/findByStatus'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'status' is not null or undefined + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + if (status !== undefined) { + localVarQueryParameters['status'] = ObjectSerializer.serialize(status, "Array<'available' | 'pending' | 'sold'>"); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'GET', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body: Array; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + body = ObjectSerializer.deserialize(body, "Array"); + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @summary Finds Pets by tags + * @param tags Tags to filter by + * @param {*} [options] Override http request options. + */ + public findPetsByTags (tags: Array, options: any = {}) : Promise<{ response: http.ClientResponse; body: Array; }> { + const localVarPath = this.basePath + '/pet/findByTags'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'tags' is not null or undefined + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + if (tags !== undefined) { + localVarQueryParameters['tags'] = ObjectSerializer.serialize(tags, "Array"); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'GET', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body: Array; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + body = ObjectSerializer.deserialize(body, "Array"); + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * Returns a single pet + * @summary Find pet by ID + * @param petId ID of pet to return + * @param {*} [options] Override http request options. + */ + public getPetById (petId: number, options: any = {}) : Promise<{ response: http.ClientResponse; body: Pet; }> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'GET', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.api_key.applyToRequest(localVarRequestOptions); + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body: Pet; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + body = ObjectSerializer.deserialize(body, "Pet"); + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * + * @summary Update an existing pet + * @param body Pet object that needs to be added to the store + * @param {*} [options] Override http request options. + */ + public updatePet (body: Pet, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/pet'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updatePet.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'PUT', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + body: ObjectSerializer.serialize(body, "Pet") + }; + + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * + * @summary Updates a pet in the store with form data + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @param {*} [options] Override http request options. + */ + public updatePetWithForm (petId: number, name?: string, status?: string, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + if (name !== undefined) { + localVarFormParams['name'] = ObjectSerializer.serialize(name, "string"); + } + + if (status !== undefined) { + localVarFormParams['status'] = ObjectSerializer.serialize(status, "string"); + } + + let localVarRequestOptions: localVarRequest.Options = { + method: 'POST', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * + * @summary uploads an image + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @param {*} [options] Override http request options. + */ + public uploadFile (petId: number, additionalMetadata?: string, file?: Buffer, options: any = {}) : Promise<{ response: http.ClientResponse; body: ApiResponse; }> { + const localVarPath = this.basePath + '/pet/{petId}/uploadImage' + .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + if (additionalMetadata !== undefined) { + localVarFormParams['additionalMetadata'] = ObjectSerializer.serialize(additionalMetadata, "string"); + } + + if (file !== undefined) { + localVarFormParams['file'] = file; + } + localVarUseFormData = true; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'POST', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body: ApiResponse; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + body = ObjectSerializer.deserialize(body, "ApiResponse"); + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } +} +export enum StoreApiApiKeys { + api_key, +} + +export class StoreApi { + protected _basePath = defaultBasePath; + protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; + + protected authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } + + constructor(basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + + set basePath(basePath: string) { + this._basePath = basePath; + } + + get basePath() { + return this._basePath; + } + + public setDefaultAuthentication(auth: Authentication) { + this.authentications.default = auth; + } + + public setApiKey(key: StoreApiApiKeys, value: string) { + (this.authentications as any)[StoreApiApiKeys[key]].apiKey = value; + } + + set accessToken(token: string) { + this.authentications.petstore_auth.accessToken = token; + } + /** + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * @summary Delete purchase order by ID + * @param orderId ID of the order that needs to be deleted + * @param {*} [options] Override http request options. + */ + public deleteOrder (orderId: number, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'DELETE', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * Returns a map of status codes to quantities + * @summary Returns pet inventories by status + * @param {*} [options] Override http request options. + */ + public getInventory (options: any = {}) : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { + const localVarPath = this.basePath + '/store/inventory'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'GET', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.api_key.applyToRequest(localVarRequestOptions); + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + body = ObjectSerializer.deserialize(body, "{ [key: string]: number; }"); + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * @summary Find purchase order by ID + * @param orderId ID of pet that needs to be fetched + * @param {*} [options] Override http request options. + */ + public getOrderById (orderId: number, options: any = {}) : Promise<{ response: http.ClientResponse; body: Order; }> { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'GET', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + body = ObjectSerializer.deserialize(body, "Order"); + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * + * @summary Place an order for a pet + * @param body order placed for purchasing the pet + * @param {*} [options] Override http request options. + */ + public placeOrder (body: Order, options: any = {}) : Promise<{ response: http.ClientResponse; body: Order; }> { + const localVarPath = this.basePath + '/store/order'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling placeOrder.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'POST', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + body: ObjectSerializer.serialize(body, "Order") + }; + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + body = ObjectSerializer.deserialize(body, "Order"); + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } +} +export enum UserApiApiKeys { + api_key, +} + +export class UserApi { + protected _basePath = defaultBasePath; + protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; + + protected authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } + + constructor(basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + + set basePath(basePath: string) { + this._basePath = basePath; + } + + get basePath() { + return this._basePath; + } + + public setDefaultAuthentication(auth: Authentication) { + this.authentications.default = auth; + } + + public setApiKey(key: UserApiApiKeys, value: string) { + (this.authentications as any)[UserApiApiKeys[key]].apiKey = value; + } + + set accessToken(token: string) { + this.authentications.petstore_auth.accessToken = token; + } + /** + * This can only be done by the logged in user. + * @summary Create user + * @param body Created user object + * @param {*} [options] Override http request options. + */ + public createUser (body: User, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/user'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUser.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'POST', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + body: ObjectSerializer.serialize(body, "User") + }; + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * + * @summary Creates list of users with given input array + * @param body List of user object + * @param {*} [options] Override http request options. + */ + public createUsersWithArrayInput (body: Array, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/user/createWithArray'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'POST', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + body: ObjectSerializer.serialize(body, "Array") + }; + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * + * @summary Creates list of users with given input array + * @param body List of user object + * @param {*} [options] Override http request options. + */ + public createUsersWithListInput (body: Array, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/user/createWithList'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'POST', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + body: ObjectSerializer.serialize(body, "Array") + }; + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * This can only be done by the logged in user. + * @summary Delete user + * @param username The name that needs to be deleted + * @param {*} [options] Override http request options. + */ + public deleteUser (username: string, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', encodeURIComponent(String(username))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'DELETE', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * + * @summary Get user by user name + * @param username The name that needs to be fetched. Use user1 for testing. + * @param {*} [options] Override http request options. + */ + public getUserByName (username: string, options: any = {}) : Promise<{ response: http.ClientResponse; body: User; }> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', encodeURIComponent(String(username))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'GET', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body: User; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + body = ObjectSerializer.deserialize(body, "User"); + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * + * @summary Logs user into the system + * @param username The user name for login + * @param password The password for login in clear text + * @param {*} [options] Override http request options. + */ + public loginUser (username: string, password: string, options: any = {}) : Promise<{ response: http.ClientResponse; body: string; }> { + const localVarPath = this.basePath + '/user/login'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + + // verify required parameter 'password' is not null or undefined + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + if (username !== undefined) { + localVarQueryParameters['username'] = ObjectSerializer.serialize(username, "string"); + } + + if (password !== undefined) { + localVarQueryParameters['password'] = ObjectSerializer.serialize(password, "string"); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'GET', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body: string; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + body = ObjectSerializer.deserialize(body, "string"); + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * + * @summary Logs out current logged in user session + * @param {*} [options] Override http request options. + */ + public logoutUser (options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/user/logout'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'GET', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } + /** + * This can only be done by the logged in user. + * @summary Updated user + * @param username name that need to be updated + * @param body Updated user object + * @param {*} [options] Override http request options. + */ + public updateUser (username: string, body: User, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', encodeURIComponent(String(username))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this.defaultHeaders); + let localVarFormParams: any = {}; + + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + + // verify required parameter 'body' is not null or undefined + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updateUser.'); + } + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'PUT', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + body: ObjectSerializer.serialize(body, "User") + }; + + this.authentications.default.applyToRequest(localVarRequestOptions); + + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } +} diff --git a/test/generated-clients/typescript-node/git_push.sh b/test/generated-clients/typescript-node/git_push.sh new file mode 100644 index 00000000..ae01b182 --- /dev/null +++ b/test/generated-clients/typescript-node/git_push.sh @@ -0,0 +1,52 @@ +#!/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" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +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://github.com/${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 + fi + +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" +git push origin master 2>&1 | grep -v 'To https' +