diff --git a/bin/configs/typescript-node-3.0.yaml b/bin/configs/typescript-node-3.0.yaml new file mode 100644 index 000000000000..539f57c0a3ac --- /dev/null +++ b/bin/configs/typescript-node-3.0.yaml @@ -0,0 +1,4 @@ +generatorName: typescript-node +outputDir: samples/client/petstore/typescript-node/3_0 +inputSpec: modules/openapi-generator/src/test/resources/3_0/typescript-node/SampleProject.yaml +templateDir: modules/openapi-generator/src/main/resources/typescript-node diff --git a/modules/openapi-generator/src/main/resources/typescript-node/model.mustache b/modules/openapi-generator/src/main/resources/typescript-node/model.mustache index 5b2d594a99ad..8bd764134687 100644 --- a/modules/openapi-generator/src/main/resources/typescript-node/model.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-node/model.mustache @@ -17,7 +17,18 @@ export class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{ {{#description}} /** * {{{.}}} + {{#deprecated}} + * + * @deprecated + {{/deprecated}} */ +{{/description}} +{{^description}} + {{#deprecated}} + /** + * @deprecated + */ + {{/deprecated}} {{/description}} '{{name}}'{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}{{#defaultValue}} = {{#isEnum}}{{classname}}.{{/isEnum}}{{{.}}}{{/defaultValue}}; {{/vars}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientCodegenTest.java index 26019413080a..108d12c0917b 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientCodegenTest.java @@ -4,8 +4,11 @@ import io.swagger.v3.oas.models.media.ObjectSchema; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; +import org.openapitools.codegen.ClientOptInput; import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.DefaultGenerator; import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.CodegenConfigurator; import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen; import org.openapitools.codegen.model.ModelMap; import org.openapitools.codegen.model.ModelsMap; @@ -16,6 +19,10 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.*; @Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NODE}) @@ -227,6 +234,68 @@ public void postProcessOperationsWithModelsTestWithModelNamePrefix() { Assert.assertEquals(tsImports.get(0).get("filename"), "./prefixChild"); } + @Test + public void testApisGeneration() throws IOException { + + File output = Files.createTempDirectory("typescriptnodeclient_").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("typescript-node") + .setInputSpec("src/test/resources/3_0/typescript-node/SampleProject.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + files.forEach(File::deleteOnExit); + + TestUtils.assertFileContains(Paths.get(output + "/api/basicApi.ts"), + "* Sample project"); + TestUtils.assertFileContains(Paths.get(output + "/api/basicApi.ts"), + "export class BasicApi {"); + } + + @Test + public void testModelsGeneration() throws IOException { + + File output = Files.createTempDirectory("typescriptnodeclient_").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("typescript-node") + .setInputSpec("src/test/resources/3_0/typescript-node/SampleProject.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + files.forEach(File::deleteOnExit); + + TestUtils.assertFileContains(Paths.get(output + "/model/group.ts"), + "export class Group {"); + } + + @Test + public void testDeprecatedAttribute() throws IOException { + + File output = Files.createTempDirectory("typescriptnodeclient_").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("typescript-node") + .setInputSpec("src/test/resources/3_0/typescript-node/SampleProject.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + files.forEach(File::deleteOnExit); + + TestUtils.assertFileContains(Paths.get(output + "/model/group.ts"), + "* @deprecated"); + } + private OperationsMap createPostProcessOperationsMapWithImportName(String importName) { OperationMap operations = new OperationMap(); operations.setClassname("Pet"); diff --git a/modules/openapi-generator/src/test/resources/3_0/typescript-node/SampleProject.yaml b/modules/openapi-generator/src/test/resources/3_0/typescript-node/SampleProject.yaml new file mode 100644 index 000000000000..a9cb17fada33 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/typescript-node/SampleProject.yaml @@ -0,0 +1,371 @@ +openapi: 3.0.0 +info: + title: Sample project + version: '1.0' + description: 'Sample API Check "API Key" ' + license: + name: Apache 2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0' +servers: + - url: 'http://localhost:{port}/{version}' + description: dev server + variables: + port: + description: Port number + enum: + - '5000' + - '8080' + default: '5000' + version: + default: v1 + description: API version + - url: 'http://localhost:{port}/{version}' + description: test server + variables: + port: + description: Port number + enum: + - '5000' + - '8080' + default: '5000' + version: + default: v1 + description: API version +paths: + '/users/': + get: + summary: Get User Info by Query Param + operationId: get-users-query-id + description: Retrieve the information of the user with the matching user ID. + tags: + - basic + parameters: + - description: Query Id. + name: pUserId + in: query + required: true + schema: + type: string + example: 888 + - description: Custom HTTP header + name: Custom-Header + in: header + schema: + type: string + - description: Custom HTTP header with default + name: Another-Custom-Header + in: header + schema: + type: string + default: abc + + responses: + '200': + description: User Found + content: + application/json: + schema: + $ref: '#/components/schemas/User' + example: + id: schema-example + firstName: Alice + lastName: Smith333 + email: alice.smith@gmail.com + dateOfBirth: '1997-10-31' + emailVerified: true + signUpDate: '2019-08-24' + examples: + Get User Alice Smith: + value: + id: 142 + firstName: Alice + lastName: Smith + email: alice.smith@gmail.com + dateOfBirth: '1997-10-31' + emailVerified: true + signUpDate: '2019-08-24' + Get User Phil Smith: + value: + id: 143 + firstName: Phil + lastName: Smith + email: alice.smith@gmail.com + dateOfBirth: '1997-10-31' + emailVerified: true + signUpDate: '2019-08-24' + '404': + description: User Not Found + '/users/{userId}': + parameters: + - schema: + type: integer + examples: + a: + value: a + summary: a summary + b: + value: b + summary: b summary + name: userId + in: path + required: true + description: Id of an existing user. + - schema: + type: string + default: code_one + name: strCode + in: header + description: Code as header + - schema: + type: string + name: strCode2 + in: header + description: Code as header2 + get: + summary: Get User Info by User ID + tags: + - advanced + responses: + '200': + description: User Found + content: + application/json: + schema: + $ref: '#/components/schemas/User' + example: + id: 9998 + firstName: Alice9998 resp example + lastName: Smith9998 + email: alice.smith@gmail.com + dateOfBirth: '1997-10-31' + emailVerified: true + createDate: '2019-08-24' + '404': + description: User Not Found + operationId: get-users-userId + description: Retrieve the information of the user with the matching user ID. + patch: + summary: Update User Information + operationId: patch-users-userId + responses: + '200': + description: User Updated + content: + application/json: + schema: + $ref: '#/components/schemas/User' + examples: + Updated User Rebecca Baker: + value: + id: 13 + firstName: Rebecca + lastName: Baker + email: rebecca@gmail.com + dateOfBirth: '1985-10-02' + emailVerified: false + createDate: '2019-08-24' + '404': + description: User Not Found + '409': + description: Email Already Taken + description: Update the information of an existing user. + requestBody: + content: + application/json: + schema: + type: object + properties: + firstName: + type: string + lastName: + type: string + email: + type: string + description: >- + If a new email is given, the user's email verified property + will be set to false. + dateOfBirth: + type: string + examples: + Update First Name: + value: + firstName: Rebecca + Update Email: + value: + email: rebecca@gmail.com + verified: true + Update Last Name & Date of Birth: + value: + lastName: Baker + dateOfBirth: '1985-10-02' + description: Patch user properties to update. + /user: + post: + summary: Create New User + operationId: post-user + responses: + '200': + description: User Created + content: + application/json: + schema: + $ref: '#/components/schemas/User' + examples: + basic: + $ref: '#/components/examples/get-user-basic' + '400': + description: Missing Required Information + '409': + description: Email Already Taken + requestBody: + content: + application/json: + schema: + type: object + properties: + firstName: + type: string + lastName: + type: string + email: + type: string + dateOfBirth: + type: string + format: date + required: + - firstName + - lastName + - email + - dateOfBirth + examples: + basic: + $ref: '#/components/examples/get-user-basic' + description: Post the necessary fields for the API to create a new user. + description: Create a new user. + tags: + - basic + '/groups/{groupId}': + get: + summary: Get group by ID + tags: + - advanced + parameters: + - description: group Id + name: groupId + in: path + required: true + schema: + type: integer + default: 1 + responses: + '200': + description: Group Found + content: + application/json: + schema: + $ref: '#/components/schemas/Group' + '404': + description: Group Not Found + operationId: get-groups-groupId + description: Get group of users + +components: + securitySchemes: + BasicAuth: + type: http + scheme: basic + BearerAuth: + type: http + scheme: bearer + ApiKeyAuth: + type: apiKey + name: X-API-Key + in: header + schemas: + User: + title: User + type: object + description: '' + example: + id: 999 + firstName: Alice9 schema example + lastName: Smith9 + email: alice.smith@gmail.com + dateOfBirth: '1997-10-31' + emailVerified: true + createDate: '2019-08-24' + properties: + id: + type: integer + description: Unique identifier for the given user. + example: 0 + firstName: + type: string + example: Alix + lastName: + type: string + example: Smith + email: + type: string + format: email + example: alix.smith@gmail.com + dateOfBirth: + type: string + format: date + example: '1997-10-31' + emailVerified: + type: boolean + description: Set to true if the user's email has been verified. + example: true + deprecated: true + createDate: + type: string + format: date + description: The date that the user was created. + example: '2019-08-24' + tags: + type: array + items: + type: string + description: Tags assigned to the user + required: + - id + - firstName + - lastName + - email + - emailVerified + Group: + title: Group + type: object + description: '' + properties: + id: + type: integer + description: Unique identifier for the given group. + name: + type: string + example: admin + deprecated: true + required: + - id + - name + examples: + get-user-basic: + summary: Example request for Get User + value: + id: 777 + firstName: Alotta + lastName: Rotta + email: alotta.rotta@gmail.com + dateOfBirth: '1997-10-31' + emailVerified: true + createDate: '2019-08-24' + tags: + - user + - admin + - guest +tags: + - name: basic + description: Basic tag + - name: advanced + description: Advanced tag diff --git a/samples/client/petstore/typescript-node/3_0/.gitignore b/samples/client/petstore/typescript-node/3_0/.gitignore new file mode 100644 index 000000000000..149b57654723 --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/petstore/typescript-node/3_0/.openapi-generator-ignore b/samples/client/petstore/typescript-node/3_0/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/typescript-node/3_0/.openapi-generator/FILES b/samples/client/petstore/typescript-node/3_0/.openapi-generator/FILES new file mode 100644 index 000000000000..833a6211a587 --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/.openapi-generator/FILES @@ -0,0 +1,12 @@ +.gitignore +api.ts +api/advancedApi.ts +api/apis.ts +api/basicApi.ts +api/defaultApi.ts +git_push.sh +model/group.ts +model/models.ts +model/patchUsersUserIdRequest.ts +model/postUserRequest.ts +model/user.ts diff --git a/samples/client/petstore/typescript-node/3_0/.openapi-generator/VERSION b/samples/client/petstore/typescript-node/3_0/.openapi-generator/VERSION new file mode 100644 index 000000000000..17f2442ff3bc --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.9.0-SNAPSHOT diff --git a/samples/client/petstore/typescript-node/3_0/api.ts b/samples/client/petstore/typescript-node/3_0/api.ts new file mode 100644 index 000000000000..b1119f15c47f --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/api.ts @@ -0,0 +1,3 @@ +// This is the entrypoint for the package +export * from './api/apis'; +export * from './model/models'; diff --git a/samples/client/petstore/typescript-node/3_0/api/advancedApi.ts b/samples/client/petstore/typescript-node/3_0/api/advancedApi.ts new file mode 100644 index 000000000000..7a1cb0de90ca --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/api/advancedApi.ts @@ -0,0 +1,252 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import localVarRequest from 'request'; +import http from 'http'; + +/* tslint:disable:no-unused-locals */ +import { Group } from '../model/group'; +import { User } from '../model/user'; + +import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models'; +import { HttpBasicAuth, HttpBearerAuth, ApiKeyAuth, OAuth } from '../model/models'; + +import { HttpError, RequestFile } from './apis'; + +let defaultBasePath = 'http://localhost:5000/v1'; + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +export enum AdvancedApiApiKeys { + ApiKeyAuth, +} + +export class AdvancedApi { + protected _basePath = defaultBasePath; + protected _defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; + + protected authentications = { + 'default': new VoidAuth(), + 'BasicAuth': new HttpBasicAuth(), + 'BearerAuth': new HttpBearerAuth(), + 'ApiKeyAuth': new ApiKeyAuth('header', 'X-API-Key'), + } + + protected interceptors: Interceptor[] = []; + + constructor(basePath?: string); + constructor(username: string, password: string, basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + this.username = basePathOrUsername; + this.password = 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; + } + + set defaultHeaders(defaultHeaders: any) { + this._defaultHeaders = defaultHeaders; + } + + get defaultHeaders() { + return this._defaultHeaders; + } + + get basePath() { + return this._basePath; + } + + public setDefaultAuthentication(auth: Authentication) { + this.authentications.default = auth; + } + + public setApiKey(key: AdvancedApiApiKeys, value: string) { + (this.authentications as any)[AdvancedApiApiKeys[key]].apiKey = value; + } + + set username(username: string) { + this.authentications.BasicAuth.username = username; + } + + set password(password: string) { + this.authentications.BasicAuth.password = password; + } + + set accessToken(accessToken: string | (() => string)) { + this.authentications.BearerAuth.accessToken = accessToken; + } + + public addInterceptor(interceptor: Interceptor) { + this.interceptors.push(interceptor); + } + + /** + * Get group of users + * @summary Get group by ID + * @param groupId group Id + */ + public async getGroupsGroupId (groupId: number, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: Group; }> { + const localVarPath = this.basePath + '/groups/{groupId}' + .replace('{' + 'groupId' + '}', encodeURIComponent(String(groupId))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this._defaultHeaders); + const produces = ['application/json']; + // give precedence to 'application/json' + if (produces.indexOf('application/json') >= 0) { + localVarHeaderParams.Accept = 'application/json'; + } else { + localVarHeaderParams.Accept = produces.join(','); + } + let localVarFormParams: any = {}; + + // verify required parameter 'groupId' is not null or undefined + if (groupId === null || groupId === undefined) { + throw new Error('Required parameter groupId was null or undefined when calling getGroupsGroupId.'); + } + + (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, + }; + + let authenticationPromise = Promise.resolve(); + authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); + + let interceptorPromise = authenticationPromise; + for (const interceptor of this.interceptors) { + interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); + } + + return interceptorPromise.then(() => { + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.IncomingMessage; body: Group; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Group"); + resolve({ response: response, body: body }); + } else { + reject(new HttpError(response, body, response.statusCode)); + } + } + }); + }); + }); + } + /** + * Retrieve the information of the user with the matching user ID. + * @summary Get User Info by User ID + * @param userId Id of an existing user. + * @param strCode Code as header + * @param strCode2 Code as header2 + */ + public async getUsersUserId (userId: number, strCode?: string, strCode2?: string, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: User; }> { + const localVarPath = this.basePath + '/users/{userId}' + .replace('{' + 'userId' + '}', encodeURIComponent(String(userId))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this._defaultHeaders); + const produces = ['application/json']; + // give precedence to 'application/json' + if (produces.indexOf('application/json') >= 0) { + localVarHeaderParams.Accept = 'application/json'; + } else { + localVarHeaderParams.Accept = produces.join(','); + } + let localVarFormParams: any = {}; + + // verify required parameter 'userId' is not null or undefined + if (userId === null || userId === undefined) { + throw new Error('Required parameter userId was null or undefined when calling getUsersUserId.'); + } + + localVarHeaderParams['strCode'] = ObjectSerializer.serialize(strCode, "string"); + localVarHeaderParams['strCode2'] = ObjectSerializer.serialize(strCode2, "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, + }; + + let authenticationPromise = Promise.resolve(); + authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); + + let interceptorPromise = authenticationPromise; + for (const interceptor of this.interceptors) { + interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); + } + + return interceptorPromise.then(() => { + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.IncomingMessage; body: User; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "User"); + resolve({ response: response, body: body }); + } else { + reject(new HttpError(response, body, response.statusCode)); + } + } + }); + }); + }); + } +} diff --git a/samples/client/petstore/typescript-node/3_0/api/apis.ts b/samples/client/petstore/typescript-node/3_0/api/apis.ts new file mode 100644 index 000000000000..e1018461120c --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/api/apis.ts @@ -0,0 +1,18 @@ +export * from './advancedApi'; +import { AdvancedApi } from './advancedApi'; +export * from './basicApi'; +import { BasicApi } from './basicApi'; +export * from './defaultApi'; +import { DefaultApi } from './defaultApi'; +import * as http from 'http'; + +export class HttpError extends Error { + constructor (public response: http.IncomingMessage, public body: any, public statusCode?: number) { + super('HTTP request failed'); + this.name = 'HttpError'; + } +} + +export { RequestFile } from '../model/models'; + +export const APIS = [AdvancedApi, BasicApi, DefaultApi]; diff --git a/samples/client/petstore/typescript-node/3_0/api/basicApi.ts b/samples/client/petstore/typescript-node/3_0/api/basicApi.ts new file mode 100644 index 000000000000..8fa911ff35e8 --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/api/basicApi.ts @@ -0,0 +1,250 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import localVarRequest from 'request'; +import http from 'http'; + +/* tslint:disable:no-unused-locals */ +import { PostUserRequest } from '../model/postUserRequest'; +import { User } from '../model/user'; + +import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models'; +import { HttpBasicAuth, HttpBearerAuth, ApiKeyAuth, OAuth } from '../model/models'; + +import { HttpError, RequestFile } from './apis'; + +let defaultBasePath = 'http://localhost:5000/v1'; + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +export enum BasicApiApiKeys { + ApiKeyAuth, +} + +export class BasicApi { + protected _basePath = defaultBasePath; + protected _defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; + + protected authentications = { + 'default': new VoidAuth(), + 'BasicAuth': new HttpBasicAuth(), + 'BearerAuth': new HttpBearerAuth(), + 'ApiKeyAuth': new ApiKeyAuth('header', 'X-API-Key'), + } + + protected interceptors: Interceptor[] = []; + + constructor(basePath?: string); + constructor(username: string, password: string, basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + this.username = basePathOrUsername; + this.password = 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; + } + + set defaultHeaders(defaultHeaders: any) { + this._defaultHeaders = defaultHeaders; + } + + get defaultHeaders() { + return this._defaultHeaders; + } + + get basePath() { + return this._basePath; + } + + public setDefaultAuthentication(auth: Authentication) { + this.authentications.default = auth; + } + + public setApiKey(key: BasicApiApiKeys, value: string) { + (this.authentications as any)[BasicApiApiKeys[key]].apiKey = value; + } + + set username(username: string) { + this.authentications.BasicAuth.username = username; + } + + set password(password: string) { + this.authentications.BasicAuth.password = password; + } + + set accessToken(accessToken: string | (() => string)) { + this.authentications.BearerAuth.accessToken = accessToken; + } + + public addInterceptor(interceptor: Interceptor) { + this.interceptors.push(interceptor); + } + + /** + * Retrieve the information of the user with the matching user ID. + * @summary Get User Info by Query Param + * @param pUserId Query Id. + * @param customHeader Custom HTTP header + * @param anotherCustomHeader Custom HTTP header with default + */ + public async getUsersQueryId (pUserId: string, customHeader?: string, anotherCustomHeader?: string, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: User; }> { + const localVarPath = this.basePath + '/users/'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this._defaultHeaders); + const produces = ['application/json']; + // give precedence to 'application/json' + if (produces.indexOf('application/json') >= 0) { + localVarHeaderParams.Accept = 'application/json'; + } else { + localVarHeaderParams.Accept = produces.join(','); + } + let localVarFormParams: any = {}; + + // verify required parameter 'pUserId' is not null or undefined + if (pUserId === null || pUserId === undefined) { + throw new Error('Required parameter pUserId was null or undefined when calling getUsersQueryId.'); + } + + if (pUserId !== undefined) { + localVarQueryParameters['pUserId'] = ObjectSerializer.serialize(pUserId, "string"); + } + + localVarHeaderParams['Custom-Header'] = ObjectSerializer.serialize(customHeader, "string"); + localVarHeaderParams['Another-Custom-Header'] = ObjectSerializer.serialize(anotherCustomHeader, "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, + }; + + let authenticationPromise = Promise.resolve(); + authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); + + let interceptorPromise = authenticationPromise; + for (const interceptor of this.interceptors) { + interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); + } + + return interceptorPromise.then(() => { + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.IncomingMessage; body: User; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "User"); + resolve({ response: response, body: body }); + } else { + reject(new HttpError(response, body, response.statusCode)); + } + } + }); + }); + }); + } + /** + * Create a new user. + * @summary Create New User + * @param postUserRequest Post the necessary fields for the API to create a new user. + */ + public async postUser (postUserRequest?: PostUserRequest, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: User; }> { + const localVarPath = this.basePath + '/user'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this._defaultHeaders); + const produces = ['application/json']; + // give precedence to 'application/json' + if (produces.indexOf('application/json') >= 0) { + localVarHeaderParams.Accept = 'application/json'; + } else { + localVarHeaderParams.Accept = produces.join(','); + } + let localVarFormParams: any = {}; + + (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(postUserRequest, "PostUserRequest") + }; + + let authenticationPromise = Promise.resolve(); + authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); + + let interceptorPromise = authenticationPromise; + for (const interceptor of this.interceptors) { + interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); + } + + return interceptorPromise.then(() => { + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.IncomingMessage; body: User; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "User"); + resolve({ response: response, body: body }); + } else { + reject(new HttpError(response, body, response.statusCode)); + } + } + }); + }); + }); + } +} diff --git a/samples/client/petstore/typescript-node/3_0/api/defaultApi.ts b/samples/client/petstore/typescript-node/3_0/api/defaultApi.ts new file mode 100644 index 000000000000..9786eacce900 --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/api/defaultApi.ts @@ -0,0 +1,185 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import localVarRequest from 'request'; +import http from 'http'; + +/* tslint:disable:no-unused-locals */ +import { PatchUsersUserIdRequest } from '../model/patchUsersUserIdRequest'; +import { User } from '../model/user'; + +import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models'; +import { HttpBasicAuth, HttpBearerAuth, ApiKeyAuth, OAuth } from '../model/models'; + +import { HttpError, RequestFile } from './apis'; + +let defaultBasePath = 'http://localhost:5000/v1'; + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +export enum DefaultApiApiKeys { + ApiKeyAuth, +} + +export class DefaultApi { + protected _basePath = defaultBasePath; + protected _defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; + + protected authentications = { + 'default': new VoidAuth(), + 'BasicAuth': new HttpBasicAuth(), + 'BearerAuth': new HttpBearerAuth(), + 'ApiKeyAuth': new ApiKeyAuth('header', 'X-API-Key'), + } + + protected interceptors: Interceptor[] = []; + + constructor(basePath?: string); + constructor(username: string, password: string, basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + this.username = basePathOrUsername; + this.password = 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; + } + + set defaultHeaders(defaultHeaders: any) { + this._defaultHeaders = defaultHeaders; + } + + get defaultHeaders() { + return this._defaultHeaders; + } + + get basePath() { + return this._basePath; + } + + public setDefaultAuthentication(auth: Authentication) { + this.authentications.default = auth; + } + + public setApiKey(key: DefaultApiApiKeys, value: string) { + (this.authentications as any)[DefaultApiApiKeys[key]].apiKey = value; + } + + set username(username: string) { + this.authentications.BasicAuth.username = username; + } + + set password(password: string) { + this.authentications.BasicAuth.password = password; + } + + set accessToken(accessToken: string | (() => string)) { + this.authentications.BearerAuth.accessToken = accessToken; + } + + public addInterceptor(interceptor: Interceptor) { + this.interceptors.push(interceptor); + } + + /** + * Update the information of an existing user. + * @summary Update User Information + * @param userId Id of an existing user. + * @param strCode Code as header + * @param strCode2 Code as header2 + * @param patchUsersUserIdRequest Patch user properties to update. + */ + public async patchUsersUserId (userId: number, strCode?: string, strCode2?: string, patchUsersUserIdRequest?: PatchUsersUserIdRequest, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: User; }> { + const localVarPath = this.basePath + '/users/{userId}' + .replace('{' + 'userId' + '}', encodeURIComponent(String(userId))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this._defaultHeaders); + const produces = ['application/json']; + // give precedence to 'application/json' + if (produces.indexOf('application/json') >= 0) { + localVarHeaderParams.Accept = 'application/json'; + } else { + localVarHeaderParams.Accept = produces.join(','); + } + let localVarFormParams: any = {}; + + // verify required parameter 'userId' is not null or undefined + if (userId === null || userId === undefined) { + throw new Error('Required parameter userId was null or undefined when calling patchUsersUserId.'); + } + + localVarHeaderParams['strCode'] = ObjectSerializer.serialize(strCode, "string"); + localVarHeaderParams['strCode2'] = ObjectSerializer.serialize(strCode2, "string"); + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'PATCH', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + body: ObjectSerializer.serialize(patchUsersUserIdRequest, "PatchUsersUserIdRequest") + }; + + let authenticationPromise = Promise.resolve(); + authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); + + let interceptorPromise = authenticationPromise; + for (const interceptor of this.interceptors) { + interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); + } + + return interceptorPromise.then(() => { + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.IncomingMessage; body: User; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "User"); + resolve({ response: response, body: body }); + } else { + reject(new HttpError(response, body, response.statusCode)); + } + } + }); + }); + }); + } +} diff --git a/samples/client/petstore/typescript-node/3_0/git_push.sh b/samples/client/petstore/typescript-node/3_0/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +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://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/typescript-node/3_0/model/group.ts b/samples/client/petstore/typescript-node/3_0/model/group.ts new file mode 100644 index 000000000000..cd52c6bbd3b3 --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/model/group.ts @@ -0,0 +1,46 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { RequestFile } from './models'; + +/** +* +*/ +export class Group { + /** + * Unique identifier for the given group. + */ + 'id': number; + /** + * @deprecated + */ + '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 Group.attributeTypeMap; + } +} + diff --git a/samples/client/petstore/typescript-node/3_0/model/models.ts b/samples/client/petstore/typescript-node/3_0/model/models.ts new file mode 100644 index 000000000000..01b62488cb90 --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/model/models.ts @@ -0,0 +1,278 @@ +import localVarRequest from 'request'; + +export * from './group'; +export * from './patchUsersUserIdRequest'; +export * from './postUserRequest'; +export * from './user'; + +import * as fs from 'fs'; + +export interface RequestDetailedFile { + value: Buffer; + options?: { + filename?: string; + contentType?: string; + } +} + +export type RequestFile = string | Buffer | fs.ReadStream | RequestDetailedFile; + + +import { Group } from './group'; +import { PatchUsersUserIdRequest } from './patchUsersUserIdRequest'; +import { PostUserRequest } from './postUserRequest'; +import { User } from './user'; + +/* tslint:disable:no-unused-variable */ +let primitives = [ + "string", + "boolean", + "double", + "integer", + "long", + "float", + "number", + "any" + ]; + +let enumsMap: {[index: string]: any} = { +} + +let typeMap: {[index: string]: any} = { + "Group": Group, + "PatchUsersUserIdRequest": PatchUsersUserIdRequest, + "PostUserRequest": PostUserRequest, + "User": User, +} + +// Check if a string starts with another string without using es6 features +function startsWith(str: string, match: string): boolean { + return str.substring(0, match.length) === match; +} + +// Check if a string ends with another string without using es6 features +function endsWith(str: string, match: string): boolean { + return str.length >= match.length && str.substring(str.length - match.length) === match; +} + +const nullableSuffix = " | null"; +const optionalSuffix = " | undefined"; +const arrayPrefix = "Array<"; +const arraySuffix = ">"; +const mapPrefix = "{ [key: string]: "; +const mapSuffix = "; }"; + +export 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]) { + var discriminatorType = data[discriminatorProperty]; + if(typeMap[discriminatorType]){ + return discriminatorType; // use the type given in the discriminator + } else { + return expectedType; // discriminator did not map to a type + } + } else { + return expectedType; // discriminator was not present (or an empty string) + } + } + } + } + + public static serialize(data: any, type: string): any { + if (data == undefined) { + return data; + } else if (primitives.indexOf(type.toLowerCase()) !== -1) { + return data; + } else if (endsWith(type, nullableSuffix)) { + let subType: string = type.slice(0, -nullableSuffix.length); // Type | null => Type + return ObjectSerializer.serialize(data, subType); + } else if (endsWith(type, optionalSuffix)) { + let subType: string = type.slice(0, -optionalSuffix.length); // Type | undefined => Type + return ObjectSerializer.serialize(data, subType); + } else if (startsWith(type, arrayPrefix)) { + let subType: string = type.slice(arrayPrefix.length, -arraySuffix.length); // Array => Type + let transformedData: any[] = []; + for (let index = 0; index < data.length; index++) { + let datum = data[index]; + transformedData.push(ObjectSerializer.serialize(datum, subType)); + } + return transformedData; + } else if (startsWith(type, mapPrefix)) { + let subType: string = type.slice(mapPrefix.length, -mapSuffix.length); // { [key: string]: Type; } => Type + let transformedData: { [key: string]: any } = {}; + for (let key in data) { + transformedData[key] = ObjectSerializer.serialize( + data[key], + subType, + ); + } + return transformedData; + } else if (type === "Date") { + return data.toISOString(); + } else { + if (enumsMap[type]) { + return data; + } + if (!typeMap[type]) { // in case we dont know the type + return data; + } + + // Get the actual type of this object + type = this.findCorrectType(data, type); + + // get the map for the correct type. + let attributeTypes = typeMap[type].getAttributeTypeMap(); + let instance: {[index: string]: any} = {}; + for (let index = 0; index < attributeTypes.length; index++) { + let attributeType = attributeTypes[index]; + instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type); + } + return instance; + } + } + + public static deserialize(data: any, type: string): any { + // 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 (endsWith(type, nullableSuffix)) { + let subType: string = type.slice(0, -nullableSuffix.length); // Type | null => Type + return ObjectSerializer.deserialize(data, subType); + } else if (endsWith(type, optionalSuffix)) { + let subType: string = type.slice(0, -optionalSuffix.length); // Type | undefined => Type + return ObjectSerializer.deserialize(data, subType); + } else if (startsWith(type, arrayPrefix)) { + let subType: string = type.slice(arrayPrefix.length, -arraySuffix.length); // Array => Type + let transformedData: any[] = []; + for (let index = 0; index < data.length; index++) { + let datum = data[index]; + transformedData.push(ObjectSerializer.deserialize(datum, subType)); + } + return transformedData; + } else if (startsWith(type, mapPrefix)) { + let subType: string = type.slice(mapPrefix.length, -mapSuffix.length); // { [key: string]: Type; } => Type + let transformedData: { [key: string]: any } = {}; + for (let key in data) { + transformedData[key] = ObjectSerializer.deserialize( + data[key], + 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 = 0; index < attributeTypes.length; index++) { + let attributeType = attributeTypes[index]; + instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type); + } + return instance; + } + } +} + +export interface Authentication { + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: localVarRequest.Options): Promise | 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 HttpBearerAuth implements Authentication { + public accessToken: string | (() => string) = ''; + + applyToRequest(requestOptions: localVarRequest.Options): void { + if (requestOptions && requestOptions.headers) { + const accessToken = typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + requestOptions.headers["Authorization"] = "Bearer " + accessToken; + } + } +} + +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; + } else if (this.location == 'cookie' && requestOptions && requestOptions.headers) { + if (requestOptions.headers['Cookie']) { + requestOptions.headers['Cookie'] += '; ' + this.paramName + '=' + encodeURIComponent(this.apiKey); + } + else { + requestOptions.headers['Cookie'] = this.paramName + '=' + encodeURIComponent(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 type Interceptor = (requestOptions: localVarRequest.Options) => (Promise | void); diff --git a/samples/client/petstore/typescript-node/3_0/model/patchUsersUserIdRequest.ts b/samples/client/petstore/typescript-node/3_0/model/patchUsersUserIdRequest.ts new file mode 100644 index 000000000000..3b5adbe239ea --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/model/patchUsersUserIdRequest.ts @@ -0,0 +1,52 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { RequestFile } from './models'; + +export class PatchUsersUserIdRequest { + 'firstName'?: string; + 'lastName'?: string; + /** + * If a new email is given, the user\'s email verified property will be set to false. + */ + 'email'?: string; + 'dateOfBirth'?: string; + + static discriminator: string | undefined = undefined; + + static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ + { + "name": "firstName", + "baseName": "firstName", + "type": "string" + }, + { + "name": "lastName", + "baseName": "lastName", + "type": "string" + }, + { + "name": "email", + "baseName": "email", + "type": "string" + }, + { + "name": "dateOfBirth", + "baseName": "dateOfBirth", + "type": "string" + } ]; + + static getAttributeTypeMap() { + return PatchUsersUserIdRequest.attributeTypeMap; + } +} + diff --git a/samples/client/petstore/typescript-node/3_0/model/postUserRequest.ts b/samples/client/petstore/typescript-node/3_0/model/postUserRequest.ts new file mode 100644 index 000000000000..7faa6be22328 --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/model/postUserRequest.ts @@ -0,0 +1,49 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { RequestFile } from './models'; + +export class PostUserRequest { + 'firstName': string; + 'lastName': string; + 'email': string; + 'dateOfBirth': string; + + static discriminator: string | undefined = undefined; + + static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ + { + "name": "firstName", + "baseName": "firstName", + "type": "string" + }, + { + "name": "lastName", + "baseName": "lastName", + "type": "string" + }, + { + "name": "email", + "baseName": "email", + "type": "string" + }, + { + "name": "dateOfBirth", + "baseName": "dateOfBirth", + "type": "string" + } ]; + + static getAttributeTypeMap() { + return PostUserRequest.attributeTypeMap; + } +} + diff --git a/samples/client/petstore/typescript-node/3_0/model/user.ts b/samples/client/petstore/typescript-node/3_0/model/user.ts new file mode 100644 index 000000000000..bb20eb669d94 --- /dev/null +++ b/samples/client/petstore/typescript-node/3_0/model/user.ts @@ -0,0 +1,87 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { RequestFile } from './models'; + +/** +* +*/ +export class User { + /** + * Unique identifier for the given user. + */ + 'id': number; + 'firstName': string; + 'lastName': string; + 'email': string; + 'dateOfBirth'?: string; + /** + * Set to true if the user\'s email has been verified. + * + * @deprecated + */ + 'emailVerified': boolean; + /** + * The date that the user was created. + */ + 'createDate'?: string; + 'tags'?: Array; + + static discriminator: string | undefined = undefined; + + static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ + { + "name": "id", + "baseName": "id", + "type": "number" + }, + { + "name": "firstName", + "baseName": "firstName", + "type": "string" + }, + { + "name": "lastName", + "baseName": "lastName", + "type": "string" + }, + { + "name": "email", + "baseName": "email", + "type": "string" + }, + { + "name": "dateOfBirth", + "baseName": "dateOfBirth", + "type": "string" + }, + { + "name": "emailVerified", + "baseName": "emailVerified", + "type": "boolean" + }, + { + "name": "createDate", + "baseName": "createDate", + "type": "string" + }, + { + "name": "tags", + "baseName": "tags", + "type": "Array" + } ]; + + static getAttributeTypeMap() { + return User.attributeTypeMap; + } +} + diff --git a/samples/client/petstore/typescript-node/default/api/advancedApi.ts b/samples/client/petstore/typescript-node/default/api/advancedApi.ts new file mode 100644 index 000000000000..7a1cb0de90ca --- /dev/null +++ b/samples/client/petstore/typescript-node/default/api/advancedApi.ts @@ -0,0 +1,252 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import localVarRequest from 'request'; +import http from 'http'; + +/* tslint:disable:no-unused-locals */ +import { Group } from '../model/group'; +import { User } from '../model/user'; + +import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models'; +import { HttpBasicAuth, HttpBearerAuth, ApiKeyAuth, OAuth } from '../model/models'; + +import { HttpError, RequestFile } from './apis'; + +let defaultBasePath = 'http://localhost:5000/v1'; + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +export enum AdvancedApiApiKeys { + ApiKeyAuth, +} + +export class AdvancedApi { + protected _basePath = defaultBasePath; + protected _defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; + + protected authentications = { + 'default': new VoidAuth(), + 'BasicAuth': new HttpBasicAuth(), + 'BearerAuth': new HttpBearerAuth(), + 'ApiKeyAuth': new ApiKeyAuth('header', 'X-API-Key'), + } + + protected interceptors: Interceptor[] = []; + + constructor(basePath?: string); + constructor(username: string, password: string, basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + this.username = basePathOrUsername; + this.password = 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; + } + + set defaultHeaders(defaultHeaders: any) { + this._defaultHeaders = defaultHeaders; + } + + get defaultHeaders() { + return this._defaultHeaders; + } + + get basePath() { + return this._basePath; + } + + public setDefaultAuthentication(auth: Authentication) { + this.authentications.default = auth; + } + + public setApiKey(key: AdvancedApiApiKeys, value: string) { + (this.authentications as any)[AdvancedApiApiKeys[key]].apiKey = value; + } + + set username(username: string) { + this.authentications.BasicAuth.username = username; + } + + set password(password: string) { + this.authentications.BasicAuth.password = password; + } + + set accessToken(accessToken: string | (() => string)) { + this.authentications.BearerAuth.accessToken = accessToken; + } + + public addInterceptor(interceptor: Interceptor) { + this.interceptors.push(interceptor); + } + + /** + * Get group of users + * @summary Get group by ID + * @param groupId group Id + */ + public async getGroupsGroupId (groupId: number, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: Group; }> { + const localVarPath = this.basePath + '/groups/{groupId}' + .replace('{' + 'groupId' + '}', encodeURIComponent(String(groupId))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this._defaultHeaders); + const produces = ['application/json']; + // give precedence to 'application/json' + if (produces.indexOf('application/json') >= 0) { + localVarHeaderParams.Accept = 'application/json'; + } else { + localVarHeaderParams.Accept = produces.join(','); + } + let localVarFormParams: any = {}; + + // verify required parameter 'groupId' is not null or undefined + if (groupId === null || groupId === undefined) { + throw new Error('Required parameter groupId was null or undefined when calling getGroupsGroupId.'); + } + + (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, + }; + + let authenticationPromise = Promise.resolve(); + authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); + + let interceptorPromise = authenticationPromise; + for (const interceptor of this.interceptors) { + interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); + } + + return interceptorPromise.then(() => { + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.IncomingMessage; body: Group; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Group"); + resolve({ response: response, body: body }); + } else { + reject(new HttpError(response, body, response.statusCode)); + } + } + }); + }); + }); + } + /** + * Retrieve the information of the user with the matching user ID. + * @summary Get User Info by User ID + * @param userId Id of an existing user. + * @param strCode Code as header + * @param strCode2 Code as header2 + */ + public async getUsersUserId (userId: number, strCode?: string, strCode2?: string, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: User; }> { + const localVarPath = this.basePath + '/users/{userId}' + .replace('{' + 'userId' + '}', encodeURIComponent(String(userId))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this._defaultHeaders); + const produces = ['application/json']; + // give precedence to 'application/json' + if (produces.indexOf('application/json') >= 0) { + localVarHeaderParams.Accept = 'application/json'; + } else { + localVarHeaderParams.Accept = produces.join(','); + } + let localVarFormParams: any = {}; + + // verify required parameter 'userId' is not null or undefined + if (userId === null || userId === undefined) { + throw new Error('Required parameter userId was null or undefined when calling getUsersUserId.'); + } + + localVarHeaderParams['strCode'] = ObjectSerializer.serialize(strCode, "string"); + localVarHeaderParams['strCode2'] = ObjectSerializer.serialize(strCode2, "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, + }; + + let authenticationPromise = Promise.resolve(); + authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); + + let interceptorPromise = authenticationPromise; + for (const interceptor of this.interceptors) { + interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); + } + + return interceptorPromise.then(() => { + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.IncomingMessage; body: User; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "User"); + resolve({ response: response, body: body }); + } else { + reject(new HttpError(response, body, response.statusCode)); + } + } + }); + }); + }); + } +} diff --git a/samples/client/petstore/typescript-node/default/api/basicApi.ts b/samples/client/petstore/typescript-node/default/api/basicApi.ts new file mode 100644 index 000000000000..8fa911ff35e8 --- /dev/null +++ b/samples/client/petstore/typescript-node/default/api/basicApi.ts @@ -0,0 +1,250 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import localVarRequest from 'request'; +import http from 'http'; + +/* tslint:disable:no-unused-locals */ +import { PostUserRequest } from '../model/postUserRequest'; +import { User } from '../model/user'; + +import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models'; +import { HttpBasicAuth, HttpBearerAuth, ApiKeyAuth, OAuth } from '../model/models'; + +import { HttpError, RequestFile } from './apis'; + +let defaultBasePath = 'http://localhost:5000/v1'; + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +export enum BasicApiApiKeys { + ApiKeyAuth, +} + +export class BasicApi { + protected _basePath = defaultBasePath; + protected _defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; + + protected authentications = { + 'default': new VoidAuth(), + 'BasicAuth': new HttpBasicAuth(), + 'BearerAuth': new HttpBearerAuth(), + 'ApiKeyAuth': new ApiKeyAuth('header', 'X-API-Key'), + } + + protected interceptors: Interceptor[] = []; + + constructor(basePath?: string); + constructor(username: string, password: string, basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + this.username = basePathOrUsername; + this.password = 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; + } + + set defaultHeaders(defaultHeaders: any) { + this._defaultHeaders = defaultHeaders; + } + + get defaultHeaders() { + return this._defaultHeaders; + } + + get basePath() { + return this._basePath; + } + + public setDefaultAuthentication(auth: Authentication) { + this.authentications.default = auth; + } + + public setApiKey(key: BasicApiApiKeys, value: string) { + (this.authentications as any)[BasicApiApiKeys[key]].apiKey = value; + } + + set username(username: string) { + this.authentications.BasicAuth.username = username; + } + + set password(password: string) { + this.authentications.BasicAuth.password = password; + } + + set accessToken(accessToken: string | (() => string)) { + this.authentications.BearerAuth.accessToken = accessToken; + } + + public addInterceptor(interceptor: Interceptor) { + this.interceptors.push(interceptor); + } + + /** + * Retrieve the information of the user with the matching user ID. + * @summary Get User Info by Query Param + * @param pUserId Query Id. + * @param customHeader Custom HTTP header + * @param anotherCustomHeader Custom HTTP header with default + */ + public async getUsersQueryId (pUserId: string, customHeader?: string, anotherCustomHeader?: string, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: User; }> { + const localVarPath = this.basePath + '/users/'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this._defaultHeaders); + const produces = ['application/json']; + // give precedence to 'application/json' + if (produces.indexOf('application/json') >= 0) { + localVarHeaderParams.Accept = 'application/json'; + } else { + localVarHeaderParams.Accept = produces.join(','); + } + let localVarFormParams: any = {}; + + // verify required parameter 'pUserId' is not null or undefined + if (pUserId === null || pUserId === undefined) { + throw new Error('Required parameter pUserId was null or undefined when calling getUsersQueryId.'); + } + + if (pUserId !== undefined) { + localVarQueryParameters['pUserId'] = ObjectSerializer.serialize(pUserId, "string"); + } + + localVarHeaderParams['Custom-Header'] = ObjectSerializer.serialize(customHeader, "string"); + localVarHeaderParams['Another-Custom-Header'] = ObjectSerializer.serialize(anotherCustomHeader, "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, + }; + + let authenticationPromise = Promise.resolve(); + authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); + + let interceptorPromise = authenticationPromise; + for (const interceptor of this.interceptors) { + interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); + } + + return interceptorPromise.then(() => { + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.IncomingMessage; body: User; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "User"); + resolve({ response: response, body: body }); + } else { + reject(new HttpError(response, body, response.statusCode)); + } + } + }); + }); + }); + } + /** + * Create a new user. + * @summary Create New User + * @param postUserRequest Post the necessary fields for the API to create a new user. + */ + public async postUser (postUserRequest?: PostUserRequest, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: User; }> { + const localVarPath = this.basePath + '/user'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this._defaultHeaders); + const produces = ['application/json']; + // give precedence to 'application/json' + if (produces.indexOf('application/json') >= 0) { + localVarHeaderParams.Accept = 'application/json'; + } else { + localVarHeaderParams.Accept = produces.join(','); + } + let localVarFormParams: any = {}; + + (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(postUserRequest, "PostUserRequest") + }; + + let authenticationPromise = Promise.resolve(); + authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); + + let interceptorPromise = authenticationPromise; + for (const interceptor of this.interceptors) { + interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); + } + + return interceptorPromise.then(() => { + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.IncomingMessage; body: User; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "User"); + resolve({ response: response, body: body }); + } else { + reject(new HttpError(response, body, response.statusCode)); + } + } + }); + }); + }); + } +} diff --git a/samples/client/petstore/typescript-node/default/api/defaultApi.ts b/samples/client/petstore/typescript-node/default/api/defaultApi.ts new file mode 100644 index 000000000000..9786eacce900 --- /dev/null +++ b/samples/client/petstore/typescript-node/default/api/defaultApi.ts @@ -0,0 +1,185 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import localVarRequest from 'request'; +import http from 'http'; + +/* tslint:disable:no-unused-locals */ +import { PatchUsersUserIdRequest } from '../model/patchUsersUserIdRequest'; +import { User } from '../model/user'; + +import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models'; +import { HttpBasicAuth, HttpBearerAuth, ApiKeyAuth, OAuth } from '../model/models'; + +import { HttpError, RequestFile } from './apis'; + +let defaultBasePath = 'http://localhost:5000/v1'; + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +export enum DefaultApiApiKeys { + ApiKeyAuth, +} + +export class DefaultApi { + protected _basePath = defaultBasePath; + protected _defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; + + protected authentications = { + 'default': new VoidAuth(), + 'BasicAuth': new HttpBasicAuth(), + 'BearerAuth': new HttpBearerAuth(), + 'ApiKeyAuth': new ApiKeyAuth('header', 'X-API-Key'), + } + + protected interceptors: Interceptor[] = []; + + constructor(basePath?: string); + constructor(username: string, password: string, basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + this.username = basePathOrUsername; + this.password = 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; + } + + set defaultHeaders(defaultHeaders: any) { + this._defaultHeaders = defaultHeaders; + } + + get defaultHeaders() { + return this._defaultHeaders; + } + + get basePath() { + return this._basePath; + } + + public setDefaultAuthentication(auth: Authentication) { + this.authentications.default = auth; + } + + public setApiKey(key: DefaultApiApiKeys, value: string) { + (this.authentications as any)[DefaultApiApiKeys[key]].apiKey = value; + } + + set username(username: string) { + this.authentications.BasicAuth.username = username; + } + + set password(password: string) { + this.authentications.BasicAuth.password = password; + } + + set accessToken(accessToken: string | (() => string)) { + this.authentications.BearerAuth.accessToken = accessToken; + } + + public addInterceptor(interceptor: Interceptor) { + this.interceptors.push(interceptor); + } + + /** + * Update the information of an existing user. + * @summary Update User Information + * @param userId Id of an existing user. + * @param strCode Code as header + * @param strCode2 Code as header2 + * @param patchUsersUserIdRequest Patch user properties to update. + */ + public async patchUsersUserId (userId: number, strCode?: string, strCode2?: string, patchUsersUserIdRequest?: PatchUsersUserIdRequest, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: User; }> { + const localVarPath = this.basePath + '/users/{userId}' + .replace('{' + 'userId' + '}', encodeURIComponent(String(userId))); + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign({}, this._defaultHeaders); + const produces = ['application/json']; + // give precedence to 'application/json' + if (produces.indexOf('application/json') >= 0) { + localVarHeaderParams.Accept = 'application/json'; + } else { + localVarHeaderParams.Accept = produces.join(','); + } + let localVarFormParams: any = {}; + + // verify required parameter 'userId' is not null or undefined + if (userId === null || userId === undefined) { + throw new Error('Required parameter userId was null or undefined when calling patchUsersUserId.'); + } + + localVarHeaderParams['strCode'] = ObjectSerializer.serialize(strCode, "string"); + localVarHeaderParams['strCode2'] = ObjectSerializer.serialize(strCode2, "string"); + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'PATCH', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + body: ObjectSerializer.serialize(patchUsersUserIdRequest, "PatchUsersUserIdRequest") + }; + + let authenticationPromise = Promise.resolve(); + authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); + + let interceptorPromise = authenticationPromise; + for (const interceptor of this.interceptors) { + interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); + } + + return interceptorPromise.then(() => { + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; + } + } + return new Promise<{ response: http.IncomingMessage; body: User; }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "User"); + resolve({ response: response, body: body }); + } else { + reject(new HttpError(response, body, response.statusCode)); + } + } + }); + }); + }); + } +} diff --git a/samples/client/petstore/typescript-node/default/model/group.ts b/samples/client/petstore/typescript-node/default/model/group.ts new file mode 100644 index 000000000000..cd52c6bbd3b3 --- /dev/null +++ b/samples/client/petstore/typescript-node/default/model/group.ts @@ -0,0 +1,46 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { RequestFile } from './models'; + +/** +* +*/ +export class Group { + /** + * Unique identifier for the given group. + */ + 'id': number; + /** + * @deprecated + */ + '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 Group.attributeTypeMap; + } +} + diff --git a/samples/client/petstore/typescript-node/default/model/patchUsersUserIdRequest.ts b/samples/client/petstore/typescript-node/default/model/patchUsersUserIdRequest.ts new file mode 100644 index 000000000000..3b5adbe239ea --- /dev/null +++ b/samples/client/petstore/typescript-node/default/model/patchUsersUserIdRequest.ts @@ -0,0 +1,52 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { RequestFile } from './models'; + +export class PatchUsersUserIdRequest { + 'firstName'?: string; + 'lastName'?: string; + /** + * If a new email is given, the user\'s email verified property will be set to false. + */ + 'email'?: string; + 'dateOfBirth'?: string; + + static discriminator: string | undefined = undefined; + + static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ + { + "name": "firstName", + "baseName": "firstName", + "type": "string" + }, + { + "name": "lastName", + "baseName": "lastName", + "type": "string" + }, + { + "name": "email", + "baseName": "email", + "type": "string" + }, + { + "name": "dateOfBirth", + "baseName": "dateOfBirth", + "type": "string" + } ]; + + static getAttributeTypeMap() { + return PatchUsersUserIdRequest.attributeTypeMap; + } +} + diff --git a/samples/client/petstore/typescript-node/default/model/postUserRequest.ts b/samples/client/petstore/typescript-node/default/model/postUserRequest.ts new file mode 100644 index 000000000000..7faa6be22328 --- /dev/null +++ b/samples/client/petstore/typescript-node/default/model/postUserRequest.ts @@ -0,0 +1,49 @@ +/** + * Sample project + * Sample API Check \"API Key\" + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { RequestFile } from './models'; + +export class PostUserRequest { + 'firstName': string; + 'lastName': string; + 'email': string; + 'dateOfBirth': string; + + static discriminator: string | undefined = undefined; + + static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ + { + "name": "firstName", + "baseName": "firstName", + "type": "string" + }, + { + "name": "lastName", + "baseName": "lastName", + "type": "string" + }, + { + "name": "email", + "baseName": "email", + "type": "string" + }, + { + "name": "dateOfBirth", + "baseName": "dateOfBirth", + "type": "string" + } ]; + + static getAttributeTypeMap() { + return PostUserRequest.attributeTypeMap; + } +} +