From f9ad16e7aa7a96ec558696a2e5ec95bfdd06b8d0 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 22 Jul 2015 17:45:31 +0800 Subject: [PATCH 01/33] Update objc client. * Add test cases for deserialization. * Pretty print model infomation. --- .../main/resources/objc/model-body.mustache | 6 +- .../petstore/objc/SwaggerClient/SWGCategory.m | 6 +- .../petstore/objc/SwaggerClient/SWGOrder.m | 6 +- .../petstore/objc/SwaggerClient/SWGPet.m | 6 +- .../petstore/objc/SwaggerClient/SWGTag.m | 6 +- .../petstore/objc/SwaggerClient/SWGUser.m | 6 +- .../SwaggerClient.xcodeproj/project.pbxproj | 8 ++ .../SwaggerClient/SWGViewController.m | 30 ++++- .../Tests/DeserializationTest.m | 119 ++++++++++++++++++ .../objc/SwaggerClientTests/Tests/PetTest.m | 37 ++++++ .../Tests/SWGApiClientTest.m | 73 ----------- 11 files changed, 222 insertions(+), 81 deletions(-) create mode 100644 samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m create mode 100644 samples/client/petstore/objc/SwaggerClientTests/Tests/PetTest.m diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index b728e6bb06c..6e93823b1f5 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -3,7 +3,7 @@ #import "{{classname}}.h" @implementation {{classname}} - + + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; @@ -21,6 +21,10 @@ } } +- (NSString *)description { + return [[self toDictionary] description]; +} + {{/model}} @end {{/models}} diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m index c41f76a5247..ebe7326d1bb 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m @@ -1,7 +1,7 @@ #import "SWGCategory.h" @implementation SWGCategory - + + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; @@ -19,4 +19,8 @@ } } +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m index 5d3179446ed..d511eee2e08 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m @@ -1,7 +1,7 @@ #import "SWGOrder.h" @implementation SWGOrder - + + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }]; @@ -19,4 +19,8 @@ } } +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.m b/samples/client/petstore/objc/SwaggerClient/SWGPet.m index d5559aa6f72..33c20c2dd20 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.m @@ -1,7 +1,7 @@ #import "SWGPet.h" @implementation SWGPet - + + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }]; @@ -19,4 +19,8 @@ } } +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.m b/samples/client/petstore/objc/SwaggerClient/SWGTag.m index 5d48a099070..5a2f395e7ad 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGTag.m @@ -1,7 +1,7 @@ #import "SWGTag.h" @implementation SWGTag - + + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; @@ -19,4 +19,8 @@ } } +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.m b/samples/client/petstore/objc/SwaggerClient/SWGUser.m index 060b65ffa12..1ee47811995 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUser.m @@ -1,7 +1,7 @@ #import "SWGUser.h" @implementation SWGUser - + + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }]; @@ -19,4 +19,8 @@ } } +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 0ba21c560ef..a5fe06f63b7 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -23,6 +23,8 @@ 6003F5BC195388D20070C39A /* Tests.m in Sources */ = {isa = PBXBuildFile; fileRef = 6003F5BB195388D20070C39A /* Tests.m */; }; 873B8AEB1B1F5CCA007FD442 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 873B8AEA1B1F5CCA007FD442 /* Main.storyboard */; }; 94BE6BE84795B5034A811E61 /* libPods-SwaggerClient_Example.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 8D46325ECAD48245C07F6733 /* libPods-SwaggerClient_Example.a */; }; + CF0ADB481B5F95D6008A2729 /* PetTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF0ADB471B5F95D6008A2729 /* PetTest.m */; }; + CF8F71391B5F73AC00162980 /* DeserializationTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF8F71381B5F73AC00162980 /* DeserializationTest.m */; }; CFDFB4121B3CFFA8009739C5 /* UserApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CFDFB40D1B3CFEC3009739C5 /* UserApiTest.m */; }; CFDFB4131B3CFFDD009739C5 /* PetApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CFDFB40A1B3CFEC3009739C5 /* PetApiTest.m */; }; CFDFB4141B3CFFF6009739C5 /* StoreApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CFDFB40B1B3CFEC3009739C5 /* StoreApiTest.m */; }; @@ -65,6 +67,8 @@ 873B8AEA1B1F5CCA007FD442 /* Main.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = Main.storyboard; sourceTree = ""; }; 8D46325ECAD48245C07F6733 /* libPods-SwaggerClient_Example.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-SwaggerClient_Example.a"; sourceTree = BUILT_PRODUCTS_DIR; }; BFB4BE760737508B3CFC23B2 /* Pods-SwaggerClient_Example.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient_Example.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example.release.xcconfig"; sourceTree = ""; }; + CF0ADB471B5F95D6008A2729 /* PetTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PetTest.m; sourceTree = ""; }; + CF8F71381B5F73AC00162980 /* DeserializationTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DeserializationTest.m; sourceTree = ""; }; CFDFB40A1B3CFEC3009739C5 /* PetApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PetApiTest.m; sourceTree = ""; }; CFDFB40B1B3CFEC3009739C5 /* StoreApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = StoreApiTest.m; sourceTree = ""; }; CFDFB40C1B3CFEC3009739C5 /* SWGApiClientTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiClientTest.m; sourceTree = ""; }; @@ -166,6 +170,8 @@ CFDFB40A1B3CFEC3009739C5 /* PetApiTest.m */, CFDFB40B1B3CFEC3009739C5 /* StoreApiTest.m */, CFDFB40C1B3CFEC3009739C5 /* SWGApiClientTest.m */, + CF0ADB471B5F95D6008A2729 /* PetTest.m */, + CF8F71381B5F73AC00162980 /* DeserializationTest.m */, CFDFB40D1B3CFEC3009739C5 /* UserApiTest.m */, 6003F5BB195388D20070C39A /* Tests.m */, 6003F5B6195388D20070C39A /* Supporting Files */, @@ -374,10 +380,12 @@ buildActionMask = 2147483647; files = ( CFDFB4141B3CFFF6009739C5 /* StoreApiTest.m in Sources */, + CF0ADB481B5F95D6008A2729 /* PetTest.m in Sources */, CFDFB4131B3CFFDD009739C5 /* PetApiTest.m in Sources */, 6003F5BC195388D20070C39A /* Tests.m in Sources */, CFDFB4151B3D000B009739C5 /* SWGApiClientTest.m in Sources */, CFDFB4121B3CFFA8009739C5 /* UserApiTest.m in Sources */, + CF8F71391B5F73AC00162980 /* DeserializationTest.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m index a56f31408aa..d538fe49fdc 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m @@ -7,6 +7,7 @@ // #import "SWGViewController.h" +#import @interface SWGViewController () @@ -17,13 +18,38 @@ - (void)viewDidLoad { [super viewDidLoad]; - // Do any additional setup after loading the view, typically from a nib. + SWGPet *pet = [self createPet]; + NSLog(@"%@", pet); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; - // Dispose of any resources that can be recreated. +} + +- (SWGPet*) createPet { + SWGPet * pet = [[SWGPet alloc] init]; + pet._id = [[NSNumber alloc] initWithLong:[[NSDate date] timeIntervalSince1970]]; + pet.name = @"monkey"; + + SWGCategory * category = [[SWGCategory alloc] init]; + category._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; + category.name = @"super-happy"; + pet.category = category; + + SWGTag *tag1 = [[SWGTag alloc] init]; + tag1._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; + tag1.name = @"test tag 1"; + SWGTag *tag2 = [[SWGTag alloc] init]; + tag2._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; + tag2.name = @"test tag 2"; + pet.tags = (NSArray *)[[NSArray alloc] initWithObjects:tag1, tag2, nil]; + + pet.status = @"available"; + + NSArray * photos = [[NSArray alloc] initWithObjects:@"http://foo.bar.com/3", @"http://foo.bar.com/4", nil]; + pet.photoUrls = photos; + return pet; } @end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m new file mode 100644 index 00000000000..2650dde31d0 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m @@ -0,0 +1,119 @@ +#import +#import +#import +#import + +@interface DeserializationTest : XCTestCase { + +@private SWGApiClient *apiClient; + +} + +@end + +@implementation DeserializationTest + +- (void)setUp { + [super setUp]; + apiClient = [[SWGApiClient alloc] init]; +} + +- (void)testDeserializeDate { + NSString *dateStr = @"2012-09-27"; + + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + NSTimeZone *timezone = [NSTimeZone timeZoneWithName:@"UTC"]; + [formatter setTimeZone:timezone]; + [formatter setDateFormat:@"yyyy-MM-dd"]; + NSDate *date = [formatter dateFromString:dateStr]; + + NSDate *deserializedDate = [apiClient deserialize:dateStr class:@"NSDate*"]; + + XCTAssertEqualWithAccuracy([date timeIntervalSinceReferenceDate], [deserializedDate timeIntervalSinceReferenceDate], 0.001); +} + +- (void)testDeserializeDateTime { + NSString *dateTimeStr = @"1997-07-16T19:20:30+00:00"; + + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; + NSDate *dateTime = [formatter dateFromString:dateTimeStr]; + + NSDate *deserializedDateTime = [apiClient deserialize:dateTimeStr class:@"NSDate*"]; + + XCTAssertEqualWithAccuracy([dateTime timeIntervalSinceReferenceDate], [deserializedDateTime timeIntervalSinceReferenceDate], 0.001); +} + +- (void)testDeserializeObject { + XCTAssertTrue([[apiClient deserialize:@"" class:@"NSObject*"] isKindOfClass:[NSObject class]]); +} + +- (void)testDeserializeString { + NSString *data = @"test string"; + NSString *result = [apiClient deserialize:data class:@"NSString*"]; + + XCTAssertTrue([result isEqualToString:data]); +} + +- (void)testDeserializeListOfModels { + NSArray *data = + @[ + @{ + @"id": @119, + @"category": @{ + @"id": @0, + @"name": @"string" + }, + @"name": @"doggie", + @"photoUrls": @[ + @"string" + ], + @"tags": @[ + @{ + @"id": @0, + @"name": @"string" + } + ], + @"status": @"available" + + }]; + + NSArray *result = [apiClient deserialize:data class:@"NSArray*"]; + + XCTAssertTrue([result isKindOfClass:[NSArray class]]); + XCTAssertTrue([[result firstObject] isKindOfClass:[SWGPet class]]); + XCTAssertEqualObjects([[result firstObject] _id], @119); +} + +- (void)testDeserializeMapOfModels { + NSDictionary *data = + @{ + @"pet": @{ + @"id": @119, + @"category": @{ + @"id": @0, + @"name": @"string" + }, + @"name": @"doggie", + @"photoUrls": @[ + @"string" + ], + @"tags": @[ + @{ + @"id": @0, + @"name": @"string" + } + ], + @"status": @"available" + + } + }; + + NSDictionary *result = [apiClient deserialize:data class:@"NSDictionary* /* NSString, SWGPet */"]; + + XCTAssertTrue([result isKindOfClass:[NSDictionary class]]); + XCTAssertTrue([result[@"pet"] isKindOfClass:[SWGPet class]]); + XCTAssertEqualObjects([result[@"pet"] _id], @119); +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetTest.m new file mode 100644 index 00000000000..9dbde13310b --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetTest.m @@ -0,0 +1,37 @@ +#import +#import +#import + +@interface PetTest : XCTestCase { + +@private SWGPet *pet; + +} + +@end + +@implementation PetTest + +- (void)setUp { + [super setUp]; + + NSDictionary *petDict = @{ @"id": @1, @"name": @"test pet", + @"status": @"sold", + @"photoUrls": @[@"string"], + @"category": @{ @"id": @1, @"name": @"test category" }, + @"tags": @[ @{ @"id": @1, @"name": @"test tag" } ]}; + pet = [[SWGPet alloc] initWithDictionary:petDict error:nil]; +} + +- (void)testDescription { + NSDictionary *petDict = @{ @"id": @1, @"name": @"test pet", + @"status": @"sold", + @"photoUrls": @[@"string"], + @"category": @{ @"id": @1, @"name": @"test category" }, + @"tags": @[ @{ @"id": @1, @"name": @"test tag" } ]}; + NSString *petStr = [petDict description]; + + XCTAssertTrue([[pet description] isEqualToString:petStr]); +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m index 00c6bf70da6..6365632ea2d 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m @@ -98,77 +98,4 @@ XCTAssertEqualObjects(basicAuthCredentials, [config getBasicAuthToken]); } -- (void)testDeserialize { - id data; - id result; - - // list of models - data = - @[ - @{ - @"id": @119, - @"category": @{ - @"id": @0, - @"name": @"string" - }, - @"name": @"doggie", - @"photoUrls": @[ - @"string" - ], - @"tags": @[ - @{ - @"id": @0, - @"name": @"string" - } - ], - @"status": @"available" - - }]; - result = [self.apiClient deserialize:data class:@"NSArray*"]; - - XCTAssertTrue([result isKindOfClass:[NSArray class]]); - XCTAssertTrue([[result firstObject] isKindOfClass:[SWGPet class]]); - XCTAssertEqualObjects([[result firstObject] _id], @119); - - // map of models - data = - @{ - @"pet": @{ - @"id": @119, - @"category": @{ - @"id": @0, - @"name": @"string" - }, - @"name": @"doggie", - @"photoUrls": @[ - @"string" - ], - @"tags": @[ - @{ - @"id": @0, - @"name": @"string" - } - ], - @"status": @"available" - - } - }; - result = [self.apiClient deserialize:data class:@"NSDictionary* /* NSString, SWGPet */"]; - - XCTAssertTrue([result isKindOfClass:[NSDictionary class]]); - XCTAssertTrue([result[@"pet"] isKindOfClass:[SWGPet class]]); - XCTAssertEqualObjects([result[@"pet"] _id], @119); - - // pure object - result = [self.apiClient deserialize:@"" class:@"NSObject*"]; - - XCTAssertTrue([result isKindOfClass:[NSObject class]]); - - // NSString - data = @"test string"; - result = [self.apiClient deserialize:data class:@"NSString*"]; - - XCTAssertTrue([result isKindOfClass:[NSString class]]); -} - @end From 37c79525f7b6ecf7c776301474f0ec6dbd734ec3 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 22 Jul 2015 18:31:50 +0800 Subject: [PATCH 02/33] Update model body template in objc client. * Add some comments. --- .../src/main/resources/objc/model-body.mustache | 13 +++++++++++++ .../petstore/objc/SwaggerClient/SWGCategory.m | 13 +++++++++++++ .../client/petstore/objc/SwaggerClient/SWGOrder.m | 13 +++++++++++++ samples/client/petstore/objc/SwaggerClient/SWGPet.m | 13 +++++++++++++ samples/client/petstore/objc/SwaggerClient/SWGTag.m | 13 +++++++++++++ .../client/petstore/objc/SwaggerClient/SWGUser.m | 13 +++++++++++++ 6 files changed, 78 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index 6e93823b1f5..4ce1155a820 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -4,11 +4,20 @@ @implementation {{classname}} +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, or return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; @@ -21,6 +30,10 @@ } } +/** + * Return a string that represents the properties json of the model. + * This method will be called when logging model object using `NSLog`. + */ - (NSString *)description { return [[self toDictionary] description]; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m index ebe7326d1bb..8d41527ea2a 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m @@ -2,11 +2,20 @@ @implementation SWGCategory +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, or return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"name"]; @@ -19,6 +28,10 @@ } } +/** + * Return a string that represents the properties json of the model. + * This method will be called when logging model object using `NSLog`. + */ - (NSString *)description { return [[self toDictionary] description]; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m index d511eee2e08..950edd796a9 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m @@ -2,11 +2,20 @@ @implementation SWGOrder +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, or return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"]; @@ -19,6 +28,10 @@ } } +/** + * Return a string that represents the properties json of the model. + * This method will be called when logging model object using `NSLog`. + */ - (NSString *)description { return [[self toDictionary] description]; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.m b/samples/client/petstore/objc/SwaggerClient/SWGPet.m index 33c20c2dd20..48a0940338c 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.m @@ -2,11 +2,20 @@ @implementation SWGPet +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, or return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"category", @"tags", @"status"]; @@ -19,6 +28,10 @@ } } +/** + * Return a string that represents the properties json of the model. + * This method will be called when logging model object using `NSLog`. + */ - (NSString *)description { return [[self toDictionary] description]; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.m b/samples/client/petstore/objc/SwaggerClient/SWGTag.m index 5a2f395e7ad..1ee6964e60c 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGTag.m @@ -2,11 +2,20 @@ @implementation SWGTag +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, or return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"name"]; @@ -19,6 +28,10 @@ } } +/** + * Return a string that represents the properties json of the model. + * This method will be called when logging model object using `NSLog`. + */ - (NSString *)description { return [[self toDictionary] description]; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.m b/samples/client/petstore/objc/SwaggerClient/SWGUser.m index 1ee47811995..934b91fba73 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUser.m @@ -2,11 +2,20 @@ @implementation SWGUser +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, or return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"username", @"firstName", @"lastName", @"email", @"password", @"phone", @"userStatus"]; @@ -19,6 +28,10 @@ } } +/** + * Return a string that represents the properties json of the model. + * This method will be called when logging model object using `NSLog`. + */ - (NSString *)description { return [[self toDictionary] description]; } From 08ea05f7a14fbfc02dc38ec1a33942940845e950 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 23 Jul 2015 16:03:38 +0800 Subject: [PATCH 03/33] Update objc client. * Add comments in SWGConfiguration.h * Change `Date` to `date` in ObjcClientCodegen.java * Update comments in model body template --- .../codegen/languages/ObjcClientCodegen.java | 2 +- .../objc/Configuration-body.mustache | 22 ++++--- .../objc/Configuration-header.mustache | 63 ++++++++++++++++--- .../main/resources/objc/model-body.mustache | 4 +- .../petstore/objc/SwaggerClient/SWGCategory.m | 4 +- .../objc/SwaggerClient/SWGConfiguration.h | 63 ++++++++++++++++--- .../objc/SwaggerClient/SWGConfiguration.m | 22 ++++--- .../petstore/objc/SwaggerClient/SWGOrder.m | 4 +- .../petstore/objc/SwaggerClient/SWGPet.m | 4 +- .../petstore/objc/SwaggerClient/SWGTag.m | 4 +- .../petstore/objc/SwaggerClient/SWGUser.m | 4 +- .../SwaggerClient/SWGViewController.m | 8 ++- .../Tests/SWGApiClientTest.m | 4 +- 13 files changed, 161 insertions(+), 47 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 0fdb19e806d..3e5edbc169f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -57,7 +57,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.clear(); typeMapping.put("enum", "NSString"); - typeMapping.put("Date", "NSDate"); + typeMapping.put("date", "NSDate"); typeMapping.put("DateTime", "NSDate"); typeMapping.put("boolean", "NSNumber"); typeMapping.put("string", "NSString"); diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache index 832c69f417e..75d73d6e414 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache @@ -60,12 +60,20 @@ #pragma mark - Setter Methods -- (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { - [self.mutableApiKey setValue:value forKey:field]; +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { + [self.mutableApiKey setValue:apiKey forKey:identifier]; } -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field { - [self.mutableApiKeyPrefix setValue:value forKey:field]; +- (void) removeApiKey:(NSString *)identifier { + [self.mutableApiKey removeObjectForKey:identifier]; +} + +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { + [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; +} + +- (void) removeApiKeyPrefix:(NSString *)identifier { + [self.mutableApiKeyPrefix removeObjectForKey:identifier]; } - (void) setLoggingFile:(NSString *)loggingFile { @@ -75,10 +83,10 @@ } _loggingFile = loggingFile; - self.loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (self.loggingFileHanlder == nil) { + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHanlder == nil) { [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - self.loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; } } diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache index 4f9518ea9d1..2ec6e18e9d5 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache @@ -1,26 +1,36 @@ #import +/** The `{{classPrefix}}Configuration` class manages the configurations for the sdk. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ @interface {{classPrefix}}Configuration : NSObject /** * Api key values for Api Key type Authentication * - * To add or remove api key, use `setValue:forApiKeyField:`. + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. */ @property (readonly, nonatomic, strong) NSDictionary *apiKey; /** * Api key prefix values to be prepend to the respective api key * - * To add or remove prefix, use `setValue:forApiKeyPrefixField:`. + * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. */ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename and Password for Basic type Authentication + * Usename for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication */ -@property (nonatomic) NSString *username; @property (nonatomic) NSString *password; /** @@ -31,9 +41,21 @@ /** * Logging Settings */ + +/** + * Debug switch, default false + */ @property (nonatomic) BOOL debug; + +/** + * Debug file location, default nil + */ @property (nonatomic) NSString *loggingFile; -@property (nonatomic) NSFileHandle *loggingFileHanlder; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; /** * Get configuration singleton instance @@ -41,14 +63,39 @@ + (instancetype) sharedConfig; /** - * Sets field in `apiKey` + * Sets field in `apiKey`. + * + * To remove a apiKey for a identifier, just set the apiKey to nil. + * + * @param apiKey The apiKey value. + * @param identifier The apiKey name. + * */ -- (void) setValue:(NSString *)value forApiKeyField:(NSString*)field; +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; + +/** + * Remove api key + * + * @param identifier The apiKey name. + */ +- (void) removeApiKey:(NSString *)identifier; /** * Sets field in `apiKeyPrefix` + * + * To remove a apiKeyPrefix for a identifier, just set the apiKeyPrefix to nil. + * + * @param apiKeyPrefix The apiKeyPrefix value. + * @param identifier The apiKeyPrefix name. */ -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field; +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; + +/** + * Remove api key prefix + * + * @param identifier The apiKeyPrefix name. + */ +- (void) removeApiKeyPrefix:(NSString *)identifier; /** * Get API key (with prefix if set) diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index 4ce1155a820..209cd7bf5a5 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -15,7 +15,7 @@ /** * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, or return `NO`. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ + (BOOL)propertyIsOptional:(NSString *)propertyName @@ -31,7 +31,7 @@ } /** - * Return a string that represents the properties json of the model. + * Returns a string that represents the properties json of the model. * This method will be called when logging model object using `NSLog`. */ - (NSString *)description { diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m index 8d41527ea2a..d2ac30e403b 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m @@ -13,7 +13,7 @@ /** * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, or return `NO`. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ + (BOOL)propertyIsOptional:(NSString *)propertyName @@ -29,7 +29,7 @@ } /** - * Return a string that represents the properties json of the model. + * Returns a string that represents the properties json of the model. * This method will be called when logging model object using `NSLog`. */ - (NSString *)description { diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h index d3619c72ab5..d1176257779 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h @@ -1,26 +1,36 @@ #import +/** The `SWGConfiguration` class manages the configurations for the sdk. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ @interface SWGConfiguration : NSObject /** * Api key values for Api Key type Authentication * - * To add or remove api key, use `setValue:forApiKeyField:`. + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. */ @property (readonly, nonatomic, strong) NSDictionary *apiKey; /** * Api key prefix values to be prepend to the respective api key * - * To add or remove prefix, use `setValue:forApiKeyPrefixField:`. + * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. */ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename and Password for Basic type Authentication + * Usename for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication */ -@property (nonatomic) NSString *username; @property (nonatomic) NSString *password; /** @@ -31,9 +41,21 @@ /** * Logging Settings */ + +/** + * Debug switch, default false + */ @property (nonatomic) BOOL debug; + +/** + * Debug file location, default nil + */ @property (nonatomic) NSString *loggingFile; -@property (nonatomic) NSFileHandle *loggingFileHanlder; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; /** * Get configuration singleton instance @@ -41,14 +63,39 @@ + (instancetype) sharedConfig; /** - * Sets field in `apiKey` + * Sets field in `apiKey`. + * + * To remove a apiKey for a identifier, just set the apiKey to nil. + * + * @param apiKey The apiKey value. + * @param identifier The apiKey name. + * */ -- (void) setValue:(NSString *)value forApiKeyField:(NSString*)field; +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; + +/** + * Remove api key + * + * @param identifier The apiKey name. + */ +- (void) removeApiKey:(NSString *)identifier; /** * Sets field in `apiKeyPrefix` + * + * To remove a apiKeyPrefix for a identifier, just set the apiKeyPrefix to nil. + * + * @param apiKeyPrefix The apiKeyPrefix value. + * @param identifier The apiKeyPrefix name. */ -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field; +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; + +/** + * Remove api key prefix + * + * @param identifier The apiKeyPrefix name. + */ +- (void) removeApiKeyPrefix:(NSString *)identifier; /** * Get API key (with prefix if set) diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m index 81e308a53fc..0e0e70e27ea 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m @@ -60,12 +60,20 @@ #pragma mark - Setter Methods -- (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { - [self.mutableApiKey setValue:value forKey:field]; +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { + [self.mutableApiKey setValue:apiKey forKey:identifier]; } -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field { - [self.mutableApiKeyPrefix setValue:value forKey:field]; +- (void) removeApiKey:(NSString *)identifier { + [self.mutableApiKey removeObjectForKey:identifier]; +} + +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { + [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; +} + +- (void) removeApiKeyPrefix:(NSString *)identifier { + [self.mutableApiKeyPrefix removeObjectForKey:identifier]; } - (void) setLoggingFile:(NSString *)loggingFile { @@ -75,10 +83,10 @@ } _loggingFile = loggingFile; - self.loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (self.loggingFileHanlder == nil) { + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHanlder == nil) { [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - self.loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; } } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m index 950edd796a9..e2ee7a1f321 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m @@ -13,7 +13,7 @@ /** * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, or return `NO`. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ + (BOOL)propertyIsOptional:(NSString *)propertyName @@ -29,7 +29,7 @@ } /** - * Return a string that represents the properties json of the model. + * Returns a string that represents the properties json of the model. * This method will be called when logging model object using `NSLog`. */ - (NSString *)description { diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.m b/samples/client/petstore/objc/SwaggerClient/SWGPet.m index 48a0940338c..1d1965cfa04 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.m @@ -13,7 +13,7 @@ /** * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, or return `NO`. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ + (BOOL)propertyIsOptional:(NSString *)propertyName @@ -29,7 +29,7 @@ } /** - * Return a string that represents the properties json of the model. + * Returns a string that represents the properties json of the model. * This method will be called when logging model object using `NSLog`. */ - (NSString *)description { diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.m b/samples/client/petstore/objc/SwaggerClient/SWGTag.m index 1ee6964e60c..36215d9482c 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGTag.m @@ -13,7 +13,7 @@ /** * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, or return `NO`. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ + (BOOL)propertyIsOptional:(NSString *)propertyName @@ -29,7 +29,7 @@ } /** - * Return a string that represents the properties json of the model. + * Returns a string that represents the properties json of the model. * This method will be called when logging model object using `NSLog`. */ - (NSString *)description { diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.m b/samples/client/petstore/objc/SwaggerClient/SWGUser.m index 934b91fba73..ecf7ee5ad7d 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUser.m @@ -13,7 +13,7 @@ /** * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, or return `NO`. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ + (BOOL)propertyIsOptional:(NSString *)propertyName @@ -29,7 +29,7 @@ } /** - * Return a string that represents the properties json of the model. + * Returns a string that represents the properties json of the model. * This method will be called when logging model object using `NSLog`. */ - (NSString *)description { diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m index d538fe49fdc..5fe98be055f 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m @@ -8,6 +8,7 @@ #import "SWGViewController.h" #import +#import @interface SWGViewController () @@ -18,8 +19,11 @@ - (void)viewDidLoad { [super viewDidLoad]; - SWGPet *pet = [self createPet]; - NSLog(@"%@", pet); + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + [config setApiKey:@"hello" forApiKeyIdentifier:@"world"]; + [config setApiKey:@"geekerzp" forApiKeyIdentifier:@"zp"]; + [config removeApiKey:@"zp"]; + NSLog(@"%@", config.apiKey); } - (void)didReceiveMemoryWarning diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m index 6365632ea2d..d19180dc008 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m @@ -61,8 +61,8 @@ - (void)testConfiguration { SWGConfiguration *config = [SWGConfiguration sharedConfig]; - [config setValue:@"123456" forApiKeyField:@"api_key"]; - [config setValue:@"PREFIX" forApiKeyPrefixField:@"api_key"]; + [config setApiKey:@"123456" forApiKeyIdentifier:@"api_key"]; + [config setApiKeyPrefix:@"PREFIX" forApiKeyPrefixIdentifier:@"api_key"]; config.username = @"test_username"; config.password = @"test_password"; From 5a235c642accc342682a81d46a161a7ce7f8cf22 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 23 Jul 2015 18:03:19 +0800 Subject: [PATCH 04/33] Update comments of objc client --- .../resources/objc/ApiClient-header.mustache | 53 ++++++++-------- .../objc/Configuration-header.mustache | 34 +++++------ .../main/resources/objc/api-header.mustache | 6 ++ .../main/resources/objc/model-body.mustache | 2 +- .../main/resources/objc/model-header.mustache | 9 ++- .../objc/SwaggerClient/SWGApiClient.h | 61 ++++++++++--------- .../petstore/objc/SwaggerClient/SWGCategory.h | 9 ++- .../petstore/objc/SwaggerClient/SWGCategory.m | 2 +- .../objc/SwaggerClient/SWGConfiguration.h | 34 +++++------ .../petstore/objc/SwaggerClient/SWGOrder.h | 9 ++- .../petstore/objc/SwaggerClient/SWGOrder.m | 2 +- .../petstore/objc/SwaggerClient/SWGPet.h | 9 ++- .../petstore/objc/SwaggerClient/SWGPet.m | 2 +- .../petstore/objc/SwaggerClient/SWGPetApi.h | 6 ++ .../petstore/objc/SwaggerClient/SWGStoreApi.h | 6 ++ .../petstore/objc/SwaggerClient/SWGTag.h | 9 ++- .../petstore/objc/SwaggerClient/SWGTag.m | 2 +- .../petstore/objc/SwaggerClient/SWGUser.h | 9 ++- .../petstore/objc/SwaggerClient/SWGUser.m | 2 +- .../petstore/objc/SwaggerClient/SWGUserApi.h | 6 ++ 20 files changed, 174 insertions(+), 98 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index 0edab7414f1..a5871400352 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -5,9 +5,14 @@ #import "{{classPrefix}}JSONRequestSerializer.h" #import "{{classPrefix}}QueryParamCollection.h" #import "{{classPrefix}}Configuration.h" - -{{#models}}{{#model}}#import "{{classname}}.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +{{#models}}{{#model}}#import "{{classname}}.h" {{/model}}{{/models}} /** @@ -25,7 +30,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; @property(nonatomic, readonly) NSOperationQueue* queue; /** - * Get the Api Client instance from pool + * Gets the Api Client instance from pool * * @param baseUrl The base url of api client. * @@ -34,68 +39,68 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +({{classPrefix}}ApiClient *)sharedClientFromPool:(NSString *)baseUrl; /** - * Get the operations queue + * Gets the operations queue * * @return The `shardQueue` static variable. */ +(NSOperationQueue*) sharedQueue; /** - * Clear Cache + * Clears Cache */ +(void)clearCache; /** - * Turn on cache + * Turns on cache * * @param enabled If the cached is enable, must be `YES` or `NO` */ +(void)setCacheEnabled:(BOOL) enabled; /** - * Get the request queue size + * Gets the request queue size * * @return The size of `queuedRequests` static variable. */ +(unsigned long)requestQueueSize; /** - * Set the client unreachable + * Sets the client unreachable * - * @param state off line state, must be `YES` or `NO` + * @param state off line state, must be `YES` or `NO` */ +(void) setOfflineState:(BOOL) state; /** - * Get the client reachability + * Gets the client reachability * * @return The client reachability. */ +(AFNetworkReachabilityStatus) getReachabilityStatus; /** - * Get the next request id + * Gets the next request id * * @return The next executed request id. */ +(NSNumber*) nextRequestId; /** - * Generate request id and add it to the queue + * Generates request id and add it to the queue * * @return The next executed request id. */ +(NSNumber*) queueRequest; /** - * Remove request id from the queue + * Removes request id from the queue * * @param requestId The request which will be removed. */ +(void) cancelRequest:(NSNumber*)requestId; /** - * URL encode NSString + * Gets URL encoded NSString * * @param unescaped The string which will be escaped. * @@ -104,21 +109,21 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +(NSString*) escape:(id)unescaped; /** - * Customize the behavior when the reachability changed + * Customizes the behavior when the reachability changed * * @param changeBlock The block will be executed when the reachability changed. */ +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; /** - * Set the client reachability strategy + * Sets the client reachability strategy * * @param host The host of {{classPrefix}}ApiClient. */ +(void) configureCacheReachibilityForHost:(NSString*)host; /** - * Detect Accept header from accepts NSArray + * Detects Accept header from accepts NSArray * * @param accepts NSArray of header * @@ -127,7 +132,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +(NSString *) selectHeaderAccept:(NSArray *)accepts; /** - * Detect Content-Type header from contentTypes NSArray + * Detects Content-Type header from contentTypes NSArray * * @param contentTypes NSArray of header * @@ -136,7 +141,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +(NSString *) selectHeaderContentType:(NSArray *)contentTypes; /** - * Set header for request + * Sets header for request * * @param value The header value * @param forKey The header key @@ -145,7 +150,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; forKey:(NSString*) forKey; /** - * Update header parameters and query parameters for authentication + * Updates header parameters and query parameters for authentication * * @param headers The header parameter will be udpated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. @@ -156,7 +161,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; WithAuthSettings:(NSArray *)authSettings; /** - * Deserialize the given data to Objective-C object. + * Deserializes the given data to Objective-C object. * * @param data The data will be deserialized. * @param class The type of objective-c object. @@ -164,7 +169,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; - (id) deserialize:(id) data class:(NSString *) class; /** - * Logging request and response + * Logs request and response * * @param operation AFHTTPRequestOperation for the HTTP request. * @param request The HTTP request. @@ -175,7 +180,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; error:(NSError *)error; /** - * Perform request + * Performs request * * @param path Request url. * @param method Request method. @@ -185,7 +190,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * @param authSettings Request authentication names. * @param requestContentType Request content-type. * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. + * @param completionBlock The block will be executed when the request completed. * * @return The request id. */ diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache index 2ec6e18e9d5..56e9fcaecd5 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache @@ -2,7 +2,7 @@ /** The `{{classPrefix}}Configuration` class manages the configurations for the sdk. * - * NOTE: This class is auto generated by the swagger code generator program. + * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -58,57 +58,57 @@ @property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; /** - * Get configuration singleton instance + * Gets configuration singleton instance */ + (instancetype) sharedConfig; /** - * Sets field in `apiKey`. + * Sets API key * - * To remove a apiKey for a identifier, just set the apiKey to nil. + * To remove a apiKey for an identifier, just set the apiKey to nil. * - * @param apiKey The apiKey value. - * @param identifier The apiKey name. + * @param apiKey API key or token. + * @param identifier API key identifier (authentication schema). * */ - (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; /** - * Remove api key + * Removes api key * - * @param identifier The apiKey name. + * @param identifier API key identifier. */ - (void) removeApiKey:(NSString *)identifier; /** - * Sets field in `apiKeyPrefix` + * Sets the prefix for API key * - * To remove a apiKeyPrefix for a identifier, just set the apiKeyPrefix to nil. + * To remove a apiKeyPrefix for an identifier, just set the apiKeyPrefix to nil. * - * @param apiKeyPrefix The apiKeyPrefix value. - * @param identifier The apiKeyPrefix name. + * @param apiKeyPrefix API key prefix. + * @param identifier API key identifier. */ - (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; /** - * Remove api key prefix + * Removes api key prefix * - * @param identifier The apiKeyPrefix name. + * @param identifier API key identifier. */ - (void) removeApiKeyPrefix:(NSString *)identifier; /** - * Get API key (with prefix if set) + * Gets API key (with prefix if set) */ - (NSString *) getApiKeyWithPrefix:(NSString *) key; /** - * Get Basic Auth token + * Gets Basic Auth token */ - (NSString *) getBasicAuthToken; /** - * Get Authentication Setings + * Gets Authentication Setings */ - (NSDictionary *) authSettings; diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 263c213dd6f..6b85f753e45 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -5,6 +5,12 @@ #import "{{classPrefix}}ApiClient.h" {{newline}} +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + {{#operations}} @interface {{classname}}: NSObject diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index 209cd7bf5a5..33c0f8cf42b 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -31,7 +31,7 @@ } /** - * Returns a string that represents the properties json of the model. + * Gets the string presentation of the object. * This method will be called when logging model object using `NSLog`. */ - (NSString *)description { diff --git a/modules/swagger-codegen/src/main/resources/objc/model-header.mustache b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache index 4afaec31a24..c3f3c865424 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache @@ -1,5 +1,12 @@ #import #import "{{classPrefix}}Object.h" + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + {{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} @@ -8,7 +15,7 @@ @protocol {{classname}} @end - + @interface {{classname}} : {{classPrefix}}Object {{#vars}} diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index 56c6adf30f2..ada8035e579 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -5,13 +5,18 @@ #import "SWGJSONRequestSerializer.h" #import "SWGQueryParamCollection.h" #import "SWGConfiguration.h" - -#import "SWGUser.h" -#import "SWGCategory.h" -#import "SWGPet.h" -#import "SWGTag.h" -#import "SWGOrder.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import "SWGUser.h" +#import "SWGCategory.h" +#import "SWGPet.h" +#import "SWGTag.h" +#import "SWGOrder.h" /** @@ -29,7 +34,7 @@ extern NSString *const SWGResponseObjectErrorKey; @property(nonatomic, readonly) NSOperationQueue* queue; /** - * Get the Api Client instance from pool + * Gets the Api Client instance from pool * * @param baseUrl The base url of api client. * @@ -38,68 +43,68 @@ extern NSString *const SWGResponseObjectErrorKey; +(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl; /** - * Get the operations queue + * Gets the operations queue * * @return The `shardQueue` static variable. */ +(NSOperationQueue*) sharedQueue; /** - * Clear Cache + * Clears Cache */ +(void)clearCache; /** - * Turn on cache + * Turns on cache * * @param enabled If the cached is enable, must be `YES` or `NO` */ +(void)setCacheEnabled:(BOOL) enabled; /** - * Get the request queue size + * Gets the request queue size * * @return The size of `queuedRequests` static variable. */ +(unsigned long)requestQueueSize; /** - * Set the client unreachable + * Sets the client unreachable * - * @param state off line state, must be `YES` or `NO` + * @param state off line state, must be `YES` or `NO` */ +(void) setOfflineState:(BOOL) state; /** - * Get the client reachability + * Gets the client reachability * * @return The client reachability. */ +(AFNetworkReachabilityStatus) getReachabilityStatus; /** - * Get the next request id + * Gets the next request id * * @return The next executed request id. */ +(NSNumber*) nextRequestId; /** - * Generate request id and add it to the queue + * Generates request id and add it to the queue * * @return The next executed request id. */ +(NSNumber*) queueRequest; /** - * Remove request id from the queue + * Removes request id from the queue * * @param requestId The request which will be removed. */ +(void) cancelRequest:(NSNumber*)requestId; /** - * URL encode NSString + * Gets URL encoded NSString * * @param unescaped The string which will be escaped. * @@ -108,21 +113,21 @@ extern NSString *const SWGResponseObjectErrorKey; +(NSString*) escape:(id)unescaped; /** - * Customize the behavior when the reachability changed + * Customizes the behavior when the reachability changed * * @param changeBlock The block will be executed when the reachability changed. */ +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; /** - * Set the client reachability strategy + * Sets the client reachability strategy * * @param host The host of SWGApiClient. */ +(void) configureCacheReachibilityForHost:(NSString*)host; /** - * Detect Accept header from accepts NSArray + * Detects Accept header from accepts NSArray * * @param accepts NSArray of header * @@ -131,7 +136,7 @@ extern NSString *const SWGResponseObjectErrorKey; +(NSString *) selectHeaderAccept:(NSArray *)accepts; /** - * Detect Content-Type header from contentTypes NSArray + * Detects Content-Type header from contentTypes NSArray * * @param contentTypes NSArray of header * @@ -140,7 +145,7 @@ extern NSString *const SWGResponseObjectErrorKey; +(NSString *) selectHeaderContentType:(NSArray *)contentTypes; /** - * Set header for request + * Sets header for request * * @param value The header value * @param forKey The header key @@ -149,7 +154,7 @@ extern NSString *const SWGResponseObjectErrorKey; forKey:(NSString*) forKey; /** - * Update header parameters and query parameters for authentication + * Updates header parameters and query parameters for authentication * * @param headers The header parameter will be udpated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. @@ -160,7 +165,7 @@ extern NSString *const SWGResponseObjectErrorKey; WithAuthSettings:(NSArray *)authSettings; /** - * Deserialize the given data to Objective-C object. + * Deserializes the given data to Objective-C object. * * @param data The data will be deserialized. * @param class The type of objective-c object. @@ -168,7 +173,7 @@ extern NSString *const SWGResponseObjectErrorKey; - (id) deserialize:(id) data class:(NSString *) class; /** - * Logging request and response + * Logs request and response * * @param operation AFHTTPRequestOperation for the HTTP request. * @param request The HTTP request. @@ -179,7 +184,7 @@ extern NSString *const SWGResponseObjectErrorKey; error:(NSError *)error; /** - * Perform request + * Performs request * * @param path Request url. * @param method Request method. @@ -189,7 +194,7 @@ extern NSString *const SWGResponseObjectErrorKey; * @param authSettings Request authentication names. * @param requestContentType Request content-type. * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. + * @param completionBlock The block will be executed when the request completed. * * @return The request id. */ diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.h b/samples/client/petstore/objc/SwaggerClient/SWGCategory.h index a2fed79b4a3..983fd610123 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGCategory.h @@ -1,10 +1,17 @@ #import #import "SWGObject.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + @protocol SWGCategory @end - + @interface SWGCategory : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m index d2ac30e403b..fb3ccecf176 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m @@ -29,7 +29,7 @@ } /** - * Returns a string that represents the properties json of the model. + * Gets the string presentation of the object. * This method will be called when logging model object using `NSLog`. */ - (NSString *)description { diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h index d1176257779..4b7f318b5ec 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h @@ -2,7 +2,7 @@ /** The `SWGConfiguration` class manages the configurations for the sdk. * - * NOTE: This class is auto generated by the swagger code generator program. + * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -58,57 +58,57 @@ @property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; /** - * Get configuration singleton instance + * Gets configuration singleton instance */ + (instancetype) sharedConfig; /** - * Sets field in `apiKey`. + * Sets API key * - * To remove a apiKey for a identifier, just set the apiKey to nil. + * To remove a apiKey for an identifier, just set the apiKey to nil. * - * @param apiKey The apiKey value. - * @param identifier The apiKey name. + * @param apiKey API key or token. + * @param identifier API key identifier (authentication schema). * */ - (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; /** - * Remove api key + * Removes api key * - * @param identifier The apiKey name. + * @param identifier API key identifier. */ - (void) removeApiKey:(NSString *)identifier; /** - * Sets field in `apiKeyPrefix` + * Sets the prefix for API key * - * To remove a apiKeyPrefix for a identifier, just set the apiKeyPrefix to nil. + * To remove a apiKeyPrefix for an identifier, just set the apiKeyPrefix to nil. * - * @param apiKeyPrefix The apiKeyPrefix value. - * @param identifier The apiKeyPrefix name. + * @param apiKeyPrefix API key prefix. + * @param identifier API key identifier. */ - (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; /** - * Remove api key prefix + * Removes api key prefix * - * @param identifier The apiKeyPrefix name. + * @param identifier API key identifier. */ - (void) removeApiKeyPrefix:(NSString *)identifier; /** - * Get API key (with prefix if set) + * Gets API key (with prefix if set) */ - (NSString *) getApiKeyWithPrefix:(NSString *) key; /** - * Get Basic Auth token + * Gets Basic Auth token */ - (NSString *) getBasicAuthToken; /** - * Get Authentication Setings + * Gets Authentication Setings */ - (NSDictionary *) authSettings; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h b/samples/client/petstore/objc/SwaggerClient/SWGOrder.h index 2e71906cd53..48a7cf0d6c1 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.h @@ -1,10 +1,17 @@ #import #import "SWGObject.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + @protocol SWGOrder @end - + @interface SWGOrder : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m index e2ee7a1f321..83fe5741cd7 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m @@ -29,7 +29,7 @@ } /** - * Returns a string that represents the properties json of the model. + * Gets the string presentation of the object. * This method will be called when logging model object using `NSLog`. */ - (NSString *)description { diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/SWGPet.h index edd54e9f31a..d78baade81a 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.h @@ -1,12 +1,19 @@ #import #import "SWGObject.h" + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + #import "SWGTag.h" #import "SWGCategory.h" @protocol SWGPet @end - + @interface SWGPet : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.m b/samples/client/petstore/objc/SwaggerClient/SWGPet.m index 1d1965cfa04..3fd315ab011 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.m @@ -29,7 +29,7 @@ } /** - * Returns a string that represents the properties json of the model. + * Gets the string presentation of the object. * This method will be called when logging model object using `NSLog`. */ - (NSString *)description { diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h index 39f23edb028..929b16eab1f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h @@ -4,6 +4,12 @@ #import "SWGApiClient.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + @interface SWGPetApi: NSObject @property(nonatomic, assign)SWGApiClient *apiClient; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h index 7488c1baa70..7b4f99dea7b 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h @@ -4,6 +4,12 @@ #import "SWGApiClient.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + @interface SWGStoreApi: NSObject @property(nonatomic, assign)SWGApiClient *apiClient; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.h b/samples/client/petstore/objc/SwaggerClient/SWGTag.h index d9cc84be270..97e95807550 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGTag.h @@ -1,10 +1,17 @@ #import #import "SWGObject.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + @protocol SWGTag @end - + @interface SWGTag : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.m b/samples/client/petstore/objc/SwaggerClient/SWGTag.m index 36215d9482c..3bcb9973dfd 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGTag.m @@ -29,7 +29,7 @@ } /** - * Returns a string that represents the properties json of the model. + * Gets the string presentation of the object. * This method will be called when logging model object using `NSLog`. */ - (NSString *)description { diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.h b/samples/client/petstore/objc/SwaggerClient/SWGUser.h index f505ca2c041..6ba19e632b8 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUser.h @@ -1,10 +1,17 @@ #import #import "SWGObject.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + @protocol SWGUser @end - + @interface SWGUser : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.m b/samples/client/petstore/objc/SwaggerClient/SWGUser.m index ecf7ee5ad7d..d040a6bce6d 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUser.m @@ -29,7 +29,7 @@ } /** - * Returns a string that represents the properties json of the model. + * Gets the string presentation of the object. * This method will be called when logging model object using `NSLog`. */ - (NSString *)description { diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h index 6fda87cca70..9a3dfd9d23d 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h @@ -4,6 +4,12 @@ #import "SWGApiClient.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + @interface SWGUserApi: NSObject @property(nonatomic, assign)SWGApiClient *apiClient; From 037f59d0dffde531090c32b3c4676fca07c1ec11 Mon Sep 17 00:00:00 2001 From: Martin Hardorf Date: Thu, 23 Jul 2015 13:10:59 +0200 Subject: [PATCH 05/33] Add support for specifying configuration file in maven plugin --- .../swagger/codegen/plugin/CodeGenMojo.java | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index 26b6fef1135..812be6981d4 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -16,12 +16,14 @@ package io.swagger.codegen.plugin; * limitations under the License. */ +import io.swagger.codegen.CliOption; import io.swagger.codegen.ClientOptInput; import io.swagger.codegen.ClientOpts; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.DefaultGenerator; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; + import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -29,6 +31,9 @@ import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; +import config.Config; +import config.ConfigParser; + import java.io.File; import java.util.ServiceLoader; @@ -66,6 +71,12 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(name = "language", required = true) private String language; + /** + * Path to json configuration file. + */ + @Parameter(name = "configurationFile", required = false) + private String configurationFile; + /** * Add the output directory to the project as a source root, so that the @@ -90,7 +101,20 @@ public class CodeGenMojo extends AbstractMojo { if (null != templateDirectory) { config.additionalProperties().put(TEMPLATE_DIR_PARAM, templateDirectory.getAbsolutePath()); } - + + if (null != configurationFile) { + Config genConfig = ConfigParser.read(configurationFile); + if (null != genConfig) { + for (CliOption langCliOption : config.cliOptions()) { + if (genConfig.hasOption(langCliOption.getOpt())) { + config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt())); + } + } + } else { + throw new RuntimeException("Unable to read configuration file"); + } + } + ClientOptInput input = new ClientOptInput().opts(new ClientOpts()).swagger(swagger); input.setConfig(config); new DefaultGenerator().opts(input).generate(); From 992b0c7e5edf4c2ca44ec2ac7a6438ffac70969a Mon Sep 17 00:00:00 2001 From: Martin Hardorf Date: Thu, 23 Jul 2015 13:11:53 +0200 Subject: [PATCH 06/33] Sort model objects by inheritance --- .../io/swagger/codegen/DefaultGenerator.java | 55 ++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 6289757d80f..d48238c2489 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -2,6 +2,8 @@ package io.swagger.codegen; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; + +import io.swagger.models.ComposedModel; import io.swagger.models.Contact; import io.swagger.models.Info; import io.swagger.models.License; @@ -12,6 +14,7 @@ import io.swagger.models.Swagger; import io.swagger.models.auth.OAuth2Definition; import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.util.Json; + import org.apache.commons.io.IOUtils; import java.io.File; @@ -21,6 +24,8 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -119,7 +124,9 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { // models Map definitions = swagger.getDefinitions(); if (definitions != null) { - for (String name : definitions.keySet()) { + List sortedModelKeys = sortModelsByInheritance(definitions); + + for (String name : sortedModelKeys) { Model model = definitions.get(name); Map modelMap = new HashMap(); modelMap.put(name, model); @@ -326,6 +333,52 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.put(flagFieldName, true); } } + + private List sortModelsByInheritance(final Map definitions) { + List sortedModelKeys = new ArrayList(definitions.keySet()); + Comparator cmp = new Comparator() { + @Override + public int compare(String o1, String o2) { + Model model1 = definitions.get(o1); + Model model2 = definitions.get(o2); + + int model1InheritanceDepth = getInheritanceDepth(model1); + int model2InheritanceDepth = getInheritanceDepth(model2); + + if (model1InheritanceDepth == model2InheritanceDepth) { + return 0; + } else if (model1InheritanceDepth > model2InheritanceDepth) { + return 1; + } else { + return -1; + } + } + + private int getInheritanceDepth(Model model) { + int inheritanceDepth = 0; + Model parent = getParent(model); + + while (parent != null) { + inheritanceDepth++; + parent = getParent(parent); + } + + return inheritanceDepth; + } + + private Model getParent(Model model) { + if (model instanceof ComposedModel) { + return definitions.get(((ComposedModel) model).getParent().getReference()); + } + + return null; + } + }; + + Collections.sort(sortedModelKeys, cmp); + + return sortedModelKeys; + } public Map> processPaths(Map paths) { Map> ops = new HashMap>(); From 071fc2ded6a9d61e05f3ab51827e84760a119b52 Mon Sep 17 00:00:00 2001 From: Atsushi Nagase Date: Wed, 22 Jul 2015 19:30:39 +0900 Subject: [PATCH 07/33] [Swift] Add podspec template --- .../io/swagger/codegen/languages/SwiftCodegen.java | 3 ++- .../src/main/resources/swift/Podspec.mustache | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 modules/swagger-codegen/src/main/resources/swift/Podspec.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 5d4f5f341a7..e610da320b3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -143,6 +143,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("usePromiseKit", true); } + supportingFiles.add(new SupportingFile("Podspec.mustache", "", projectName + ".podspec")); supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, @@ -283,4 +284,4 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { return builder.toString(); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache new file mode 100644 index 00000000000..de5a9d1973f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -0,0 +1,10 @@ +Pod::Spec.new do |s| + s.name = '{{projectName}}'{{#projectDescription}} + s.summary = '{{projectDescription}}'{{/projectDescription}} + s.ios.deployment_target = '8.0' + s.osx.deployment_target = '10.9' + s.source = { git: 'git@github.com:swagger-api/swagger-mustache.git', tag: 'v1.0.0' } + s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift' + s.dependency 'PromiseKit', '~> 2.1' + s.dependency 'Alamofire', '~> 1.2' +end From 80b536320251f1f07debcc1419b596ac4aad6d25 Mon Sep 17 00:00:00 2001 From: Atsushi Nagase Date: Fri, 24 Jul 2015 16:27:28 +0900 Subject: [PATCH 08/33] [Swift] add cliOptions for podspec ``` podSource Source information used for Podspec podVersion Version used for Podspec podAuthors Authors used for Podspec podSocialMediaURL Social Media URL used for Podspec podDocsetURL Docset URL used for Podspec podLicense License used for Podspec podHomepage Homepage used for Podspec podSummary Summary used for Podspec podDescription Description used for Podspec podScreenshots Screenshots used for Podspec podDocumentationURL Documentation URL used for Podspec ``` --- .../io/swagger/codegen/languages/SwiftCodegen.java | 11 +++++++++++ .../src/main/resources/swift/Podspec.mustache | 11 ++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index e610da320b3..7915e4e3e2c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -109,6 +109,17 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available.")); cliOptions.add(new CliOption("unwrapRequired", "Treat 'required' properties in response as non-optional " + "(which would crash the app if api returns null as opposed to required option specified in json schema")); + cliOptions.add(new CliOption("podSource", "Source information used for Podspec")); + cliOptions.add(new CliOption("podVersion", "Version used for Podspec")); + cliOptions.add(new CliOption("podAuthors", "Authors used for Podspec")); + cliOptions.add(new CliOption("podSocialMediaURL", "Social Media URL used for Podspec")); + cliOptions.add(new CliOption("podDocsetURL", "Docset URL used for Podspec")); + cliOptions.add(new CliOption("podLicense", "License used for Podspec")); + cliOptions.add(new CliOption("podHomepage", "Homepage used for Podspec")); + cliOptions.add(new CliOption("podSummary", "Summary used for Podspec")); + cliOptions.add(new CliOption("podDescription", "Description used for Podspec")); + cliOptions.add(new CliOption("podScreenshots", "Screenshots used for Podspec")); + cliOptions.add(new CliOption("podDocumentationURL", "Documentation URL used for Podspec")); } @Override diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index de5a9d1973f..a7be288ebcd 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -3,7 +3,16 @@ Pod::Spec.new do |s| s.summary = '{{projectDescription}}'{{/projectDescription}} s.ios.deployment_target = '8.0' s.osx.deployment_target = '10.9' - s.source = { git: 'git@github.com:swagger-api/swagger-mustache.git', tag: 'v1.0.0' } + s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}}{{#podAuthors}} + s.authors = {{& podAuthors}}{{/podAuthors}}{{#podSocialMediaURL}} + s.social_media_url = '{{podSocialMediaURL}}'{{/podSocialMediaURL}}{{#podDocsetURL}} + s.docset_url = '{{podDocsetURL}}'{{/podDocsetURL}} + s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Apache License, Version 2.0'{{/podLicense}}{{#podHomepage}} + s.homepage = '{{podHomepage}}'{{/podHomepage}}{{#podSummary}} + s.summary = '{{podSummary}}'{{/podSummary}}{{#podDescription}} + s.description = '{{podDescription}}'{{/podDescription}}{{#podScreenshots}} + s.screenshots = {{& podScreenshots}}{{/podScreenshots}}{{#podDocumentationURL}} + s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift' s.dependency 'PromiseKit', '~> 2.1' s.dependency 'Alamofire', '~> 1.2' From 646da19c7d97248f4d288913c557a2aa044d4905 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Fri, 24 Jul 2015 09:48:49 +0200 Subject: [PATCH 09/33] Combine TypeScript node output in one file and add missing require statements --- .../TypeScriptAngularClientCodegen.java | 3 +- .../TypeScriptNodeClientCodegen.java | 6 +- .../resources/TypeScript-node/api.mustache | 145 +-- .../resources/TypeScript-node/model.mustache | 33 - .../client/petstore/typescript-node/api.ts | 828 ++++++++++++++++++ .../petstore/typescript-node/api/PetApi.ts | 378 -------- .../petstore/typescript-node/api/StoreApi.ts | 192 ---- .../petstore/typescript-node/api/UserApi.ts | 372 -------- .../typescript-node/model/Category.ts | 7 - .../petstore/typescript-node/model/Order.ts | 26 - .../petstore/typescript-node/model/Pet.ts | 26 - .../petstore/typescript-node/model/Tag.ts | 7 - .../petstore/typescript-node/model/User.ts | 22 - 13 files changed, 928 insertions(+), 1117 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache create mode 100644 samples/client/petstore/typescript-node/api.ts delete mode 100644 samples/client/petstore/typescript-node/api/PetApi.ts delete mode 100644 samples/client/petstore/typescript-node/api/StoreApi.ts delete mode 100644 samples/client/petstore/typescript-node/api/UserApi.ts delete mode 100644 samples/client/petstore/typescript-node/model/Category.ts delete mode 100644 samples/client/petstore/typescript-node/model/Order.ts delete mode 100644 samples/client/petstore/typescript-node/model/Pet.ts delete mode 100644 samples/client/petstore/typescript-node/model/Tag.ts delete mode 100644 samples/client/petstore/typescript-node/model/User.ts diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index 11cae0de0ef..9b9422bbcd9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -19,7 +19,8 @@ public class TypeScriptAngularClientCodegen extends TypeScriptNodeClientCodegen templateDir = "TypeScript-Angular"; apiPackage = "api"; modelPackage = "model"; - + + supportingFiles.clear(); supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage + File.separator, "api.d.ts")); } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index 0ea33f21709..9e2e1056dcf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -31,11 +31,9 @@ public class TypeScriptNodeClientCodegen extends DefaultCodegen implements Codeg public TypeScriptNodeClientCodegen() { super(); outputFolder = "generated-code/typescript-node"; - modelTemplateFiles.put("model.mustache", ".ts"); - apiTemplateFiles.put("api.mustache", ".ts"); templateDir = "TypeScript-node"; - apiPackage = "api"; - modelPackage = "model"; + + supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); reservedWords = new HashSet(Arrays.asList("abstract", "continue", "for", "new", "switch", "assert", "default", "if", diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index debeed69515..67b7d4fc3fa 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -1,10 +1,52 @@ +import request = require('request'); +import promise = require('bluebird'); +import http = require('http'); + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + /* tslint:disable:no-unused-variable */ -{{#operations}} +{{#models}} +{{#model}} +{{#description}} +/** +* {{{description}}} +*/ +{{/description}} +export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ +{{#vars}} {{#description}} /** - * {{&description}} + * {{{description}}} */ +{{/description}} + {{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; +{{/vars}} +} + +{{#hasEnums}} +export module {{classname}} { +{{#vars}} +{{#isEnum}} + export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} + {{.}} = '{{.}}',{{/values}}{{/allowableValues}} + } +{{/isEnum}} +{{/vars}} +} +{{/hasEnums}} +{{/model}} +{{/models}} + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#description}} +/** +* {{&description}} +*/ {{/description}} export class {{classname}} { private basePath = '{{contextPath}}'; @@ -14,60 +56,65 @@ export class {{classname}} { this.basePath = basePath; } } +{{#operation}} - {{#operation}} - public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { - var path = this.url + this.basePath + '{{path}}'; + public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { + var path = this.url + this.basePath + '{{path}}'; - {{#pathParams}} - path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); - {{/pathParams}} +{{#pathParams}} + path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); - var queryParameters: any = {}; - var headerParams: any = {}; +{{/pathParams}} + var queryParameters: any = {}; + var headerParams: any = {}; - {{#allParams}}{{#required}} - // verify required parameter '{{paramName}}' is set - if (!{{paramName}}) { - throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); - } - {{/required}}{{/allParams}} - - {{#queryParams}}if ({{paramName}} !== undefined) { - queryParameters['{{paramName}}'] = {{paramName}}; - } - {{/queryParams}} - - {{#headerParams}}headerParams['{{paramName}}'] = {{paramName}}; - {{/headerParams}} - - var deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); - - request({ - method: '{{httpMethod}}', - qs: queryParameters, - uri: path, - json: true, - {{#bodyParam}}body: {{paramName}}, - {{/bodyParam}} - auth: { - username: this.username, password: this.password +{{#allParams}} +{{#required}} + // verify required parameter '{{paramName}}' is set + if (!{{paramName}}) { + throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); + +{{/required}} +{{/allParams}} +{{#queryParams}} + if ({{paramName}} !== undefined) { + queryParameters['{{paramName}}'] = {{paramName}}; } - } - }); - return deferred.promise; - } +{{/queryParams}} +{{#headerParams}} + headerParams['{{paramName}}'] = {{paramName}}; - {{/operation}} +{{/headerParams}} + var deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); + + request({ + method: '{{httpMethod}}', + qs: queryParameters, + uri: path, + json: true, + {{#bodyParam}}body: {{paramName}}, + {{/bodyParam}} + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +{{/operation}} } {{/operations}} +{{/apis}} +{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache deleted file mode 100644 index 55c8997e1bc..00000000000 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache +++ /dev/null @@ -1,33 +0,0 @@ -{{#models}} -{{#model}} -{{#description}} -/** - * {{{description}}} - */ -{{/description}} -export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ -{{#vars}} - -{{#description}} - /** - * {{{description}}} - */ -{{/description}} - {{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; -{{/vars}} -} - -{{#hasEnums}} -export module {{classname}} { -{{#vars}} -{{#isEnum}} - - export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} - {{.}} = '{{.}}',{{/values}}{{/allowableValues}} - } -{{/isEnum}} -{{/vars}} -} -{{/hasEnums}} -{{/model}} -{{/models}} diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts new file mode 100644 index 00000000000..b165be2d313 --- /dev/null +++ b/samples/client/petstore/typescript-node/api.ts @@ -0,0 +1,828 @@ +import request = require('request'); +import promise = require('bluebird'); +import http = require('http'); + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +/* tslint:disable:no-unused-variable */ + +export class User { + id: number; + username: string; + firstName: string; + lastName: string; + email: string; + password: string; + phone: string; + /** + * User Status + */ + userStatus: number; +} + +export class Category { + id: number; + name: string; +} + +export class Pet { + id: number; + category: Category; + name: string; + photoUrls: Array; + tags: Array; + /** + * pet status in the store + */ + status: Pet.StatusEnum; +} + +export module Pet { + export enum StatusEnum { + available = 'available', + pending = 'pending', + sold = 'sold', + } +} +export class Tag { + id: number; + name: string; +} + +export class Order { + id: number; + petId: number; + quantity: number; + shipDate: Date; + /** + * Order Status + */ + status: Order.StatusEnum; + complete: boolean; +} + +export module Order { + export enum StatusEnum { + placed = 'placed', + approved = 'approved', + delivered = 'delivered', + } +} + +export class UserApi { + private basePath = '/v2'; + + constructor(private url: string, private username: string, private password: string, basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + public createUser (body?: User) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user'; + + var queryParameters: any = {}; + var headerParams: any = {}; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/createWithArray'; + + var queryParameters: any = {}; + var headerParams: any = {}; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/createWithList'; + + var queryParameters: any = {}; + var headerParams: any = {}; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { + var path = this.url + this.basePath + '/user/login'; + + var queryParameters: any = {}; + var headerParams: any = {}; + + if (username !== undefined) { + queryParameters['username'] = username; + } + + if (password !== undefined) { + queryParameters['password'] = password; + } + + var deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public logoutUser () : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/logout'; + + var queryParameters: any = {}; + var headerParams: any = {}; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { + var path = this.url + this.basePath + '/user/{username}'; + + path = path.replace('{' + 'username' + '}', String(username)); + + var queryParameters: any = {}; + var headerParams: any = {}; + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling getUserByName'); + } + + var deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/{username}'; + + path = path.replace('{' + 'username' + '}', String(username)); + + var queryParameters: any = {}; + var headerParams: any = {}; + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling updateUser'); + } + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'PUT', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public deleteUser (username: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/{username}'; + + path = path.replace('{' + 'username' + '}', String(username)); + + var queryParameters: any = {}; + var headerParams: any = {}; + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling deleteUser'); + } + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'DELETE', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +} +export class PetApi { + private basePath = '/v2'; + + constructor(private url: string, private username: string, private password: string, basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet'; + + var queryParameters: any = {}; + var headerParams: any = {}; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'PUT', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet'; + + var queryParameters: any = {}; + var headerParams: any = {}; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { + var path = this.url + this.basePath + '/pet/findByStatus'; + + var queryParameters: any = {}; + var headerParams: any = {}; + + if (status !== undefined) { + queryParameters['status'] = status; + } + + var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { + var path = this.url + this.basePath + '/pet/findByTags'; + + var queryParameters: any = {}; + var headerParams: any = {}; + + if (tags !== undefined) { + queryParameters['tags'] = tags; + } + + var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling getPetById'); + } + + var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling updatePetWithForm'); + } + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling deletePet'); + } + + headerParams['apiKey'] = apiKey; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'DELETE', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public uploadFile (petId: number, additionalMetadata?: string, file?: file) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}/uploadImage'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling uploadFile'); + } + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +} +export class StoreApi { + private basePath = '/v2'; + + constructor(private url: string, private username: string, private password: string, basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + public getInventory () : Promise<{ response: http.ClientResponse; body: map; }> { + var path = this.url + this.basePath + '/store/inventory'; + + var queryParameters: any = {}; + var headerParams: any = {}; + + var deferred = promise.defer<{ response: http.ClientResponse; body: map; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { + var path = this.url + this.basePath + '/store/order'; + + var queryParameters: any = {}; + var headerParams: any = {}; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { + var path = this.url + this.basePath + '/store/order/{orderId}'; + + path = path.replace('{' + 'orderId' + '}', String(orderId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling getOrderById'); + } + + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/store/order/{orderId}'; + + path = path.replace('{' + 'orderId' + '}', String(orderId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'DELETE', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +} diff --git a/samples/client/petstore/typescript-node/api/PetApi.ts b/samples/client/petstore/typescript-node/api/PetApi.ts deleted file mode 100644 index 02605f2c8a8..00000000000 --- a/samples/client/petstore/typescript-node/api/PetApi.ts +++ /dev/null @@ -1,378 +0,0 @@ -/* tslint:disable:no-unused-variable */ - -export class PetApi { - private basePath = 'http://petstore.swagger.io/v2'; - - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - - public updatePet (body: Pet ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'PUT', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public addPet (body: Pet ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public findPetsByStatus (status: Array ) : Promise<{ response: http.ClientResponse; body: Array; }> { - var path = this.url + this.basePath + '/pet/findByStatus'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - if (status !== undefined) { - queryParameters['status'] = status; - } - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public findPetsByTags (tags: Array ) : Promise<{ response: http.ClientResponse; body: Array; }> { - var path = this.url + this.basePath + '/pet/findByTags'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - if (tags !== undefined) { - queryParameters['tags'] = tags; - } - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public getPetById (petId: number ) : Promise<{ response: http.ClientResponse; body: Pet; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - - path = path.replace('{' + 'petId' + '}', String(petId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public updatePetWithForm (petId: string, name: string, status: string ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - - path = path.replace('{' + 'petId' + '}', String(petId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public deletePet (apiKey: string, petId: number ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - - path = path.replace('{' + 'petId' + '}', String(petId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - - - - - headerParams['apiKey'] = apiKey; - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'DELETE', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public uploadFile (petId: number, additionalMetadata: string, file: file ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}/uploadImage'; - - - path = path.replace('{' + 'petId' + '}', String(petId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - -} diff --git a/samples/client/petstore/typescript-node/api/StoreApi.ts b/samples/client/petstore/typescript-node/api/StoreApi.ts deleted file mode 100644 index 71cfe106fca..00000000000 --- a/samples/client/petstore/typescript-node/api/StoreApi.ts +++ /dev/null @@ -1,192 +0,0 @@ -/* tslint:disable:no-unused-variable */ - -export class StoreApi { - private basePath = 'http://petstore.swagger.io/v2'; - - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - - public getInventory ( ) : Promise<{ response: http.ClientResponse; body: map; }> { - var path = this.url + this.basePath + '/store/inventory'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: map; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public placeOrder (body: Order ) : Promise<{ response: http.ClientResponse; body: Order; }> { - var path = this.url + this.basePath + '/store/order'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public getOrderById (orderId: string ) : Promise<{ response: http.ClientResponse; body: Order; }> { - var path = this.url + this.basePath + '/store/order/{orderId}'; - - - path = path.replace('{' + 'orderId' + '}', String(orderId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public deleteOrder (orderId: string ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/store/order/{orderId}'; - - - path = path.replace('{' + 'orderId' + '}', String(orderId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'DELETE', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - -} diff --git a/samples/client/petstore/typescript-node/api/UserApi.ts b/samples/client/petstore/typescript-node/api/UserApi.ts deleted file mode 100644 index ca6fd41c593..00000000000 --- a/samples/client/petstore/typescript-node/api/UserApi.ts +++ /dev/null @@ -1,372 +0,0 @@ -/* tslint:disable:no-unused-variable */ - -export class UserApi { - private basePath = 'http://petstore.swagger.io/v2'; - - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - - public createUser (body: User ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public createUsersWithArrayInput (body: Array ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/createWithArray'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public createUsersWithListInput (body: Array ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/createWithList'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public loginUser (username: string, password: string ) : Promise<{ response: http.ClientResponse; body: string; }> { - var path = this.url + this.basePath + '/user/login'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - if (username !== undefined) { - queryParameters['username'] = username; - } - if (password !== undefined) { - queryParameters['password'] = password; - } - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public logoutUser ( ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/logout'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public getUserByName (username: string ) : Promise<{ response: http.ClientResponse; body: User; }> { - var path = this.url + this.basePath + '/user/{username}'; - - - path = path.replace('{' + 'username' + '}', String(username)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public updateUser (username: string, body: User ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/{username}'; - - - path = path.replace('{' + 'username' + '}', String(username)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling updateUser'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'PUT', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public deleteUser (username: string ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/{username}'; - - - path = path.replace('{' + 'username' + '}', String(username)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'DELETE', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - -} diff --git a/samples/client/petstore/typescript-node/model/Category.ts b/samples/client/petstore/typescript-node/model/Category.ts deleted file mode 100644 index fc4b2874e93..00000000000 --- a/samples/client/petstore/typescript-node/model/Category.ts +++ /dev/null @@ -1,7 +0,0 @@ -export class Category { - - id: number; - - name: string; -} - diff --git a/samples/client/petstore/typescript-node/model/Order.ts b/samples/client/petstore/typescript-node/model/Order.ts deleted file mode 100644 index b46ad4570a0..00000000000 --- a/samples/client/petstore/typescript-node/model/Order.ts +++ /dev/null @@ -1,26 +0,0 @@ -export class Order { - - id: number; - - petId: number; - - quantity: number; - - shipDate: DateTime; - - /** - * Order Status - */ - status: Order.StatusEnum; - - complete: boolean; -} - -export module Order { - - export enum StatusEnum { - placed = 'placed', - approved = 'approved', - delivered = 'delivered', - } -} diff --git a/samples/client/petstore/typescript-node/model/Pet.ts b/samples/client/petstore/typescript-node/model/Pet.ts deleted file mode 100644 index 4a3faa129ed..00000000000 --- a/samples/client/petstore/typescript-node/model/Pet.ts +++ /dev/null @@ -1,26 +0,0 @@ -export class Pet { - - id: number; - - category: Category; - - name: string; - - photoUrls: Array; - - tags: Array; - - /** - * pet status in the store - */ - status: Pet.StatusEnum; -} - -export module Pet { - - export enum StatusEnum { - available = 'available', - pending = 'pending', - sold = 'sold', - } -} diff --git a/samples/client/petstore/typescript-node/model/Tag.ts b/samples/client/petstore/typescript-node/model/Tag.ts deleted file mode 100644 index 6ae0d4ef576..00000000000 --- a/samples/client/petstore/typescript-node/model/Tag.ts +++ /dev/null @@ -1,7 +0,0 @@ -export class Tag { - - id: number; - - name: string; -} - diff --git a/samples/client/petstore/typescript-node/model/User.ts b/samples/client/petstore/typescript-node/model/User.ts deleted file mode 100644 index fee31563d13..00000000000 --- a/samples/client/petstore/typescript-node/model/User.ts +++ /dev/null @@ -1,22 +0,0 @@ -export class User { - - id: number; - - username: string; - - firstName: string; - - lastName: string; - - email: string; - - password: string; - - phone: string; - - /** - * User Status - */ - userStatus: number; -} - From 88ed496b4421b148700aeea3e00378c52531c2aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Fri, 24 Jul 2015 10:03:02 +0200 Subject: [PATCH 10/33] Extract abstract class for TypeScript generators --- .../AbstractTypeScriptClientCodegen.java | 143 ++++++++++++++ .../TypeScriptAngularClientCodegen.java | 14 +- .../TypeScriptNodeClientCodegen.java | 177 ++---------------- 3 files changed, 166 insertions(+), 168 deletions(-) create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java new file mode 100644 index 00000000000..4b0ae9c4e24 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -0,0 +1,143 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public AbstractTypeScriptClientCodegen() { + super(); + reservedWords = new HashSet(Arrays.asList("abstract", + "continue", "for", "new", "switch", "assert", "default", "if", + "package", "synchronized", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", + "byte", "else", "import", "public", "throws", "case", "enum", + "instanceof", "return", "transient", "catch", "extends", "int", + "short", "try", "char", "final", "interface", "static", "void", + "class", "finally", "const", "super", "while")); + + languageSpecificPrimitives = new HashSet(Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object")); + instantiationTypes.put("array", "Array"); + + typeMapping = new HashMap(); + typeMapping.put("Array", "Array"); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "string"); + typeMapping.put("int", "number"); + typeMapping.put("float", "number"); + typeMapping.put("number", "number"); + typeMapping.put("long", "number"); + typeMapping.put("short", "number"); + typeMapping.put("char", "string"); + typeMapping.put("double", "number"); + typeMapping.put("object", "any"); + typeMapping.put("integer", "number"); + typeMapping.put("Map", "any"); + typeMapping.put("DateTime", "Date"); + + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) + return name; + + // camelize the variable name + // pet_id => PetId + name = camelize(name, true); + + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) + name = escapeReservedWord(name); + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) + throw new RuntimeException(name + + " (reserved word) cannot be used as a model name"); + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) + return type; + } else + type = swaggerType; + return type; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index 9b9422bbcd9..a33a8e2a46f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -1,16 +1,18 @@ package io.swagger.codegen.languages; -import java.io.File; - import io.swagger.codegen.SupportingFile; -public class TypeScriptAngularClientCodegen extends TypeScriptNodeClientCodegen { +public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen { @Override public String getName() { return "typescript-angular"; } - + + public String getHelp() { + return "Generates a TypeScript AngurlarJS client library."; + } + public TypeScriptAngularClientCodegen() { super(); outputFolder = "generated-code/typescript-angular"; @@ -19,8 +21,6 @@ public class TypeScriptAngularClientCodegen extends TypeScriptNodeClientCodegen templateDir = "TypeScript-Angular"; apiPackage = "api"; modelPackage = "model"; - - supportingFiles.clear(); - supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage + File.separator, "api.d.ts")); + supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage, "api.d.ts")); } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index 9e2e1056dcf..b92598b1fb6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -1,169 +1,24 @@ package io.swagger.codegen.languages; -import io.swagger.codegen.*; -import io.swagger.models.properties.*; +import io.swagger.codegen.SupportingFile; -import java.util.*; -import java.io.File; +public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen { -public class TypeScriptNodeClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-typescript-node-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/typescript"; + @Override + public String getName() { + return "typescript-node"; + } - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } + @Override + public String getHelp() { + return "Generates a TypeScript nodejs client library."; + } - @Override - public String getName() { - return "typescript-node"; - } + public TypeScriptNodeClientCodegen() { + super(); + outputFolder = "generated-code/typescript-node"; + templateDir = "TypeScript-node"; + supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); + } - @Override - public String getHelp() { - return "Generates a TypeScript nodejs client library."; - } - - public TypeScriptNodeClientCodegen() { - super(); - outputFolder = "generated-code/typescript-node"; - templateDir = "TypeScript-node"; - - supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); - - reservedWords = new HashSet(Arrays.asList("abstract", - "continue", "for", "new", "switch", "assert", "default", "if", - "package", "synchronized", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", - "byte", "else", "import", "public", "throws", "case", "enum", - "instanceof", "return", "transient", "catch", "extends", "int", - "short", "try", "char", "final", "interface", "static", "void", - "class", "finally", "const", "super", "while")); - - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - - languageSpecificPrimitives = new HashSet(Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object")); - instantiationTypes.put("array", "Array"); - - typeMapping = new HashMap(); - typeMapping.put("Array", "Array"); - typeMapping.put("array", "Array"); - typeMapping.put("List", "Array"); - typeMapping.put("boolean", "boolean"); - typeMapping.put("string", "string"); - typeMapping.put("int", "number"); - typeMapping.put("float", "number"); - typeMapping.put("number", "number"); - typeMapping.put("long", "number"); - typeMapping.put("short", "number"); - typeMapping.put("char", "string"); - typeMapping.put("double", "number"); - typeMapping.put("object", "any"); - typeMapping.put("integer", "number"); - typeMapping.put("Map", "any"); - typeMapping.put("DateTime", "Date"); - - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) - return name; - - // camelize the variable name - // pet_id => PetId - name = camelize(name, true); - - // for reserved word or word starting with number, append _ - if (reservedWords.contains(name) || name.matches("^\\d.*")) - name = escapeReservedWord(name); - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword, e.g. return - if (reservedWords.contains(name)) - throw new RuntimeException(name - + " (reserved word) cannot be used as a model name"); - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + ""; - } - return super.getTypeDeclaration(p); - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) - return type; - } else - type = swaggerType; - return type; - } } From bc8eae838c157eba6fecc6cf86f18a720d0cb486 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Fri, 24 Jul 2015 10:14:42 +0200 Subject: [PATCH 11/33] Beautify typescript angular output --- .../resources/TypeScript-Angular/api.mustache | 35 +++++++++++++------ 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index bd5eaaef87a..427d847663b 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -6,11 +6,11 @@ module {{package}} { 'use strict'; - {{#description}} +{{#description}} /** * {{&description}} */ - {{/description}} +{{/description}} export class {{classname}} { private basePath = '{{contextPath}}'; @@ -21,24 +21,37 @@ module {{package}} { this.basePath = basePath; } } - {{#operation}} +{{#operation}} + public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { var path = this.basePath + '{{path}}'; - {{#pathParams}} + +{{#pathParams}} path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); - {{/pathParams}} + +{{/pathParams}} var queryParameters: any = {}; var headerParams: any = {}; - {{#allParams}}{{#required}} + +{{#allParams}} +{{#required}} // verify required parameter '{{paramName}}' is set if (!{{paramName}}) { throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); } - {{/required}}{{/allParams}} - {{#queryParams}}if ({{paramName}} !== undefined) { + +{{/required}} +{{/allParams}} +{{#queryParams}} + if ({{paramName}} !== undefined) { queryParameters['{{paramName}}'] = {{paramName}}; - }{{/queryParams}} - {{#headerParams}}headerParams['{{paramName}}'] = {{paramName}};{{/headerParams}} + } + +{{/queryParams}} +{{#headerParams}} + headerParams['{{paramName}}'] = {{paramName}}; + +{{/headerParams}} var httpRequestParams: any = { method: '{{httpMethod}}', url: path, @@ -59,7 +72,7 @@ module {{package}} { return this.$http(httpRequestParams); } - {{/operation}} +{{/operation}} } } {{/operations}} From 3723a9ba2d1d78d6a4a15e9216bd3b20ec091181 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Fri, 24 Jul 2015 10:22:41 +0200 Subject: [PATCH 12/33] Updating typescript samples --- .../typescript-angular/{api => }/Category.ts | 2 +- .../typescript-angular/{api => }/Order.ts | 4 +- .../typescript-angular/{api => }/Pet.ts | 2 +- .../typescript-angular/{api => }/PetApi.ts | 153 ++++++++---------- .../typescript-angular/{api => }/StoreApi.ts | 81 ++++------ .../typescript-angular/{api => }/Tag.ts | 2 +- .../typescript-angular/{api => }/User.ts | 2 +- .../typescript-angular/{api => }/UserApi.ts | 153 ++++++++---------- .../typescript-angular/{api => }/api.d.ts | 0 9 files changed, 177 insertions(+), 222 deletions(-) rename samples/client/petstore/typescript-angular/{api => }/Category.ts (91%) rename samples/client/petstore/typescript-angular/{api => }/Order.ts (92%) rename samples/client/petstore/typescript-angular/{api => }/Pet.ts (97%) rename samples/client/petstore/typescript-angular/{api => }/PetApi.ts (74%) rename samples/client/petstore/typescript-angular/{api => }/StoreApi.ts (72%) rename samples/client/petstore/typescript-angular/{api => }/Tag.ts (90%) rename samples/client/petstore/typescript-angular/{api => }/User.ts (96%) rename samples/client/petstore/typescript-angular/{api => }/UserApi.ts (73%) rename samples/client/petstore/typescript-angular/{api => }/api.d.ts (100%) diff --git a/samples/client/petstore/typescript-angular/api/Category.ts b/samples/client/petstore/typescript-angular/Category.ts similarity index 91% rename from samples/client/petstore/typescript-angular/api/Category.ts rename to samples/client/petstore/typescript-angular/Category.ts index e4a3caa208e..2ec6a2b20f9 100644 --- a/samples/client/petstore/typescript-angular/api/Category.ts +++ b/samples/client/petstore/typescript-angular/Category.ts @@ -1,6 +1,6 @@ /// -module api { +module { 'use strict'; export class Category { diff --git a/samples/client/petstore/typescript-angular/api/Order.ts b/samples/client/petstore/typescript-angular/Order.ts similarity index 92% rename from samples/client/petstore/typescript-angular/api/Order.ts rename to samples/client/petstore/typescript-angular/Order.ts index 3f37c608758..f916138d7a0 100644 --- a/samples/client/petstore/typescript-angular/api/Order.ts +++ b/samples/client/petstore/typescript-angular/Order.ts @@ -1,6 +1,6 @@ /// -module api { +module { 'use strict'; export class Order { @@ -11,7 +11,7 @@ module api { quantity: number; - shipDate: DateTime; + shipDate: Date; /** * Order Status diff --git a/samples/client/petstore/typescript-angular/api/Pet.ts b/samples/client/petstore/typescript-angular/Pet.ts similarity index 97% rename from samples/client/petstore/typescript-angular/api/Pet.ts rename to samples/client/petstore/typescript-angular/Pet.ts index c34be9c3dbc..ac8d6b72fdf 100644 --- a/samples/client/petstore/typescript-angular/api/Pet.ts +++ b/samples/client/petstore/typescript-angular/Pet.ts @@ -1,6 +1,6 @@ /// -module api { +module { 'use strict'; export class Pet { diff --git a/samples/client/petstore/typescript-angular/api/PetApi.ts b/samples/client/petstore/typescript-angular/PetApi.ts similarity index 74% rename from samples/client/petstore/typescript-angular/api/PetApi.ts rename to samples/client/petstore/typescript-angular/PetApi.ts index d294cfbebbc..3067994a76c 100644 --- a/samples/client/petstore/typescript-angular/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular/PetApi.ts @@ -2,12 +2,11 @@ /* tslint:disable:no-unused-variable member-ordering */ -module api { +module { 'use strict'; - export class PetApi { - private basePath = 'http://petstore.swagger.io/v2'; + private basePath = '/v2'; static $inject: string[] = ['$http']; @@ -16,15 +15,13 @@ module api { this.basePath = basePath; } } - - public updatePet (body: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public updatePet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'PUT', url: path, @@ -32,11 +29,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -45,15 +42,13 @@ module api { return this.$http(httpRequestParams); } - - public addPet (body: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public addPet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -61,11 +56,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -74,28 +69,28 @@ module api { return this.$http(httpRequestParams); } - - public findPetsByStatus (status: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { + + public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { var path = this.basePath + '/pet/findByStatus'; - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + if (status !== undefined) { queryParameters['status'] = status; } - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -104,28 +99,28 @@ module api { return this.$http(httpRequestParams); } - - public findPetsByTags (tags: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { + + public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { var path = this.basePath + '/pet/findByTags'; - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + if (tags !== undefined) { queryParameters['tags'] = tags; } - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -134,33 +129,31 @@ module api { return this.$http(httpRequestParams); } - - public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/pet/{petId}'; - + path = path.replace('{' + 'petId' + '}', String(petId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling getPetById'); } - - - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -169,33 +162,31 @@ module api { return this.$http(httpRequestParams); } - - public updatePetWithForm (petId: string, name: string, status: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet/{petId}'; - + path = path.replace('{' + 'petId' + '}', String(petId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } - - - + var httpRequestParams: any = { method: 'POST', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -204,33 +195,33 @@ module api { return this.$http(httpRequestParams); } - - public deletePet (apiKey: string, petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet/{petId}'; - + path = path.replace('{' + 'petId' + '}', String(petId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling deletePet'); } - - + headerParams['apiKey'] = apiKey; + var httpRequestParams: any = { method: 'DELETE', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -239,33 +230,31 @@ module api { return this.$http(httpRequestParams); } - - public uploadFile (petId: number, additionalMetadata: string, file: file, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public uploadFile (petId: number, additionalMetadata?: string, file?: file, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet/{petId}/uploadImage'; - + path = path.replace('{' + 'petId' + '}', String(petId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling uploadFile'); } - - - + var httpRequestParams: any = { method: 'POST', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -274,9 +263,5 @@ module api { return this.$http(httpRequestParams); } - } - - angular.module('api_PetApi', ['$http']) - .service('PetApi', PetApi); } diff --git a/samples/client/petstore/typescript-angular/api/StoreApi.ts b/samples/client/petstore/typescript-angular/StoreApi.ts similarity index 72% rename from samples/client/petstore/typescript-angular/api/StoreApi.ts rename to samples/client/petstore/typescript-angular/StoreApi.ts index e8c85b00c45..67f60be3133 100644 --- a/samples/client/petstore/typescript-angular/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/StoreApi.ts @@ -2,12 +2,11 @@ /* tslint:disable:no-unused-variable member-ordering */ -module api { +module { 'use strict'; - export class StoreApi { - private basePath = 'http://petstore.swagger.io/v2'; + private basePath = '/v2'; static $inject: string[] = ['$http']; @@ -16,26 +15,24 @@ module api { this.basePath = basePath; } } - - public getInventory ( extraHttpRequestParams?: any ) : ng.IHttpPromise> { + + public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise> { var path = this.basePath + '/store/inventory'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -44,15 +41,13 @@ module api { return this.$http(httpRequestParams); } - - public placeOrder (body: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public placeOrder (body?: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/store/order'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -60,11 +55,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -73,33 +68,31 @@ module api { return this.$http(httpRequestParams); } - - public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/store/order/{orderId}'; - + path = path.replace('{' + 'orderId' + '}', String(orderId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling getOrderById'); } - - - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -108,33 +101,31 @@ module api { return this.$http(httpRequestParams); } - - public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/store/order/{orderId}'; - + path = path.replace('{' + 'orderId' + '}', String(orderId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling deleteOrder'); } - - - + var httpRequestParams: any = { method: 'DELETE', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -143,9 +134,5 @@ module api { return this.$http(httpRequestParams); } - } - - angular.module('api_StoreApi', ['$http']) - .service('StoreApi', StoreApi); } diff --git a/samples/client/petstore/typescript-angular/api/Tag.ts b/samples/client/petstore/typescript-angular/Tag.ts similarity index 90% rename from samples/client/petstore/typescript-angular/api/Tag.ts rename to samples/client/petstore/typescript-angular/Tag.ts index 33f0ffaa1e2..e614fcc084d 100644 --- a/samples/client/petstore/typescript-angular/api/Tag.ts +++ b/samples/client/petstore/typescript-angular/Tag.ts @@ -1,6 +1,6 @@ /// -module api { +module { 'use strict'; export class Tag { diff --git a/samples/client/petstore/typescript-angular/api/User.ts b/samples/client/petstore/typescript-angular/User.ts similarity index 96% rename from samples/client/petstore/typescript-angular/api/User.ts rename to samples/client/petstore/typescript-angular/User.ts index 57385044943..93b8ae0fde6 100644 --- a/samples/client/petstore/typescript-angular/api/User.ts +++ b/samples/client/petstore/typescript-angular/User.ts @@ -1,6 +1,6 @@ /// -module api { +module { 'use strict'; export class User { diff --git a/samples/client/petstore/typescript-angular/api/UserApi.ts b/samples/client/petstore/typescript-angular/UserApi.ts similarity index 73% rename from samples/client/petstore/typescript-angular/api/UserApi.ts rename to samples/client/petstore/typescript-angular/UserApi.ts index 40d82f73852..10166a0ea90 100644 --- a/samples/client/petstore/typescript-angular/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular/UserApi.ts @@ -2,12 +2,11 @@ /* tslint:disable:no-unused-variable member-ordering */ -module api { +module { 'use strict'; - export class UserApi { - private basePath = 'http://petstore.swagger.io/v2'; + private basePath = '/v2'; static $inject: string[] = ['$http']; @@ -16,15 +15,13 @@ module api { this.basePath = basePath; } } - - public createUser (body: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public createUser (body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -32,11 +29,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -45,15 +42,13 @@ module api { return this.$http(httpRequestParams); } - - public createUsersWithArrayInput (body: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public createUsersWithArrayInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/createWithArray'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -61,11 +56,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -74,15 +69,13 @@ module api { return this.$http(httpRequestParams); } - - public createUsersWithListInput (body: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public createUsersWithListInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/createWithList'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -90,11 +83,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -103,30 +96,32 @@ module api { return this.$http(httpRequestParams); } - - public loginUser (username: string, password: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public loginUser (username?: string, password?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/user/login'; - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + if (username !== undefined) { queryParameters['username'] = username; - }if (password !== undefined) { + } + + if (password !== undefined) { queryParameters['password'] = password; } - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -135,26 +130,24 @@ module api { return this.$http(httpRequestParams); } - - public logoutUser ( extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public logoutUser (extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/logout'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -163,33 +156,31 @@ module api { return this.$http(httpRequestParams); } - - public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/user/{username}'; - + path = path.replace('{' + 'username' + '}', String(username)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling getUserByName'); } - - - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -198,22 +189,20 @@ module api { return this.$http(httpRequestParams); } - - public updateUser (username: string, body: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public updateUser (username: string, body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/{username}'; - + path = path.replace('{' + 'username' + '}', String(username)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling updateUser'); } - - - + var httpRequestParams: any = { method: 'PUT', url: path, @@ -221,11 +210,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -234,33 +223,31 @@ module api { return this.$http(httpRequestParams); } - - public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/{username}'; - + path = path.replace('{' + 'username' + '}', String(username)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling deleteUser'); } - - - + var httpRequestParams: any = { method: 'DELETE', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -269,9 +256,5 @@ module api { return this.$http(httpRequestParams); } - } - - angular.module('api_UserApi', ['$http']) - .service('UserApi', UserApi); } diff --git a/samples/client/petstore/typescript-angular/api/api.d.ts b/samples/client/petstore/typescript-angular/api.d.ts similarity index 100% rename from samples/client/petstore/typescript-angular/api/api.d.ts rename to samples/client/petstore/typescript-angular/api.d.ts From 7a1f3dbf9e5d42da5c5a9321b25ec2119e6d633b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Fri, 24 Jul 2015 10:23:07 +0200 Subject: [PATCH 13/33] Fix angular output to go to one dir to make it build --- .../codegen/languages/TypeScriptAngularClientCodegen.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index a33a8e2a46f..33c3c48c168 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -19,8 +19,6 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode modelTemplateFiles.put("model.mustache", ".ts"); apiTemplateFiles.put("api.mustache", ".ts"); templateDir = "TypeScript-Angular"; - apiPackage = "api"; - modelPackage = "model"; supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage, "api.d.ts")); } } \ No newline at end of file From 34b341874c1b932bbde8a0efbbd1b8d1ba2d2df2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Fri, 24 Jul 2015 11:05:36 +0200 Subject: [PATCH 14/33] Include api and model package in angular --- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 2 +- .../codegen/languages/TypeScriptAngularClientCodegen.java | 6 +++++- .../typescript-angular/{ => API/Client}/Category.ts | 2 +- .../petstore/typescript-angular/{ => API/Client}/Order.ts | 2 +- .../petstore/typescript-angular/{ => API/Client}/Pet.ts | 2 +- .../petstore/typescript-angular/{ => API/Client}/PetApi.ts | 2 +- .../typescript-angular/{ => API/Client}/StoreApi.ts | 2 +- .../petstore/typescript-angular/{ => API/Client}/Tag.ts | 2 +- .../petstore/typescript-angular/{ => API/Client}/User.ts | 2 +- .../petstore/typescript-angular/{ => API/Client}/UserApi.ts | 2 +- .../petstore/typescript-angular/{ => API/Client}/api.d.ts | 0 11 files changed, 14 insertions(+), 10 deletions(-) rename samples/client/petstore/typescript-angular/{ => API/Client}/Category.ts (87%) rename samples/client/petstore/typescript-angular/{ => API/Client}/Order.ts (96%) rename samples/client/petstore/typescript-angular/{ => API/Client}/Pet.ts (96%) rename samples/client/petstore/typescript-angular/{ => API/Client}/PetApi.ts (99%) rename samples/client/petstore/typescript-angular/{ => API/Client}/StoreApi.ts (99%) rename samples/client/petstore/typescript-angular/{ => API/Client}/Tag.ts (86%) rename samples/client/petstore/typescript-angular/{ => API/Client}/User.ts (94%) rename samples/client/petstore/typescript-angular/{ => API/Client}/UserApi.ts (99%) rename samples/client/petstore/typescript-angular/{ => API/Client}/api.d.ts (100%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index bc4f08d7f55..c44e070fe62 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -600,7 +600,7 @@ public class DefaultCodegen { public CodegenProperty fromProperty(String name, Property p) { if (p == null) { - LOGGER.error("unexpected missing property for name " + null); + LOGGER.error("unexpected missing property for name " + name); return null; } CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index 33c3c48c168..8eec2b8772e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -2,6 +2,8 @@ package io.swagger.codegen.languages; import io.swagger.codegen.SupportingFile; +import java.io.File; + public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen { @Override @@ -19,6 +21,8 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode modelTemplateFiles.put("model.mustache", ".ts"); apiTemplateFiles.put("api.mustache", ".ts"); templateDir = "TypeScript-Angular"; - supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage, "api.d.ts")); + apiPackage = "API.Client"; + modelPackage = "API.Client"; + supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts")); } } \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/Category.ts b/samples/client/petstore/typescript-angular/API/Client/Category.ts similarity index 87% rename from samples/client/petstore/typescript-angular/Category.ts rename to samples/client/petstore/typescript-angular/API/Client/Category.ts index 2ec6a2b20f9..7faf87208eb 100644 --- a/samples/client/petstore/typescript-angular/Category.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Category.ts @@ -1,6 +1,6 @@ /// -module { +module API.Client { 'use strict'; export class Category { diff --git a/samples/client/petstore/typescript-angular/Order.ts b/samples/client/petstore/typescript-angular/API/Client/Order.ts similarity index 96% rename from samples/client/petstore/typescript-angular/Order.ts rename to samples/client/petstore/typescript-angular/API/Client/Order.ts index f916138d7a0..abee3a2894b 100644 --- a/samples/client/petstore/typescript-angular/Order.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Order.ts @@ -1,6 +1,6 @@ /// -module { +module API.Client { 'use strict'; export class Order { diff --git a/samples/client/petstore/typescript-angular/Pet.ts b/samples/client/petstore/typescript-angular/API/Client/Pet.ts similarity index 96% rename from samples/client/petstore/typescript-angular/Pet.ts rename to samples/client/petstore/typescript-angular/API/Client/Pet.ts index ac8d6b72fdf..9523bef90b0 100644 --- a/samples/client/petstore/typescript-angular/Pet.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Pet.ts @@ -1,6 +1,6 @@ /// -module { +module API.Client { 'use strict'; export class Pet { diff --git a/samples/client/petstore/typescript-angular/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts similarity index 99% rename from samples/client/petstore/typescript-angular/PetApi.ts rename to samples/client/petstore/typescript-angular/API/Client/PetApi.ts index 3067994a76c..d3052eec52f 100644 --- a/samples/client/petstore/typescript-angular/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -2,7 +2,7 @@ /* tslint:disable:no-unused-variable member-ordering */ -module { +module API.Client { 'use strict'; export class PetApi { diff --git a/samples/client/petstore/typescript-angular/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts similarity index 99% rename from samples/client/petstore/typescript-angular/StoreApi.ts rename to samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index 67f60be3133..f796cef4b94 100644 --- a/samples/client/petstore/typescript-angular/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -2,7 +2,7 @@ /* tslint:disable:no-unused-variable member-ordering */ -module { +module API.Client { 'use strict'; export class StoreApi { diff --git a/samples/client/petstore/typescript-angular/Tag.ts b/samples/client/petstore/typescript-angular/API/Client/Tag.ts similarity index 86% rename from samples/client/petstore/typescript-angular/Tag.ts rename to samples/client/petstore/typescript-angular/API/Client/Tag.ts index e614fcc084d..2ec9b456f27 100644 --- a/samples/client/petstore/typescript-angular/Tag.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Tag.ts @@ -1,6 +1,6 @@ /// -module { +module API.Client { 'use strict'; export class Tag { diff --git a/samples/client/petstore/typescript-angular/User.ts b/samples/client/petstore/typescript-angular/API/Client/User.ts similarity index 94% rename from samples/client/petstore/typescript-angular/User.ts rename to samples/client/petstore/typescript-angular/API/Client/User.ts index 93b8ae0fde6..ca8ac57c7a3 100644 --- a/samples/client/petstore/typescript-angular/User.ts +++ b/samples/client/petstore/typescript-angular/API/Client/User.ts @@ -1,6 +1,6 @@ /// -module { +module API.Client { 'use strict'; export class User { diff --git a/samples/client/petstore/typescript-angular/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts similarity index 99% rename from samples/client/petstore/typescript-angular/UserApi.ts rename to samples/client/petstore/typescript-angular/API/Client/UserApi.ts index 10166a0ea90..eb04f4b31f0 100644 --- a/samples/client/petstore/typescript-angular/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -2,7 +2,7 @@ /* tslint:disable:no-unused-variable member-ordering */ -module { +module API.Client { 'use strict'; export class UserApi { diff --git a/samples/client/petstore/typescript-angular/api.d.ts b/samples/client/petstore/typescript-angular/API/Client/api.d.ts similarity index 100% rename from samples/client/petstore/typescript-angular/api.d.ts rename to samples/client/petstore/typescript-angular/API/Client/api.d.ts From 50736458d081c9b339a096566b071e67474fa6d0 Mon Sep 17 00:00:00 2001 From: Ondrej Novy Date: Fri, 24 Jul 2015 11:45:36 +0200 Subject: [PATCH 15/33] Allow to set cookie in python(3) API constructor. --- .../src/main/resources/python/api_client.mustache | 4 ++-- .../src/main/resources/python3/swagger.mustache | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 37bf1be69c0..16604bca18c 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -45,13 +45,13 @@ class ApiClient(object): :param header_value: a header value to pass when making calls to the API """ def __init__(self, host=Configuration().host, - header_name=None, header_value=None): + header_name=None, header_value=None, cookie=None): self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.host = host - self.cookie = None + self.cookie = cookie # Set default User-Agent. self.user_agent = 'Python-Swagger' diff --git a/modules/swagger-codegen/src/main/resources/python3/swagger.mustache b/modules/swagger-codegen/src/main/resources/python3/swagger.mustache index f99f0d4d250..57f959c380b 100644 --- a/modules/swagger-codegen/src/main/resources/python3/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python3/swagger.mustache @@ -18,13 +18,13 @@ from .models import * class ApiClient: """Generic API client for Swagger client library builds""" - def __init__(self, apiKey=None, apiServer=None): + def __init__(self, apiKey=None, apiServer=None, cookie=None): if apiKey == None: raise Exception('You must pass an apiKey when instantiating the ' 'APIClient') self.apiKey = apiKey self.apiServer = apiServer - self.cookie = None + self.cookie = cookie def callAPI(self, resourcePath, method, queryParams, postData, headerParams=None): From 9fc8c770d3fef93aef6f1e26ecf47882d3acf8d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Sat, 25 Jul 2015 13:55:30 +0200 Subject: [PATCH 16/33] Adding build system for poetaster typescript node sample --- .../petstore/typescript-node/.gitignore | 3 +++ .../petstore/typescript-node/package.json | 19 +++++++++++++++++ .../client/petstore/typescript-node/tsd.json | 21 +++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 samples/client/petstore/typescript-node/.gitignore create mode 100644 samples/client/petstore/typescript-node/package.json create mode 100644 samples/client/petstore/typescript-node/tsd.json diff --git a/samples/client/petstore/typescript-node/.gitignore b/samples/client/petstore/typescript-node/.gitignore new file mode 100644 index 00000000000..ea683e8b6fe --- /dev/null +++ b/samples/client/petstore/typescript-node/.gitignore @@ -0,0 +1,3 @@ +/node_modules +/typings +/api.js \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/package.json b/samples/client/petstore/typescript-node/package.json new file mode 100644 index 00000000000..dd12b489399 --- /dev/null +++ b/samples/client/petstore/typescript-node/package.json @@ -0,0 +1,19 @@ +{ + "name": "petstore-typescript-node-sample", + "version": "1.0.0", + "description": "Sample of generated TypeScript petstore client", + "main": "api.js", + "scripts": { + "postinstall": "tsd reinstall", + "test": "tsc --module commonjs api.ts typings/tsd.d.ts" + }, + "author": "Mads M. Tandrup", + "license": "Apache 2.0", + "dependencies": { + "bluebird": "^2.9.34", + "request": "^2.60.0" + }, + "devDependencies": { + "tsd": "^0.6.3" + } +} diff --git a/samples/client/petstore/typescript-node/tsd.json b/samples/client/petstore/typescript-node/tsd.json new file mode 100644 index 00000000000..d72b84c3173 --- /dev/null +++ b/samples/client/petstore/typescript-node/tsd.json @@ -0,0 +1,21 @@ +{ + "version": "v4", + "repo": "borisyankov/DefinitelyTyped", + "ref": "master", + "path": "typings", + "bundle": "typings/tsd.d.ts", + "installed": { + "bluebird/bluebird.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "request/request.d.ts": { + "commit": "2cc4331067a81e2ae6bc4590e7b33bf286c8f28f" + }, + "form-data/form-data.d.ts": { + "commit": "2cc4331067a81e2ae6bc4590e7b33bf286c8f28f" + }, + "node/node.d.ts": { + "commit": "48b4cb54af76f02b33dccaa0fdd2ae97db7cdd1b" + } + } +} From bbf0ce8c803b8d4d57706a2aeec3d5192a485f40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Sat, 25 Jul 2015 13:57:45 +0200 Subject: [PATCH 17/33] Adding README for sample --- samples/client/petstore/typescript-node/README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 samples/client/petstore/typescript-node/README.md diff --git a/samples/client/petstore/typescript-node/README.md b/samples/client/petstore/typescript-node/README.md new file mode 100644 index 00000000000..e62d97d300c --- /dev/null +++ b/samples/client/petstore/typescript-node/README.md @@ -0,0 +1,14 @@ +# SwaggerClient + +Sample of TypeScript Node.js petstore client + +## Testing the generated code + +``` +npm install +npm test +``` + +## Author + +mads@maetzke-tandrup.dk \ No newline at end of file From 3f9b2a96787eddd79acf790aefba525c2cadcd2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Sat, 25 Jul 2015 14:11:10 +0200 Subject: [PATCH 18/33] Adding build system for typescript AngularJS sample --- .../petstore/typescript-angular/.gitignore | 3 +++ .../petstore/typescript-angular/README.md | 14 ++++++++++++++ .../petstore/typescript-angular/package.json | 19 +++++++++++++++++++ .../petstore/typescript-angular/tsconfig.json | 18 ++++++++++++++++++ .../petstore/typescript-angular/tsd.json | 15 +++++++++++++++ .../petstore/typescript-node/package.json | 3 ++- 6 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 samples/client/petstore/typescript-angular/.gitignore create mode 100644 samples/client/petstore/typescript-angular/README.md create mode 100644 samples/client/petstore/typescript-angular/package.json create mode 100644 samples/client/petstore/typescript-angular/tsconfig.json create mode 100644 samples/client/petstore/typescript-angular/tsd.json diff --git a/samples/client/petstore/typescript-angular/.gitignore b/samples/client/petstore/typescript-angular/.gitignore new file mode 100644 index 00000000000..abfad1bf5e2 --- /dev/null +++ b/samples/client/petstore/typescript-angular/.gitignore @@ -0,0 +1,3 @@ +/node_modules +/typings +/client.js \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/README.md b/samples/client/petstore/typescript-angular/README.md new file mode 100644 index 00000000000..ba2e8d1ef85 --- /dev/null +++ b/samples/client/petstore/typescript-angular/README.md @@ -0,0 +1,14 @@ +# SwaggerClient + +Sample of TypeScript AngularJS petstore client + +## Testing the generated code + +``` +npm install +npm test +``` + +## Author + +mads@maetzke-tandrup.dk \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/package.json b/samples/client/petstore/typescript-angular/package.json new file mode 100644 index 00000000000..1d5568b1db5 --- /dev/null +++ b/samples/client/petstore/typescript-angular/package.json @@ -0,0 +1,19 @@ +{ + "name": "petstore-typescript-node-sample", + "version": "1.0.0", + "description": "Sample of generated TypeScript petstore client", + "main": "api.js", + "scripts": { + "postinstall": "tsd reinstall", + "test": "tsc" + }, + "author": "Mads M. Tandrup", + "license": "Apache 2.0", + "dependencies": { + "angular": "^1.4.3" + }, + "devDependencies": { + "tsd": "^0.6.3", + "typescript": "^1.5.3" + } +} diff --git a/samples/client/petstore/typescript-angular/tsconfig.json b/samples/client/petstore/typescript-angular/tsconfig.json new file mode 100644 index 00000000000..c389d5011ff --- /dev/null +++ b/samples/client/petstore/typescript-angular/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "noImplicitAny": true, + "out": "client.js" + }, + "files": [ + "API/Client/Category.ts", + "API/Client/Pet.ts", + "API/Client/StoreApi.ts", + "API/Client/User.ts", + "API/Client/api.d.ts", + "API/Client/Order.ts", + "API/Client/PetApi.ts", + "API/Client/Tag.ts", + "API/Client/UserApi.ts", + "typings/tsd.d.ts" + ] +} diff --git a/samples/client/petstore/typescript-angular/tsd.json b/samples/client/petstore/typescript-angular/tsd.json new file mode 100644 index 00000000000..182b9f68fa2 --- /dev/null +++ b/samples/client/petstore/typescript-angular/tsd.json @@ -0,0 +1,15 @@ +{ + "version": "v4", + "repo": "borisyankov/DefinitelyTyped", + "ref": "master", + "path": "typings", + "bundle": "typings/tsd.d.ts", + "installed": { + "angularjs/angular.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "jquery/jquery.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + } + } +} diff --git a/samples/client/petstore/typescript-node/package.json b/samples/client/petstore/typescript-node/package.json index dd12b489399..e0c2a74a47c 100644 --- a/samples/client/petstore/typescript-node/package.json +++ b/samples/client/petstore/typescript-node/package.json @@ -14,6 +14,7 @@ "request": "^2.60.0" }, "devDependencies": { - "tsd": "^0.6.3" + "tsd": "^0.6.3", + "typescript": "^1.5.3" } } From f98974190e4ddabaf2c5bfb831fb6d34ec4d560a Mon Sep 17 00:00:00 2001 From: Atsushi Nagase Date: Thu, 23 Jul 2015 19:05:25 +0900 Subject: [PATCH 19/33] [Swift] Support file upload with Alamofire 1.3.0 refs: - https://github.com/Alamofire/Alamofire/milestones/1.3.0 - https://github.com/Alamofire/Alamofire/pull/539 --- .../codegen/languages/SwiftCodegen.java | 2 +- .../swift/AlamofireImplementations.mustache | 36 ++++++++++++++++++- .../src/main/resources/swift/api.mustache | 4 +-- 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 7915e4e3e2c..55c3864adb7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -100,7 +100,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("number", "Double"); typeMapping.put("double", "Double"); typeMapping.put("object", "String"); - typeMapping.put("file", "NSData"); + typeMapping.put("file", "NSURL"); importMapping = new HashMap(); diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 61e2bf2886d..d795e9cb6c2 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -29,7 +29,41 @@ class AlamofireRequestBuilder: RequestBuilder { managerStore[managerId] = manager let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL - let request = manager.request(Alamofire.Method(rawValue: method)!, URLString, parameters: parameters, encoding: encoding) + let xMethod = Alamofire.Method(rawValue: method) + var request: Request? = nil + let fileKeys = parameters == nil ? [] : map(filter(parameters!) { $1.isKindOfClass(NSURL) }) { $0.0 } + + if fileKeys.count > 0 { + manager.upload( + xMethod!, URLString, headers: nil, + multipartFormData: { mpForm in + for (k, v) in self.parameters! { + if v.isKindOfClass(NSURL) { + mpForm.appendBodyPart(fileURL: v as! NSURL, name: k) + } else if let str = v as? NSString { + mpForm.appendBodyPart(data: str.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + } else if let num = v as? NSNumber { + mpForm.appendBodyPart(data: num.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + } + } + }, + encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + self.processRequest(upload, managerId, completion) + case .Failure(let encodingError): + completion(response: nil, erorr: encodingError) + } + } + ) + } else { + processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + } + + } + + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, erorr: NSError?) -> Void) { if let credential = self.credential { request.authenticate(usingCredential: credential) } diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index cdc2395dc03..7595a1fa81d 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -35,7 +35,7 @@ extension {{projectName}}API { public class func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}} path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}})", options: .LiteralSearch, range: nil){{/pathParams}} - let url = {{projectName}}API.basePath + path + let URLString = {{projectName}}API.basePath + path {{#bodyParam}} let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} let nillableParameters: [String:AnyObject?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}} @@ -47,7 +47,7 @@ extension {{projectName}}API { let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() - return requestBuilder(method: "{{httpMethod}}", URLString: url, parameters: parameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) + return requestBuilder(method: "{{httpMethod}}", URLString: URLString, parameters: parameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) } {{/operation}} } From 5dcdadb751e07d39efaee17125ef6a934ce83a5f Mon Sep 17 00:00:00 2001 From: Atsushi Nagase Date: Thu, 23 Jul 2015 21:50:01 +0900 Subject: [PATCH 20/33] [Swift] tweak conditions https://github.com/ngs/swagger-codegen/commit/336bb87b5371ff857883fc5eb1da7bff62c72f3f#commitcomment-12318006 --- .../swift/AlamofireImplementations.mustache | 22 ++++++++++++------- .../main/resources/swift/Cartfile.mustache | 2 +- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index d795e9cb6c2..c1718cb6780 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -30,7 +30,6 @@ class AlamofireRequestBuilder: RequestBuilder { let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL let xMethod = Alamofire.Method(rawValue: method) - var request: Request? = nil let fileKeys = parameters == nil ? [] : map(filter(parameters!) { $1.isKindOfClass(NSURL) }) { $0.0 } if fileKeys.count > 0 { @@ -38,12 +37,19 @@ class AlamofireRequestBuilder: RequestBuilder { xMethod!, URLString, headers: nil, multipartFormData: { mpForm in for (k, v) in self.parameters! { - if v.isKindOfClass(NSURL) { - mpForm.appendBodyPart(fileURL: v as! NSURL, name: k) - } else if let str = v as? NSString { - mpForm.appendBodyPart(data: str.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) - } else if let num = v as? NSNumber { - mpForm.appendBodyPart(data: num.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + switch v { + case let fileURL as NSURL: + mpForm.appendBodyPart(fileURL: fileURL, name: k) + break + case let string as NSString: + mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + case let number as NSNumber: + mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break } } }, @@ -100,7 +106,7 @@ class AlamofireRequestBuilder: RequestBuilder { completion(response: response, erorr: nil) return } - + completion(response: nil, erorr: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) } } diff --git a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache index af74617bcf2..f7838edf7ca 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache @@ -1,2 +1,2 @@ -github "Alamofire/Alamofire" >= 1.2 +github "Alamofire/Alamofire" >= 1.3 github "mxcl/PromiseKit" >=1.5.3 From 979a704310a8c4c6058c5ec3a2c1c81872f4699b Mon Sep 17 00:00:00 2001 From: Atsushi Nagase Date: Sun, 26 Jul 2015 03:01:11 +0900 Subject: [PATCH 21/33] [Swift] Update Alamofire to 1.3 in Podspec --- .../swagger-codegen/src/main/resources/swift/Podspec.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index a7be288ebcd..7933315b958 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -15,5 +15,5 @@ Pod::Spec.new do |s| s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift' s.dependency 'PromiseKit', '~> 2.1' - s.dependency 'Alamofire', '~> 1.2' + s.dependency 'Alamofire', '~> 1.3' end From b56da43953107f7ca21dbc4769a3f37d65613c02 Mon Sep 17 00:00:00 2001 From: Atsushi Nagase Date: Sun, 26 Jul 2015 03:19:33 +0900 Subject: [PATCH 22/33] [Swift] Add version to Podspec template --- .../swagger-codegen/src/main/resources/swift/Podspec.mustache | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index a7be288ebcd..53fac508941 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -3,6 +3,7 @@ Pod::Spec.new do |s| s.summary = '{{projectDescription}}'{{/projectDescription}} s.ios.deployment_target = '8.0' s.osx.deployment_target = '10.9' + s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}0.0.1{{/podVersion}}' s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}}{{#podAuthors}} s.authors = {{& podAuthors}}{{/podAuthors}}{{#podSocialMediaURL}} s.social_media_url = '{{podSocialMediaURL}}'{{/podSocialMediaURL}}{{#podDocsetURL}} From b0f6b4959544767f0863c91d9072032d63b4e28a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Sat, 25 Jul 2015 22:02:06 +0200 Subject: [PATCH 23/33] Fix TypeScript Map type --- .../codegen/languages/AbstractTypeScriptClientCodegen.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index 4b0ae9c4e24..a31cd39997f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -121,9 +121,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + ""; + return "{ [key: string]: "+ getTypeDeclaration(inner) + "; }"; } return super.getTypeDeclaration(p); } From fea8e680dff165751b8a035325a657cf0e8956bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Sat, 25 Jul 2015 22:05:29 +0200 Subject: [PATCH 24/33] Fix TypeScript node file upload --- .../AbstractTypeScriptClientCodegen.java | 2 ++ .../resources/TypeScript-node/api.mustache | 29 ++++++++++++++++--- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index a31cd39997f..883ad66ff7f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -122,6 +122,8 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); return "{ [key: string]: "+ getTypeDeclaration(inner) + "; }"; + } else if (p instanceof FileProperty) { + return "any"; } return super.getTypeDeclaration(p); } diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index 67b7d4fc3fa..098cd8bc1dc 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -67,6 +67,7 @@ export class {{classname}} { {{/pathParams}} var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; {{#allParams}} {{#required}} @@ -87,19 +88,39 @@ export class {{classname}} { headerParams['{{paramName}}'] = {{paramName}}; {{/headerParams}} + var useFormData = false; + +{{#formParams}} + if ({{paramName}} !== undefined) { + formParams['{{paramName}}'] = {{paramName}}; + } +{{#isFile}} + useFormData = true; +{{/isFile}} + +{{/formParams}} var deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); - request({ + var requestOptions: any = { method: '{{httpMethod}}', qs: queryParameters, uri: path, json: true, - {{#bodyParam}}body: {{paramName}}, - {{/bodyParam}} +{{#bodyParam}} + body: {{paramName}}, +{{/bodyParam}} auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { From e41a475335e6b3510997c6aa63d41c2b1b7ca0ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Sat, 25 Jul 2015 22:05:43 +0200 Subject: [PATCH 25/33] Update typescript node sample --- .../client/petstore/typescript-node/api.ts | 323 ++++++++++++++---- 1 file changed, 260 insertions(+), 63 deletions(-) diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index b165be2d313..bef650a81e8 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -85,20 +85,29 @@ export class UserApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); - request({ + var requestOptions: any = { method: 'POST', qs: queryParameters, uri: path, json: true, body: body, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -118,20 +127,29 @@ export class UserApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); - request({ + var requestOptions: any = { method: 'POST', qs: queryParameters, uri: path, json: true, body: body, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -151,20 +169,29 @@ export class UserApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); - request({ + var requestOptions: any = { method: 'POST', qs: queryParameters, uri: path, json: true, body: body, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -184,6 +211,7 @@ export class UserApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; if (username !== undefined) { queryParameters['username'] = username; @@ -193,18 +221,26 @@ export class UserApi { queryParameters['password'] = password; } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); - request({ + var requestOptions: any = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -224,19 +260,28 @@ export class UserApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); - request({ + var requestOptions: any = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -258,24 +303,33 @@ export class UserApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling getUserByName'); } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); - request({ + var requestOptions: any = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -297,25 +351,34 @@ export class UserApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling updateUser'); } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); - request({ + var requestOptions: any = { method: 'PUT', qs: queryParameters, uri: path, json: true, body: body, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -337,24 +400,33 @@ export class UserApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling deleteUser'); } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); - request({ + var requestOptions: any = { method: 'DELETE', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -383,20 +455,29 @@ export class PetApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); - request({ + var requestOptions: any = { method: 'PUT', qs: queryParameters, uri: path, json: true, body: body, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -416,20 +497,29 @@ export class PetApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); - request({ + var requestOptions: any = { method: 'POST', qs: queryParameters, uri: path, json: true, body: body, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -449,23 +539,32 @@ export class PetApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; if (status !== undefined) { queryParameters['status'] = status; } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - request({ + var requestOptions: any = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -485,23 +584,32 @@ export class PetApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; if (tags !== undefined) { queryParameters['tags'] = tags; } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - request({ + var requestOptions: any = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -523,24 +631,33 @@ export class PetApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling getPetById'); } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); - request({ + var requestOptions: any = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -562,24 +679,41 @@ export class PetApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } + var useFormData = false; + if (name !== undefined) { + formParams['name'] = name; + } + + if (status !== undefined) { + formParams['status'] = status; + } + var deferred = promise.defer<{ response: http.ClientResponse; }>(); - request({ + var requestOptions: any = { method: 'POST', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -601,6 +735,7 @@ export class PetApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; // verify required parameter 'petId' is set if (!petId) { @@ -609,18 +744,26 @@ export class PetApi { headerParams['apiKey'] = apiKey; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); - request({ + var requestOptions: any = { method: 'DELETE', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -635,31 +778,49 @@ export class PetApi { return deferred.promise; } - public uploadFile (petId: number, additionalMetadata?: string, file?: file) : Promise<{ response: http.ClientResponse; }> { + public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; }> { var path = this.url + this.basePath + '/pet/{petId}/uploadImage'; path = path.replace('{' + 'petId' + '}', String(petId)); var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling uploadFile'); } + var useFormData = false; + if (additionalMetadata !== undefined) { + formParams['additionalMetadata'] = additionalMetadata; + } + + if (file !== undefined) { + formParams['file'] = file; + } + useFormData = true; + var deferred = promise.defer<{ response: http.ClientResponse; }>(); - request({ + var requestOptions: any = { method: 'POST', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -683,24 +844,33 @@ export class StoreApi { } } - public getInventory () : Promise<{ response: http.ClientResponse; body: map; }> { + public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { var path = this.url + this.basePath + '/store/inventory'; var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; - var deferred = promise.defer<{ response: http.ClientResponse; body: map; }>(); + var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); - request({ + var requestOptions: any = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -720,20 +890,29 @@ export class StoreApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - request({ + var requestOptions: any = { method: 'POST', qs: queryParameters, uri: path, json: true, body: body, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -755,24 +934,33 @@ export class StoreApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling getOrderById'); } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - request({ + var requestOptions: any = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { @@ -794,24 +982,33 @@ export class StoreApi { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling deleteOrder'); } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); - request({ + var requestOptions: any = { method: 'DELETE', qs: queryParameters, uri: path, json: true, - auth: { username: this.username, password: this.password } - }, (error, response, body) => { + } + + if (useFormData) { + requestOptions.formData = formParams; + } else { + requestOptions.form = formParams; + } + + request(requestOptions, (error, response, body) => { if (error) { deferred.reject(error); } else { From 02da80e83798e2d39e8f92dbcbb0d9770e8ee658 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Sun, 26 Jul 2015 08:22:32 +0200 Subject: [PATCH 26/33] Update sample with small test script --- .../resources/TypeScript-node/api.mustache | 17 +- .../petstore/typescript-node/.gitignore | 2 +- .../client/petstore/typescript-node/api.ts | 360 ++++++++++++------ .../client/petstore/typescript-node/client.ts | 44 +++ .../petstore/typescript-node/package.json | 2 +- .../petstore/typescript-node/tsconfig.json | 11 + .../client/petstore/typescript-node/tsd.json | 6 +- 7 files changed, 311 insertions(+), 131 deletions(-) create mode 100644 samples/client/petstore/typescript-node/client.ts create mode 100644 samples/client/petstore/typescript-node/tsconfig.json diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index 098cd8bc1dc..2d3de0411b6 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -101,7 +101,7 @@ export class {{classname}} { {{/formParams}} var deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: '{{httpMethod}}', qs: queryParameters, uri: path, @@ -109,15 +109,20 @@ export class {{classname}} { {{#bodyParam}} body: {{paramName}}, {{/bodyParam}} - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { diff --git a/samples/client/petstore/typescript-node/.gitignore b/samples/client/petstore/typescript-node/.gitignore index ea683e8b6fe..5c06ad7bc24 100644 --- a/samples/client/petstore/typescript-node/.gitignore +++ b/samples/client/petstore/typescript-node/.gitignore @@ -1,3 +1,3 @@ /node_modules /typings -/api.js \ No newline at end of file +/*.js diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index bef650a81e8..cf556042fae 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -88,23 +88,29 @@ export class UserApi { var formParams: any = {}; var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'POST', qs: queryParameters, uri: path, json: true, body: body, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -130,23 +136,29 @@ export class UserApi { var formParams: any = {}; var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'POST', qs: queryParameters, uri: path, json: true, body: body, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -172,23 +184,29 @@ export class UserApi { var formParams: any = {}; var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'POST', qs: queryParameters, uri: path, json: true, body: body, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -222,22 +240,28 @@ export class UserApi { } var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -263,22 +287,28 @@ export class UserApi { var formParams: any = {}; var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -311,22 +341,28 @@ export class UserApi { } var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -359,23 +395,29 @@ export class UserApi { } var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'PUT', qs: queryParameters, uri: path, json: true, body: body, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -408,22 +450,28 @@ export class UserApi { } var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -458,23 +506,29 @@ export class PetApi { var formParams: any = {}; var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'PUT', qs: queryParameters, uri: path, json: true, body: body, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -500,23 +554,29 @@ export class PetApi { var formParams: any = {}; var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'POST', qs: queryParameters, uri: path, json: true, body: body, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -546,22 +606,28 @@ export class PetApi { } var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -591,22 +657,28 @@ export class PetApi { } var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -639,22 +711,28 @@ export class PetApi { } var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -687,6 +765,7 @@ export class PetApi { } var useFormData = false; + if (name !== undefined) { formParams['name'] = name; } @@ -697,20 +776,25 @@ export class PetApi { var deferred = promise.defer<{ response: http.ClientResponse; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'POST', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -745,22 +829,28 @@ export class PetApi { headerParams['apiKey'] = apiKey; var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -793,6 +883,7 @@ export class PetApi { } var useFormData = false; + if (additionalMetadata !== undefined) { formParams['additionalMetadata'] = additionalMetadata; } @@ -804,20 +895,25 @@ export class PetApi { var deferred = promise.defer<{ response: http.ClientResponse; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'POST', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -852,22 +948,28 @@ export class StoreApi { var formParams: any = {}; var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -893,23 +995,29 @@ export class StoreApi { var formParams: any = {}; var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'POST', qs: queryParameters, uri: path, json: true, body: body, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -942,22 +1050,28 @@ export class StoreApi { } var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'GET', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { @@ -990,22 +1104,28 @@ export class StoreApi { } var useFormData = false; + var deferred = promise.defer<{ response: http.ClientResponse; }>(); - var requestOptions: any = { + var requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, uri: path, json: true, - auth: { + } + + if (this.username !== undefined) { + requestOptions.auth = { username: this.username, password: this.password } } - if (useFormData) { - requestOptions.formData = formParams; - } else { - requestOptions.form = formParams; + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } } request(requestOptions, (error, response, body) => { diff --git a/samples/client/petstore/typescript-node/client.ts b/samples/client/petstore/typescript-node/client.ts new file mode 100644 index 00000000000..1a99ad67d7b --- /dev/null +++ b/samples/client/petstore/typescript-node/client.ts @@ -0,0 +1,44 @@ +import api = require('./api'); + +var petApi = new api.PetApi('http://petstore.swagger.io', undefined, undefined); + +var pet = new api.Pet(); +pet.name = 'TypeScriptDoggie'; + +var petId: any; + +petApi.addPet(pet) +.then((res) => { + var newPet = (res.response).body; + petId = (res.response).body.id; + console.log(`Created pet with ID ${petId}`); + newPet.status = api.Pet.StatusEnum.available; + return petApi.updatePet(newPet); +}) +.then((res) => { + console.log('Updated pet using POST body'); + return petApi.updatePetWithForm(petId, undefined, "pending"); +}) +.then((res) => { + console.log('Updated pet using POST form'); + return petApi.getPetById(petId); +}) +.then((res) => { + console.log('Got pet by ID: ' + JSON.stringify(res.body)); + if (res.body.status != api.Pet.StatusEnum.pending) { + throw new Error("Unexpected pet status"); + } + return petApi.deletePet(petId); +}) +.then((res) => { + console.log('Deleted pet'); +}) +.catch((err:any) => { + console.error(err); +}); + +//var pets = petApi.findPetsByStatus(['available']); + +//pets.then((data:any) => { +//console.log(data); +//}); diff --git a/samples/client/petstore/typescript-node/package.json b/samples/client/petstore/typescript-node/package.json index e0c2a74a47c..8cca4d04841 100644 --- a/samples/client/petstore/typescript-node/package.json +++ b/samples/client/petstore/typescript-node/package.json @@ -5,7 +5,7 @@ "main": "api.js", "scripts": { "postinstall": "tsd reinstall", - "test": "tsc --module commonjs api.ts typings/tsd.d.ts" + "test": "tsc && node client.js" }, "author": "Mads M. Tandrup", "license": "Apache 2.0", diff --git a/samples/client/petstore/typescript-node/tsconfig.json b/samples/client/petstore/typescript-node/tsconfig.json new file mode 100644 index 00000000000..de28deb89cc --- /dev/null +++ b/samples/client/petstore/typescript-node/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "module": "commonjs", + "noImplicitAny": true + }, + "files": [ + "api.ts", + "client.ts", + "typings/tsd.d.ts" + ] +} diff --git a/samples/client/petstore/typescript-node/tsd.json b/samples/client/petstore/typescript-node/tsd.json index d72b84c3173..89e4861f949 100644 --- a/samples/client/petstore/typescript-node/tsd.json +++ b/samples/client/petstore/typescript-node/tsd.json @@ -9,13 +9,13 @@ "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" }, "request/request.d.ts": { - "commit": "2cc4331067a81e2ae6bc4590e7b33bf286c8f28f" + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" }, "form-data/form-data.d.ts": { - "commit": "2cc4331067a81e2ae6bc4590e7b33bf286c8f28f" + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" }, "node/node.d.ts": { - "commit": "48b4cb54af76f02b33dccaa0fdd2ae97db7cdd1b" + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" } } } From dee828622a78b03fdc7370a709332392e58daf80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Sun, 26 Jul 2015 14:26:01 +0200 Subject: [PATCH 27/33] Test file upload in sample client --- .../client/petstore/typescript-node/README.md | 2 ++ .../client/petstore/typescript-node/client.ts | 20 ++++++++++-------- .../petstore/typescript-node/sample.png | Bin 0 -> 95 bytes 3 files changed, 13 insertions(+), 9 deletions(-) create mode 100644 samples/client/petstore/typescript-node/sample.png diff --git a/samples/client/petstore/typescript-node/README.md b/samples/client/petstore/typescript-node/README.md index e62d97d300c..10cd4ff7661 100644 --- a/samples/client/petstore/typescript-node/README.md +++ b/samples/client/petstore/typescript-node/README.md @@ -9,6 +9,8 @@ npm install npm test ``` +This will compile the code and run a small test application that will do some simple test calls to the Swagger Petstore API. + ## Author mads@maetzke-tandrup.dk \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/client.ts b/samples/client/petstore/typescript-node/client.ts index 1a99ad67d7b..3bab396a7d1 100644 --- a/samples/client/petstore/typescript-node/client.ts +++ b/samples/client/petstore/typescript-node/client.ts @@ -1,4 +1,5 @@ import api = require('./api'); +import fs = require('fs'); var petApi = new api.PetApi('http://petstore.swagger.io', undefined, undefined); @@ -7,6 +8,7 @@ pet.name = 'TypeScriptDoggie'; var petId: any; +// Test various API calls to the petstore petApi.addPet(pet) .then((res) => { var newPet = (res.response).body; @@ -21,6 +23,10 @@ petApi.addPet(pet) }) .then((res) => { console.log('Updated pet using POST form'); + return petApi.uploadFile(petId, undefined, fs.createReadStream('sample.png')); +}) +.then((res) => { + console.log('Uploaded image'); return petApi.getPetById(petId); }) .then((res) => { @@ -28,17 +34,13 @@ petApi.addPet(pet) if (res.body.status != api.Pet.StatusEnum.pending) { throw new Error("Unexpected pet status"); } +}) +.catch((err:any) => { + console.error(err); +}) +.finally(() => { return petApi.deletePet(petId); }) .then((res) => { console.log('Deleted pet'); -}) -.catch((err:any) => { - console.error(err); }); - -//var pets = petApi.findPetsByStatus(['available']); - -//pets.then((data:any) => { -//console.log(data); -//}); diff --git a/samples/client/petstore/typescript-node/sample.png b/samples/client/petstore/typescript-node/sample.png new file mode 100644 index 0000000000000000000000000000000000000000..c5916f289705642eec4975cf51458b9afeefe46c GIT binary patch literal 95 zcmeAS@N?(olHy`uVBq!ia0vp^j3CU&3?x-=hn)ga%mF?juK#@*VoWXSL2@NQe!*uh mnS}iXa=1KQ978JRBqsscYz)k1<~1vTECx?kKbLh*2~7ZT-W2Wt literal 0 HcmV?d00001 From 3b9b3e82f961e3aaa380d568b5f48ced28076bc9 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Mon, 27 Jul 2015 10:27:48 +0800 Subject: [PATCH 28/33] Update comments in objc client --- .../src/main/resources/objc/Configuration-header.mustache | 8 ++++---- .../client/petstore/objc/SwaggerClient/SWGConfiguration.h | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache index 56e9fcaecd5..6b311e968b0 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache @@ -2,8 +2,8 @@ /** The `{{classPrefix}}Configuration` class manages the configurations for the sdk. * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @interface {{classPrefix}}Configuration : NSObject @@ -41,14 +41,14 @@ /** * Logging Settings */ - + /** * Debug switch, default false */ @property (nonatomic) BOOL debug; /** - * Debug file location, default nil + * Debug file location, default log in console */ @property (nonatomic) NSString *loggingFile; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h index 4b7f318b5ec..0ccbe0cd8f6 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h @@ -2,8 +2,8 @@ /** The `SWGConfiguration` class manages the configurations for the sdk. * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @interface SWGConfiguration : NSObject @@ -41,14 +41,14 @@ /** * Logging Settings */ - + /** * Debug switch, default false */ @property (nonatomic) BOOL debug; /** - * Debug file location, default nil + * Debug file location, default log in console */ @property (nonatomic) NSString *loggingFile; From b18cc5e0de6b8ae3326a3a457d4cbbed64796824 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Mon, 27 Jul 2015 10:13:36 +0200 Subject: [PATCH 29/33] Include header parameters --- .../src/main/resources/TypeScript-node/api.mustache | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index 2d3de0411b6..9064a6838a1 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -104,6 +104,7 @@ export class {{classname}} { var requestOptions: request.Options = { method: '{{httpMethod}}', qs: queryParameters, + headers: headerParams, uri: path, json: true, {{#bodyParam}} From fde5c60cb0e2465fe93688cd81d601e373b684e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Mon, 27 Jul 2015 10:18:38 +0200 Subject: [PATCH 30/33] Support authentication from swagger in TypeScript Node --- .../resources/TypeScript-node/api.mustache | 114 +++++++- .../client/petstore/typescript-node/api.ts | 275 +++++++++++------- .../client/petstore/typescript-node/client.ts | 7 +- .../petstore/typescript-node/tsconfig.json | 3 +- 4 files changed, 280 insertions(+), 119 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index 9064a6838a1..f8d4577ee7a 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -40,6 +40,52 @@ export module {{classname}} { {{/model}} {{/models}} +interface Authentication { + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: request.Options): void; +} + +class HttpBasicAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + requestOptions.auth = { + username: this.username, password: this.password + } + } +} + +class ApiKeyAuth implements Authentication { + public apiKey: string; + + constructor(private location: string, private paramName: string) { + } + + applyToRequest(requestOptions: request.Options): void { + if (this.location == "query") { + (requestOptions.qs)[this.paramName] = this.apiKey; + } else if (this.location == "header") { + requestOptions.headers[this.paramName] = this.apiKey; + } + } +} + +class OAuth implements Authentication { + applyToRequest(requestOptions: request.Options): void { + // TODO: support oauth + } +} + +class VoidAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + // Do nothing + } +} + {{#apiInfo}} {{#apis}} {{#operations}} @@ -50,12 +96,64 @@ export module {{classname}} { {{/description}} export class {{classname}} { private basePath = '{{contextPath}}'; + public authentications = { + 'default': new VoidAuth(), +{{#authMethods}} +{{#isBasic}} + '{{name}}': new HttpBasicAuth(), +{{/isBasic}} +{{#isApiKey}} + '{{name}}': new ApiKeyAuth({{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{^isKeyInHeader}}'query'{{/isKeyInHeader}}, '{{keyParamName}}'), +{{/isApiKey}} +{{#isOAuth}} + '{{name}}': new OAuth(), +{{/isOAuth}} +{{/authMethods}} + } - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; + constructor(url: string, basePath?: string); +{{#authMethods}} +{{#isBasic}} + constructor(url: string, username: string, password: string, basePath?: string); +{{/isBasic}} +{{/authMethods}} + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { +{{#authMethods}} +{{#isBasic}} + this.username = basePathOrUsername; + this.password = password +{{/isBasic}} +{{/authMethods}} + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } } } +{{#authMethods}} +{{#isBasic}} + + set username(username: string) { + this.authentications.{{name}}.username = username; + } + + set password(password: string) { + this.authentications.{{name}}.password = password; + } +{{/isBasic}} +{{#isApiKey}} + + set apiKey(key: string) { + this.authentications.{{name}}.apiKey = key; + } +{{/isApiKey}} +{{#isOAuth}} +{{/isOAuth}} +{{/authMethods}} {{#operation}} public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { @@ -112,11 +210,11 @@ export class {{classname}} { {{/bodyParam}} } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } +{{#authMethods}} + this.authentications.{{name}}.applyToRequest(requestOptions); + +{{/authMethods}} + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index cf556042fae..a382508dc28 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -71,15 +71,78 @@ export module Order { } } +interface Authentication { + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: request.Options): void; +} + +class HttpBasicAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + requestOptions.auth = { + username: this.username, password: this.password + } + } +} + +class ApiKeyAuth implements Authentication { + public apiKey: string; + + constructor(private location: string, private paramName: string) { + } + + applyToRequest(requestOptions: request.Options): void { + if (this.location == "query") { + (requestOptions.qs)[this.paramName] = this.apiKey; + } else if (this.location == "header") { + requestOptions.headers[this.paramName] = this.apiKey; + } + } +} + +class OAuth implements Authentication { + applyToRequest(requestOptions: request.Options): void { + // TODO: support oauth + } +} + +class VoidAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + // Do nothing + } +} + export class UserApi { private basePath = '/v2'; + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } } } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + public createUser (body?: User) : Promise<{ response: http.ClientResponse; }> { var path = this.url + this.basePath + '/user'; @@ -94,16 +157,13 @@ export class UserApi { var requestOptions: request.Options = { method: 'POST', qs: queryParameters, + headers: headerParams, uri: path, json: true, body: body, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -142,16 +202,13 @@ export class UserApi { var requestOptions: request.Options = { method: 'POST', qs: queryParameters, + headers: headerParams, uri: path, json: true, body: body, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -190,16 +247,13 @@ export class UserApi { var requestOptions: request.Options = { method: 'POST', qs: queryParameters, + headers: headerParams, uri: path, json: true, body: body, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -246,15 +300,12 @@ export class UserApi { var requestOptions: request.Options = { method: 'GET', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -293,15 +344,12 @@ export class UserApi { var requestOptions: request.Options = { method: 'GET', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -347,15 +395,12 @@ export class UserApi { var requestOptions: request.Options = { method: 'GET', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -401,16 +446,13 @@ export class UserApi { var requestOptions: request.Options = { method: 'PUT', qs: queryParameters, + headers: headerParams, uri: path, json: true, body: body, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -456,15 +498,12 @@ export class UserApi { var requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -491,13 +530,30 @@ export class UserApi { } export class PetApi { private basePath = '/v2'; + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } } } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { var path = this.url + this.basePath + '/pet'; @@ -512,16 +568,15 @@ export class PetApi { var requestOptions: request.Options = { method: 'PUT', qs: queryParameters, + headers: headerParams, uri: path, json: true, body: body, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -560,16 +615,15 @@ export class PetApi { var requestOptions: request.Options = { method: 'POST', qs: queryParameters, + headers: headerParams, uri: path, json: true, body: body, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -612,15 +666,14 @@ export class PetApi { var requestOptions: request.Options = { method: 'GET', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -663,15 +716,14 @@ export class PetApi { var requestOptions: request.Options = { method: 'GET', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -717,15 +769,16 @@ export class PetApi { var requestOptions: request.Options = { method: 'GET', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.api_key.applyToRequest(requestOptions); + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -779,15 +832,14 @@ export class PetApi { var requestOptions: request.Options = { method: 'POST', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -835,15 +887,14 @@ export class PetApi { var requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -898,15 +949,14 @@ export class PetApi { var requestOptions: request.Options = { method: 'POST', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -933,13 +983,30 @@ export class PetApi { } export class StoreApi { private basePath = '/v2'; + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } } } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { var path = this.url + this.basePath + '/store/inventory'; @@ -954,15 +1021,14 @@ export class StoreApi { var requestOptions: request.Options = { method: 'GET', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.api_key.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -1001,16 +1067,13 @@ export class StoreApi { var requestOptions: request.Options = { method: 'POST', qs: queryParameters, + headers: headerParams, uri: path, json: true, body: body, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -1056,15 +1119,12 @@ export class StoreApi { var requestOptions: request.Options = { method: 'GET', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { @@ -1110,15 +1170,12 @@ export class StoreApi { var requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, + headers: headerParams, uri: path, json: true, } - if (this.username !== undefined) { - requestOptions.auth = { - username: this.username, password: this.password - } - } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { if (useFormData) { diff --git a/samples/client/petstore/typescript-node/client.ts b/samples/client/petstore/typescript-node/client.ts index 3bab396a7d1..111c76f03c7 100644 --- a/samples/client/petstore/typescript-node/client.ts +++ b/samples/client/petstore/typescript-node/client.ts @@ -1,13 +1,16 @@ import api = require('./api'); import fs = require('fs'); -var petApi = new api.PetApi('http://petstore.swagger.io', undefined, undefined); +var petApi = new api.PetApi('http://petstore.swagger.io'); +petApi.apiKey = 'special-key'; var pet = new api.Pet(); pet.name = 'TypeScriptDoggie'; var petId: any; +var exitCode = 0; + // Test various API calls to the petstore petApi.addPet(pet) .then((res) => { @@ -37,10 +40,12 @@ petApi.addPet(pet) }) .catch((err:any) => { console.error(err); + exitCode = 1; }) .finally(() => { return petApi.deletePet(petId); }) .then((res) => { console.log('Deleted pet'); + process.exit(exitCode); }); diff --git a/samples/client/petstore/typescript-node/tsconfig.json b/samples/client/petstore/typescript-node/tsconfig.json index de28deb89cc..572228f6356 100644 --- a/samples/client/petstore/typescript-node/tsconfig.json +++ b/samples/client/petstore/typescript-node/tsconfig.json @@ -1,7 +1,8 @@ { "compilerOptions": { "module": "commonjs", - "noImplicitAny": true + "noImplicitAny": true, + "target": "ES5" }, "files": [ "api.ts", From 09ccf12a3b00b924a7deb572382e599f55896d82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Mon, 27 Jul 2015 10:19:12 +0200 Subject: [PATCH 31/33] Update Typescript node samples --- samples/client/petstore/typescript-node/api.ts | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index a382508dc28..0b7089fdaae 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -121,8 +121,8 @@ export class UserApi { private basePath = '/v2'; public authentications = { 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), - 'petstore_auth': new OAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), } constructor(url: string, basePath?: string); @@ -138,7 +138,6 @@ export class UserApi { } } - set apiKey(key: string) { this.authentications.api_key.apiKey = key; } @@ -532,8 +531,8 @@ export class PetApi { private basePath = '/v2'; public authentications = { 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), - 'petstore_auth': new OAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), } constructor(url: string, basePath?: string); @@ -549,7 +548,6 @@ export class PetApi { } } - set apiKey(key: string) { this.authentications.api_key.apiKey = key; } @@ -985,8 +983,8 @@ export class StoreApi { private basePath = '/v2'; public authentications = { 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), - 'petstore_auth': new OAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), } constructor(url: string, basePath?: string); @@ -1002,7 +1000,6 @@ export class StoreApi { } } - set apiKey(key: string) { this.authentications.api_key.apiKey = key; } From 64f2e85608d4c55b49abc29f493f7c98c64667d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Mon, 27 Jul 2015 10:20:55 +0200 Subject: [PATCH 32/33] Update TypeScript angular sample --- samples/client/petstore/typescript-angular/API/Client/PetApi.ts | 2 +- .../client/petstore/typescript-angular/API/Client/StoreApi.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index d3052eec52f..6bb4e10d387 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -231,7 +231,7 @@ module API.Client { return this.$http(httpRequestParams); } - public uploadFile (petId: number, additionalMetadata?: string, file?: file, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet/{petId}/uploadImage'; path = path.replace('{' + 'petId' + '}', String(petId)); diff --git a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index f796cef4b94..948b6859381 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -16,7 +16,7 @@ module API.Client { } } - public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise> { + public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise<{ [key: string]: number; }> { var path = this.basePath + '/store/inventory'; var queryParameters: any = {}; From d0a3def4417c6eefd66f1d1c101ccbf68b9b5748 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20M=C3=A6tzke=20Tandrup?= Date: Mon, 27 Jul 2015 11:02:38 +0200 Subject: [PATCH 33/33] Adding `npm run clean` command to clean the sample dir --- samples/client/petstore/typescript-angular/README.md | 5 +++++ samples/client/petstore/typescript-angular/package.json | 5 +++-- samples/client/petstore/typescript-node/README.md | 6 ++++++ samples/client/petstore/typescript-node/package.json | 5 +++-- 4 files changed, 17 insertions(+), 4 deletions(-) diff --git a/samples/client/petstore/typescript-angular/README.md b/samples/client/petstore/typescript-angular/README.md index ba2e8d1ef85..3a4e49be9e8 100644 --- a/samples/client/petstore/typescript-angular/README.md +++ b/samples/client/petstore/typescript-angular/README.md @@ -9,6 +9,11 @@ npm install npm test ``` +To clean the workspace run: +``` +npm run clean +``` + ## Author mads@maetzke-tandrup.dk \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/package.json b/samples/client/petstore/typescript-angular/package.json index 1d5568b1db5..f50b782c09f 100644 --- a/samples/client/petstore/typescript-angular/package.json +++ b/samples/client/petstore/typescript-angular/package.json @@ -4,8 +4,9 @@ "description": "Sample of generated TypeScript petstore client", "main": "api.js", "scripts": { - "postinstall": "tsd reinstall", - "test": "tsc" + "postinstall": "tsd reinstall --overwrite", + "test": "tsc", + "clean": "rm -Rf node_modules/ typings/ *.js" }, "author": "Mads M. Tandrup", "license": "Apache 2.0", diff --git a/samples/client/petstore/typescript-node/README.md b/samples/client/petstore/typescript-node/README.md index 10cd4ff7661..82225d3260a 100644 --- a/samples/client/petstore/typescript-node/README.md +++ b/samples/client/petstore/typescript-node/README.md @@ -11,6 +11,12 @@ npm test This will compile the code and run a small test application that will do some simple test calls to the Swagger Petstore API. +To clean the workspace run: +``` +npm run clean +``` + + ## Author mads@maetzke-tandrup.dk \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/package.json b/samples/client/petstore/typescript-node/package.json index 8cca4d04841..ee598dcc6c2 100644 --- a/samples/client/petstore/typescript-node/package.json +++ b/samples/client/petstore/typescript-node/package.json @@ -4,8 +4,9 @@ "description": "Sample of generated TypeScript petstore client", "main": "api.js", "scripts": { - "postinstall": "tsd reinstall", - "test": "tsc && node client.js" + "postinstall": "tsd reinstall --overwrite", + "test": "tsc && node client.js", + "clean": "rm -Rf node_modules/ typings/ *.js" }, "author": "Mads M. Tandrup", "license": "Apache 2.0",