Merge pull request #866 from geekerzp/develop_2.0_objc_deserialize_map

[Objc] bug fix for map response
This commit is contained in:
Tony Tam 2015-06-22 16:53:28 -07:00
commit d1153dfeb4
30 changed files with 1275 additions and 1471 deletions

View File

@ -143,8 +143,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("SWGObject.m", sourceFolder, "SWGObject.m"));
supportingFiles.add(new SupportingFile("SWGQueryParamCollection.h", sourceFolder, "SWGQueryParamCollection.h"));
supportingFiles.add(new SupportingFile("SWGQueryParamCollection.m", sourceFolder, "SWGQueryParamCollection.m"));
supportingFiles.add(new SupportingFile("SWGApiClient.h", sourceFolder, "SWGApiClient.h"));
supportingFiles.add(new SupportingFile("SWGApiClient.m", sourceFolder, "SWGApiClient.m"));
supportingFiles.add(new SupportingFile("SWGApiClient-header.mustache", sourceFolder, "SWGApiClient.h"));
supportingFiles.add(new SupportingFile("SWGApiClient-body.mustache", sourceFolder, "SWGApiClient.m"));
supportingFiles.add(new SupportingFile("SWGJSONResponseSerializer-header.mustache", sourceFolder, "SWGJSONResponseSerializer.h"));
supportingFiles.add(new SupportingFile("SWGJSONResponseSerializer-body.mustache", sourceFolder, "SWGJSONResponseSerializer.m"));
supportingFiles.add(new SupportingFile("SWGFile.h", sourceFolder, "SWGFile.h"));
supportingFiles.add(new SupportingFile("SWGFile.m", sourceFolder, "SWGFile.m"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", sourceFolder, "JSONValueTransformer+ISO8601.m"));
@ -215,6 +217,16 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
}
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
String innerTypeDeclaration = getTypeDeclaration(inner);
if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
}
return getSwaggerType(p) + "* /* NSString, " + innerTypeDeclaration + " */";
} else {
String swaggerType = getSwaggerType(p);

View File

@ -351,179 +351,139 @@ static bool loggingEnabled = true;
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
}
#pragma mark - Perform Request Methods
#pragma mark - Deserialize methods
-(NSNumber*) dictionary: (NSString*) path
method: (NSString*) method
queryParams: (NSDictionary*) queryParams
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock {
// setting request serializer
if ([requestContentType isEqualToString:@"application/json"]) {
self.requestSerializer = [AFJSONRequestSerializer serializer];
}
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
}
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
}
else {
NSAssert(false, @"unsupport request type %@", requestContentType);
- (id) deserialize:(id) data class:(NSString *) class {
NSRegularExpression *regexp = nil;
NSTextCheckingResult *match = nil;
NSMutableArray *resultArray = nil;
NSMutableDictionary *resultDict = nil;
// return nil if data is nil
if (!data) {
return nil;
}
// setting response serializer
if ([responseContentType isEqualToString:@"application/json"]) {
self.responseSerializer = [AFJSONResponseSerializer serializer];
// remove "*" from class, if ends with "*"
if ([class hasSuffix:@"*"]) {
class = [class substringToIndex:[class length] - 1];
}
else {
self.responseSerializer = [AFHTTPResponseSerializer serializer];
// pure object
if ([class isEqualToString:@"NSObject"]) {
return [[NSObject alloc] init];
}
// list of models
NSString *arrayOfModelsPat = @"NSArray<(.+)>";
regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat
options:NSRegularExpressionCaseInsensitive
error:nil];
match = [regexp firstMatchInString:class
options:0
range:NSMakeRange(0, [class length])];
if (match) {
NSString *innerType = [class substringWithRange:[match rangeAtIndex:1]];
resultArray = [NSMutableArray arrayWithCapacity:[data count]];
[data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[resultArray addObject:[self deserialize:obj class:innerType]];
}
];
return resultArray;
}
// list of primitives
NSString *arrayOfPrimitivesPet = @"NSArray";
regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPet
options:NSRegularExpressionCaseInsensitive
error:nil];
match = [regexp firstMatchInString:class
options:0
range:NSMakeRange(0, [class length])];
if (match) {
resultArray = [NSMutableArray arrayWithCapacity:[data count]];
[data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[resultArray addObject:[self deserialize:obj class:NSStringFromClass([obj class])]];
}];
return resultArray;
}
// map
NSString *dictPat = @"NSDictionary\\* /\\* (.+), (.+) \\*/";
regexp = [NSRegularExpression regularExpressionWithPattern:dictPat
options:NSRegularExpressionCaseInsensitive
error:nil];
match = [regexp firstMatchInString:class
options:0
range:NSMakeRange(0, [class length])];
if (match) {
NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]];
resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]];
[data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[resultDict setValue:[self deserialize:obj class:valueType] forKey:key];
}];
return resultDict;
}
// auth setting
[self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings];
// primitives
NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"BOOL", @"NSNumber"];
NSMutableURLRequest * request = nil;
if (body != nil && [body isKindOfClass:[NSArray class]]){
SWGFile * file;
NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
for(id obj in body) {
if([obj isKindOfClass:[SWGFile class]]) {
file = (SWGFile*) obj;
requestContentType = @"multipart/form-data";
if ([primitiveTypes containsObject:class]) {
if ([class isEqualToString:@"NSString"]) {
return [NSString stringWithString:data];
}
else if ([class isEqualToString:@"NSDate"]) {
return [NSDate dateWithISO8601String:data];
}
else if ([class isEqualToString:@"BOOL"]) {
// Returns YES on encountering one of "Y", "y", "T", "t", or a
// digit 1-9—the method ignores any trailing characters
// NSString => BOOL => NSNumber
return [NSNumber numberWithBool:[data boolValue]];
}
else if ([class isEqualToString:@"NSNumber"]) {
// NSNumber from NSNumber
if ([data isKindOfClass:[NSNumber class]]) {
return data;
}
else if([obj isKindOfClass:[NSDictionary class]]) {
for(NSString * key in obj) {
params[key] = obj[key];
}
// NSNumber from NSString
else {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
return [formatter numberFromString:data];
}
}
NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString];
// request with multipart form
if([requestContentType isEqualToString:@"multipart/form-data"]) {
request = [self.requestSerializer multipartFormRequestWithMethod: @"POST"
URLString: urlString
parameters: nil
constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) {
for(NSString * key in params) {
NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData: data name: key];
}
if (file) {
[formData appendPartWithFileData: [file data]
name: [file paramName]
fileName: [file name]
mimeType: [file mimeType]];
}
}
error:nil];
}
// request with form parameters or json
else {
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams];
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:params
error:nil];
}
}
else {
NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams];
NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:body
error:nil];
}
BOOL hasHeaderParams = false;
if(headerParams != nil && [headerParams count] > 0)
hasHeaderParams = true;
if(offlineState) {
NSLog(@"%@ cache forced", path);
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
}
else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) {
NSLog(@"%@ cache enabled", path);
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
}
else {
NSLog(@"%@ cache disabled", path);
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
// model
Class ModelClass = NSClassFromString(class);
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
return [[ModelClass alloc] initWithDictionary:data error:nil];
}
if(body != nil) {
if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){
[self.requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"];
}
else if ([body isKindOfClass:[SWGFile class]]) {}
else {
NSAssert(false, @"unsupported post type!");
}
}
if(headerParams != nil){
for(NSString * key in [headerParams keyEnumerator]){
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
}
}
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
// Always disable cookies!
[request setHTTPShouldHandleCookies:NO];
if (self.logRequests) {
[self logRequest:request];
}
NSNumber* requestId = [SWGApiClient queueRequest];
AFHTTPRequestOperation *op =
[self HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id JSON) {
if([self executeRequestWithId:requestId]) {
if(self.logServerResponses)
[self logResponse:JSON forRequest:request error:nil];
completionBlock(JSON, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([self executeRequestWithId:requestId]) {
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if(operation.responseObject) {
// Add in the (parsed) response body.
userInfo[SWGResponseObjectErrorKey] = operation.responseObject;
}
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
if(self.logServerResponses)
[self logResponse:nil forRequest:request error:augmentedError];
completionBlock(nil, augmentedError);
}
}
];
[self.operationQueue addOperation:op];
return requestId;
return nil;
}
-(NSNumber*) stringWithCompletionBlock: (NSString*) path
method: (NSString*) method
queryParams: (NSDictionary*) queryParams
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
completionBlock: (void (^)(NSString*, NSError *))completionBlock {
#pragma mark - Perform Request Methods
-(NSNumber*) requestWithCompletionBlock: (NSString*) path
method: (NSString*) method
queryParams: (NSDictionary*) queryParams
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
completionBlock: (void (^)(id, NSError *))completionBlock {
// setting request serializer
if ([requestContentType isEqualToString:@"application/json"]) {
self.requestSerializer = [AFJSONRequestSerializer serializer];
@ -540,7 +500,7 @@ static bool loggingEnabled = true;
// setting response serializer
if ([responseContentType isEqualToString:@"application/json"]) {
self.responseSerializer = [AFJSONResponseSerializer serializer];
self.responseSerializer = [SWGJSONResponseSerializer serializer];
}
else {
self.responseSerializer = [AFHTTPResponseSerializer serializer];
@ -648,11 +608,11 @@ static bool loggingEnabled = true;
NSNumber* requestId = [SWGApiClient queueRequest];
AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
success:^(AFHTTPRequestOperation *operation, id response) {
if([self executeRequestWithId:requestId]) {
if(self.logServerResponses)
[self logResponse:responseObject forRequest:request error:nil];
if(self.logServerResponses) {
[self logResponse:response forRequest:request error:nil];
}
completionBlock(response, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
@ -683,3 +643,4 @@ static bool loggingEnabled = true;

View File

@ -1,5 +1,10 @@
#import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import "AFHTTPRequestOperationManager.h"
#import "SWGJSONResponseSerializer.h"
{{#models}}{{#model}}#import "{{classname}}.h"
{{/model}}{{/models}}
/**
* A key for `NSError` user info dictionaries.
@ -159,37 +164,16 @@ extern NSString *const SWGResponseObjectErrorKey;
WithAuthSettings:(NSArray *)authSettings;
/**
* Perform request
* Deserialize the given data to Objective-C object.
*
* Request with non-empty response
*
* @param path Request url.
* @param method Request method.
* @param queryParams Request query parameters.
* @param body Request body.
* @param headerParams Request header parameters.
* @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.
*
* @return The request id.
* @param data The data will be deserialized.
* @param class The type of objective-c object.
*/
-(NSNumber*) dictionary:(NSString*) path
method:(NSString*) method
queryParams:(NSDictionary*) queryParams
body:(id) body
headerParams:(NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock;
- (id) deserialize:(id) data class:(NSString *) class;
/**
* Perform request
*
* Request with empty response
*
* @param path Request url.
* @param method Request method.
* @param queryParams Request query parameters.
@ -202,15 +186,18 @@ extern NSString *const SWGResponseObjectErrorKey;
*
* @return The request id.
*/
-(NSNumber*) stringWithCompletionBlock:(NSString*) path
method:(NSString*) method
queryParams:(NSDictionary*) queryParams
body:(id) body
headerParams:(NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
completionBlock:(void (^)(NSString*, NSError *))completionBlock;
-(NSNumber*) requestWithCompletionBlock:(NSString*) path
method:(NSString*) method
queryParams:(NSDictionary*) queryParams
body:(id) body
headerParams:(NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
completionBlock:(void (^)(id, NSError *))completionBlock;
@end

View File

@ -0,0 +1,39 @@
#import "SWGJSONResponseSerializer.h"
static BOOL JSONParseError(NSError *error) {
if ([error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840) {
return YES;
}
return NO;
}
@implementation SWGJSONResponseSerializer
///
/// When customize a response serializer,
/// the serializer must conform the protocol `AFURLResponseSerialization`
/// and implements the protocol method `responseObjectForResponse:error:`
///
/// @param response The response to be processed.
/// @param data The response data to be decoded.
/// @param error The error that occurred while attempting to decode the respnse data.
///
/// @return The object decoded from the specified response data.
///
- (id) responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error {
NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error];
// if response data is not a valid json, return string of data.
if (JSONParseError(*error)) {
*error = nil;
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return responseString;
}
return responseJson;
}
@end

View File

@ -0,0 +1,6 @@
#import <Foundation/Foundation.h>
#import <AFNetworking/AFURLResponseSerialization.h>
@interface SWGJSONResponseSerializer : AFJSONResponseSerializer
@end

View File

@ -72,14 +72,16 @@ static NSString * basePath = @"{{basePath}}";
return [SWGApiClient requestQueueSize];
}
#pragma mark - Api Methods
{{#operation}}
/*!
* {{{summary}}}
* {{{notes}}}
{{#allParams}} * \param {{paramName}} {{{description}}}
{{/allParams}} * \returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
///
/// {{{summary}}}
/// {{{notes}}}
/// {{#allParams}} @param {{paramName}} {{{description}}}
///
/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
///
-(NSNumber*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}
{{/allParams}}
{{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock{{/returnBaseType}}
@ -195,27 +197,19 @@ static NSString * basePath = @"{{basePath}}";
}
{{/requiredParams}}
{{/requiredParamCount}}
{{#returnContainer}}
// response is in a container
{{>apiBodyResponseWithContainer}}{{/returnContainer}}
{{#returnSimpleType}}
// non container response
{{#returnTypeIsPrimitive}}
// primitive response
{{>apiPrimitiveResponse}}{{/returnTypeIsPrimitive}}
{{#returnBaseType}}
// complex response
{{>apiNonPrimitiveResponse}}{{/returnBaseType}}
{{/returnSimpleType}}
{{^returnSimpleType}}{{^returnContainer}}
// it's void
{{>voidResponse}}
{{/returnContainer}}{{/returnSimpleType}}
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"{{httpMethod}}"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
{{^returnType}}completionBlock(error);{{/returnType}}
{{#returnType}}completionBlock([self.apiClient deserialize: data class:@"{{{returnType}}}"], error);{{/returnType}}
}
];
}
{{/operation}}

View File

@ -17,16 +17,15 @@
+(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath;
{{#operation}}
/**
{{{summary}}}
{{#notes}}{{{notes}}}{{/notes}}
{{#allParams}}@param {{paramName}} {{description}}
{{/allParams}}
return type: {{{returnType}}}
*/
///
///
/// {{{summary}}}
/// {{#notes}}{{{notes}}}{{/notes}}
///
/// {{#allParams}}@param {{paramName}} {{description}}
/// {{/allParams}}
///
/// @return {{{returnType}}}
-(NSNumber*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}}
{{/hasMore}}{{/allParams}}
{{#returnBaseType}}{{#hasParams}}

View File

@ -1,38 +0,0 @@
// {{returnContainer}} container response type
return [self.apiClient dictionary: requestUrl
method: @"{{httpMethod}}"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
{{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}}{{^returnBaseType}}completionBlock(error);{{/returnBaseType}}
return;
}
{{#isMapContainer}}
NSDictionary *result = nil;
if (data) {
result = [[NSDictionary alloc]initWithDictionary: data];
}
completionBlock(data, nil);
{{/isMapContainer}}{{#isListContainer}}
{{#returnBaseType}}if([data isKindOfClass:[NSArray class]]){
NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]];
for (NSDictionary* dict in (NSArray*)data) {
{{#returnTypeIsPrimitive}}
{{returnBaseType}}* d = [[{{{returnBaseType}}} alloc]initWithString: dict];
{{/returnTypeIsPrimitive}}
{{^returnTypeIsPrimitive}}
{{{returnBaseType}}}* d = [[{{{returnBaseType}}} alloc] initWithDictionary:dict error:nil];
{{/returnTypeIsPrimitive}}
[objs addObject:d];
}
completionBlock(({{{returnType}}})objs, nil);
}
{{/returnBaseType}}
{{/isListContainer}}
}];

View File

@ -1,24 +0,0 @@
{{^returnTypeIsPrimitive}}
// comples response type
return [self.apiClient dictionary: requestUrl
method: @"{{httpMethod}}"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
{{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}}
{{^returnBaseType}}completionBlock(error);{{/returnBaseType}}
return;
}
{{#returnType}}{{returnType}} result = nil;
if (data) {
result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc] {{#returnContainer}}{{#isMapContainer}}initWithDictionary{{/isMapContainer}}{{#isListContainer}} initWithDictionary{{/isListContainer}}{{/returnContainer}}{{^returnContainer}} initWithDictionary{{/returnContainer}}:data error:nil];
}
{{#returnType}}completionBlock(result , nil);{{/returnType}}
{{/returnType}}
}];
{{/returnTypeIsPrimitive}}

View File

@ -1,36 +0,0 @@
// primitive response type
{{#returnBaseType}}return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"{{httpMethod}}"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
{{returnBaseType}} *result = data ? [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data] : nil;
completionBlock(result, nil);
}];
{{/returnBaseType}}
{{^returnBaseType}}
// no return base type
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"{{httpMethod}}"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
{{/returnBaseType}}

View File

@ -1,15 +0,0 @@
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"{{httpMethod}}"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];

View File

@ -118,7 +118,7 @@ class ObjcModelTest extends FlatSpec with Matchers {
val vars = cm.vars
vars.get(0).baseName should be("translations")
vars.get(0).datatype should be("NSDictionary*")
vars.get(0).datatype should be("NSDictionary* /* NSString, NSString */")
vars.get(0).name should be("translations")
vars.get(0).baseType should be("NSDictionary")
vars.get(0).containerType should be("map")
@ -192,7 +192,7 @@ class ObjcModelTest extends FlatSpec with Matchers {
val vars = cm.vars
vars.get(0).baseName should be("children")
vars.get(0).complexType should be("SWGChildren")
vars.get(0).datatype should be("NSDictionary*")
vars.get(0).datatype should be("NSDictionary* /* NSString, SWGChildren */")
vars.get(0).name should be("children")
vars.get(0).baseType should be("NSDictionary")
vars.get(0).containerType should be("map")

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDESourceControlProjectFavoriteDictionaryKey</key>
<false/>
<key>IDESourceControlProjectIdentifier</key>
<string>15AAFA18-9D61-437F-988D-A691BA4C08B1</string>
<key>IDESourceControlProjectName</key>
<string>SwaggerClient</string>
<key>IDESourceControlProjectOriginsDictionary</key>
<dict>
<key>E5BBF0AA85077C865C95437976D06D819733A208</key>
<string>https://github.com/geekerzp/swagger-codegen.git</string>
</dict>
<key>IDESourceControlProjectPath</key>
<string>samples/client/petstore/objc/SwaggerClient.xcworkspace</string>
<key>IDESourceControlProjectRelativeInstallPathDictionary</key>
<dict>
<key>E5BBF0AA85077C865C95437976D06D819733A208</key>
<string>../../../../..</string>
</dict>
<key>IDESourceControlProjectURL</key>
<string>https://github.com/geekerzp/swagger-codegen.git</string>
<key>IDESourceControlProjectVersion</key>
<integer>111</integer>
<key>IDESourceControlProjectWCCIdentifier</key>
<string>E5BBF0AA85077C865C95437976D06D819733A208</string>
<key>IDESourceControlProjectWCConfigurations</key>
<array>
<dict>
<key>IDESourceControlRepositoryExtensionIdentifierKey</key>
<string>public.vcs.git</string>
<key>IDESourceControlWCCIdentifierKey</key>
<string>E5BBF0AA85077C865C95437976D06D819733A208</string>
<key>IDESourceControlWCCName</key>
<string>swagger-codegen</string>
</dict>
</array>
</dict>
</plist>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
type = "0"
version = "2.0">
<Breakpoints>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.ExceptionBreakpoint">
<BreakpointContent
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
scope = "0"
stopOnStyle = "0">
</BreakpointContent>
</BreakpointProxy>
</Breakpoints>
</Bucket>

View File

@ -10,6 +10,9 @@
BA525648922D4C0E9F44D4F1 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 73DA4F1067C343C3962F1542 /* libPods.a */; };
CF0560EB1B1855CF00C0D4EC /* SWGConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = CF0560EA1B1855CF00C0D4EC /* SWGConfiguration.m */; };
CF31D0991B105E4B00509935 /* SWGApiClientTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF31D0981B105E4B00509935 /* SWGApiClientTest.m */; };
CF5B6E2D1B2BD70800862A1C /* UserApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF5B6E2C1B2BD70800862A1C /* UserApiTest.m */; };
CFB37D061B2B11DD00D2E5F1 /* StoreApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CFB37D051B2B11DC00D2E5F1 /* StoreApiTest.m */; };
CFCEFE511B2C1330006313BE /* SWGJSONResponseSerializer.m in Sources */ = {isa = PBXBuildFile; fileRef = CFCEFE501B2C1330006313BE /* SWGJSONResponseSerializer.m */; };
CFD1B6701B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */; };
CFD1B6711B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */; };
EA66999A1811D2FA00A70D03 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA6699991811D2FA00A70D03 /* Foundation.framework */; };
@ -60,6 +63,10 @@
CF0560E91B1855CF00C0D4EC /* SWGConfiguration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGConfiguration.h; sourceTree = "<group>"; };
CF0560EA1B1855CF00C0D4EC /* SWGConfiguration.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGConfiguration.m; sourceTree = "<group>"; };
CF31D0981B105E4B00509935 /* SWGApiClientTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiClientTest.m; sourceTree = "<group>"; };
CF5B6E2C1B2BD70800862A1C /* UserApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = UserApiTest.m; sourceTree = "<group>"; };
CFB37D051B2B11DC00D2E5F1 /* StoreApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = StoreApiTest.m; sourceTree = "<group>"; };
CFCEFE4F1B2C1330006313BE /* SWGJSONResponseSerializer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGJSONResponseSerializer.h; sourceTree = "<group>"; };
CFCEFE501B2C1330006313BE /* SWGJSONResponseSerializer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGJSONResponseSerializer.m; sourceTree = "<group>"; };
CFD1B66E1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "JSONValueTransformer+ISO8601.h"; sourceTree = "<group>"; };
CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "JSONValueTransformer+ISO8601.m"; sourceTree = "<group>"; };
E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = "<group>"; };
@ -212,6 +219,8 @@
isa = PBXGroup;
children = (
EA8CD3EB1AC274BE00C47D0B /* PetApiTest.h */,
CF5B6E2C1B2BD70800862A1C /* UserApiTest.m */,
CFB37D051B2B11DC00D2E5F1 /* StoreApiTest.m */,
CF31D0981B105E4B00509935 /* SWGApiClientTest.m */,
EA6699C71811D2FB00A70D03 /* PetApiTest.m */,
EA6699C21811D2FB00A70D03 /* Supporting Files */,
@ -248,6 +257,8 @@
EAEA85D61811D3AE00F06E69 /* SWGOrder.h */,
EAEA85D71811D3AE00F06E69 /* SWGOrder.m */,
EAB26B0E1AC8E692002F5C7A /* SWGPet.h */,
CFCEFE4F1B2C1330006313BE /* SWGJSONResponseSerializer.h */,
CFCEFE501B2C1330006313BE /* SWGJSONResponseSerializer.m */,
EAEA85D91811D3AE00F06E69 /* SWGPet.m */,
EAEA85DA1811D3AE00F06E69 /* SWGPetApi.h */,
EAEA85DB1811D3AE00F06E69 /* SWGPetApi.m */,
@ -415,6 +426,7 @@
EAEA85E91811D3AE00F06E69 /* SWGOrder.m in Sources */,
EAEA85E81811D3AE00F06E69 /* SWGObject.m in Sources */,
EA8B8AA41AC6683700638FBB /* SWGQueryParamCollection.m in Sources */,
CFCEFE511B2C1330006313BE /* SWGJSONResponseSerializer.m in Sources */,
EAEA85E71811D3AE00F06E69 /* SWGFile.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@ -426,6 +438,8 @@
EAB26B0C1AC8DF78002F5C7A /* PetApiTest.h in Sources */,
CFD1B6711B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */,
EAB26B0D1AC8DF78002F5C7A /* PetApiTest.m in Sources */,
CF5B6E2D1B2BD70800862A1C /* UserApiTest.m in Sources */,
CFB37D061B2B11DD00D2E5F1 /* StoreApiTest.m in Sources */,
CF31D0991B105E4B00509935 /* SWGApiClientTest.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;

View File

@ -8,6 +8,8 @@
#import "ViewController.h"
#import "SWGPetApi.h"
#import "SWGStoreApi.h"
#import "SWGUserApi.h"
#import "SWGConfiguration.h"
@interface ViewController ()
@ -54,14 +56,14 @@
// }
];
*/
SWGConfiguration *config = [SWGConfiguration sharedConfig];
config.username = @"foo";
config.password = @"bar";
SWGPetApi *api = [[SWGPetApi alloc] init];
[api addPetWithCompletionBlock:nil
completionHandler:^(NSError *error) {
}];
[api deletePetWithCompletionBlock:@"hello"
petId:@1434529787992
completionHandler:^(NSError *error) {
if (error) {
NSLog(@"%@", error);
}
}];
}
- (void)didReceiveMemoryWarning

View File

@ -98,4 +98,77 @@
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<SWGPet>*"];
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

View File

@ -0,0 +1,44 @@
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import "SWGStoreApi.h"
@interface StoreApiTest : XCTestCase
@property (nonatomic) SWGStoreApi *api;
@end
@implementation StoreApiTest
- (void)setUp {
[super setUp];
self.api = [[SWGStoreApi alloc] init];
}
- (void)tearDown {
[super tearDown];
}
- (void)testGetInventory {
XCTestExpectation *expectation = [self expectationWithDescription:@"testGetPetByStatus"];
[self.api getInventoryWithCompletionBlock:^(NSDictionary *output, NSError *error) {
if (error) {
XCTFail(@"got error %@", error);
}
if (!output) {
XCTFail(@"failed to fetch inventory");
}
XCTAssertNotNil(output.allKeys);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:10.0 handler:nil];
}
@end

View File

@ -0,0 +1,47 @@
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import "SWGUserApi.h"
@interface UserApiTest : XCTestCase
@property (nonatomic) SWGUserApi *api;
@end
@implementation UserApiTest
- (void)setUp {
[super setUp];
self.api = [[SWGUserApi alloc] init];
}
- (void)tearDown {
[super tearDown];
}
- (void)testLoginUser {
XCTestExpectation *expectation = [self expectationWithDescription:@"test login user"];
[self.api loginUserWithCompletionBlock:@"test username" password:@"test password" completionHandler:^(NSString *output, NSError *error) {
if (error) {
XCTFail(@"got error %@", error);
}
if (!output) {
XCTFail(@"response can't be nil");
}
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"logged in user"
options:0
error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:output
options:0
range:NSMakeRange(0, [output length])];
XCTAssertNotNil(match);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:10.0 handler:nil];
}
@end

View File

@ -1,5 +1,14 @@
#import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import "AFHTTPRequestOperationManager.h"
#import "SWGJSONResponseSerializer.h"
#import "SWGUser.h"
#import "SWGCategory.h"
#import "SWGPet.h"
#import "SWGTag.h"
#import "SWGOrder.h"
/**
* A key for `NSError` user info dictionaries.
@ -159,37 +168,16 @@ extern NSString *const SWGResponseObjectErrorKey;
WithAuthSettings:(NSArray *)authSettings;
/**
* Perform request
* Deserialize the given data to Objective-C object.
*
* Request with non-empty response
*
* @param path Request url.
* @param method Request method.
* @param queryParams Request query parameters.
* @param body Request body.
* @param headerParams Request header parameters.
* @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.
*
* @return The request id.
* @param data The data will be deserialized.
* @param class The type of objective-c object.
*/
-(NSNumber*) dictionary:(NSString*) path
method:(NSString*) method
queryParams:(NSDictionary*) queryParams
body:(id) body
headerParams:(NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock;
- (id) deserialize:(id) data class:(NSString *) class;
/**
* Perform request
*
* Request with empty response
*
* @param path Request url.
* @param method Request method.
* @param queryParams Request query parameters.
@ -202,15 +190,18 @@ extern NSString *const SWGResponseObjectErrorKey;
*
* @return The request id.
*/
-(NSNumber*) stringWithCompletionBlock:(NSString*) path
method:(NSString*) method
queryParams:(NSDictionary*) queryParams
body:(id) body
headerParams:(NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
completionBlock:(void (^)(NSString*, NSError *))completionBlock;
-(NSNumber*) requestWithCompletionBlock:(NSString*) path
method:(NSString*) method
queryParams:(NSDictionary*) queryParams
body:(id) body
headerParams:(NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
completionBlock:(void (^)(id, NSError *))completionBlock;
@end

View File

@ -351,179 +351,139 @@ static bool loggingEnabled = true;
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
}
#pragma mark - Perform Request Methods
#pragma mark - Deserialize methods
-(NSNumber*) dictionary: (NSString*) path
method: (NSString*) method
queryParams: (NSDictionary*) queryParams
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock {
// setting request serializer
if ([requestContentType isEqualToString:@"application/json"]) {
self.requestSerializer = [AFJSONRequestSerializer serializer];
}
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
}
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
}
else {
NSAssert(false, @"unsupport request type %@", requestContentType);
- (id) deserialize:(id) data class:(NSString *) class {
NSRegularExpression *regexp = nil;
NSTextCheckingResult *match = nil;
NSMutableArray *resultArray = nil;
NSMutableDictionary *resultDict = nil;
// return nil if data is nil
if (!data) {
return nil;
}
// setting response serializer
if ([responseContentType isEqualToString:@"application/json"]) {
self.responseSerializer = [AFJSONResponseSerializer serializer];
// remove "*" from class, if ends with "*"
if ([class hasSuffix:@"*"]) {
class = [class substringToIndex:[class length] - 1];
}
else {
self.responseSerializer = [AFHTTPResponseSerializer serializer];
// pure object
if ([class isEqualToString:@"NSObject"]) {
return [[NSObject alloc] init];
}
// list of models
NSString *arrayOfModelsPat = @"NSArray<(.+)>";
regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat
options:NSRegularExpressionCaseInsensitive
error:nil];
match = [regexp firstMatchInString:class
options:0
range:NSMakeRange(0, [class length])];
if (match) {
NSString *innerType = [class substringWithRange:[match rangeAtIndex:1]];
resultArray = [NSMutableArray arrayWithCapacity:[data count]];
[data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[resultArray addObject:[self deserialize:obj class:innerType]];
}
];
return resultArray;
}
// list of primitives
NSString *arrayOfPrimitivesPet = @"NSArray";
regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPet
options:NSRegularExpressionCaseInsensitive
error:nil];
match = [regexp firstMatchInString:class
options:0
range:NSMakeRange(0, [class length])];
if (match) {
resultArray = [NSMutableArray arrayWithCapacity:[data count]];
[data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[resultArray addObject:[self deserialize:obj class:NSStringFromClass([obj class])]];
}];
return resultArray;
}
// map
NSString *dictPat = @"NSDictionary\\* /\\* (.+), (.+) \\*/";
regexp = [NSRegularExpression regularExpressionWithPattern:dictPat
options:NSRegularExpressionCaseInsensitive
error:nil];
match = [regexp firstMatchInString:class
options:0
range:NSMakeRange(0, [class length])];
if (match) {
NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]];
resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]];
[data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[resultDict setValue:[self deserialize:obj class:valueType] forKey:key];
}];
return resultDict;
}
// auth setting
[self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings];
// primitives
NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"BOOL", @"NSNumber"];
NSMutableURLRequest * request = nil;
if (body != nil && [body isKindOfClass:[NSArray class]]){
SWGFile * file;
NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
for(id obj in body) {
if([obj isKindOfClass:[SWGFile class]]) {
file = (SWGFile*) obj;
requestContentType = @"multipart/form-data";
if ([primitiveTypes containsObject:class]) {
if ([class isEqualToString:@"NSString"]) {
return [NSString stringWithString:data];
}
else if ([class isEqualToString:@"NSDate"]) {
return [NSDate dateWithISO8601String:data];
}
else if ([class isEqualToString:@"BOOL"]) {
// Returns YES on encountering one of "Y", "y", "T", "t", or a
// digit 1-9the method ignores any trailing characters
// NSString => BOOL => NSNumber
return [NSNumber numberWithBool:[data boolValue]];
}
else if ([class isEqualToString:@"NSNumber"]) {
// NSNumber from NSNumber
if ([data isKindOfClass:[NSNumber class]]) {
return data;
}
else if([obj isKindOfClass:[NSDictionary class]]) {
for(NSString * key in obj) {
params[key] = obj[key];
}
// NSNumber from NSString
else {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
return [formatter numberFromString:data];
}
}
NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString];
// request with multipart form
if([requestContentType isEqualToString:@"multipart/form-data"]) {
request = [self.requestSerializer multipartFormRequestWithMethod: @"POST"
URLString: urlString
parameters: nil
constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) {
for(NSString * key in params) {
NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData: data name: key];
}
if (file) {
[formData appendPartWithFileData: [file data]
name: [file paramName]
fileName: [file name]
mimeType: [file mimeType]];
}
}
error:nil];
}
// request with form parameters or json
else {
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams];
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:params
error:nil];
}
}
else {
NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams];
NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:body
error:nil];
}
BOOL hasHeaderParams = false;
if(headerParams != nil && [headerParams count] > 0)
hasHeaderParams = true;
if(offlineState) {
NSLog(@"%@ cache forced", path);
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
}
else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) {
NSLog(@"%@ cache enabled", path);
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
}
else {
NSLog(@"%@ cache disabled", path);
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
// model
Class ModelClass = NSClassFromString(class);
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
return [[ModelClass alloc] initWithDictionary:data error:nil];
}
if(body != nil) {
if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){
[self.requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"];
}
else if ([body isKindOfClass:[SWGFile class]]) {}
else {
NSAssert(false, @"unsupported post type!");
}
}
if(headerParams != nil){
for(NSString * key in [headerParams keyEnumerator]){
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
}
}
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
// Always disable cookies!
[request setHTTPShouldHandleCookies:NO];
if (self.logRequests) {
[self logRequest:request];
}
NSNumber* requestId = [SWGApiClient queueRequest];
AFHTTPRequestOperation *op =
[self HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id JSON) {
if([self executeRequestWithId:requestId]) {
if(self.logServerResponses)
[self logResponse:JSON forRequest:request error:nil];
completionBlock(JSON, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([self executeRequestWithId:requestId]) {
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if(operation.responseObject) {
// Add in the (parsed) response body.
userInfo[SWGResponseObjectErrorKey] = operation.responseObject;
}
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
if(self.logServerResponses)
[self logResponse:nil forRequest:request error:augmentedError];
completionBlock(nil, augmentedError);
}
}
];
[self.operationQueue addOperation:op];
return requestId;
return nil;
}
-(NSNumber*) stringWithCompletionBlock: (NSString*) path
method: (NSString*) method
queryParams: (NSDictionary*) queryParams
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
completionBlock: (void (^)(NSString*, NSError *))completionBlock {
#pragma mark - Perform Request Methods
-(NSNumber*) requestWithCompletionBlock: (NSString*) path
method: (NSString*) method
queryParams: (NSDictionary*) queryParams
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
completionBlock: (void (^)(id, NSError *))completionBlock {
// setting request serializer
if ([requestContentType isEqualToString:@"application/json"]) {
self.requestSerializer = [AFJSONRequestSerializer serializer];
@ -540,7 +500,7 @@ static bool loggingEnabled = true;
// setting response serializer
if ([responseContentType isEqualToString:@"application/json"]) {
self.responseSerializer = [AFJSONResponseSerializer serializer];
self.responseSerializer = [SWGJSONResponseSerializer serializer];
}
else {
self.responseSerializer = [AFHTTPResponseSerializer serializer];
@ -648,11 +608,11 @@ static bool loggingEnabled = true;
NSNumber* requestId = [SWGApiClient queueRequest];
AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
success:^(AFHTTPRequestOperation *operation, id response) {
if([self executeRequestWithId:requestId]) {
if(self.logServerResponses)
[self logResponse:responseObject forRequest:request error:nil];
if(self.logServerResponses) {
[self logResponse:response forRequest:request error:nil];
}
completionBlock(response, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
@ -683,3 +643,4 @@ static bool loggingEnabled = true;

View File

@ -0,0 +1,6 @@
#import <Foundation/Foundation.h>
#import <AFNetworking/AFURLResponseSerialization.h>
@interface SWGJSONResponseSerializer : AFJSONResponseSerializer
@end

View File

@ -0,0 +1,39 @@
#import "SWGJSONResponseSerializer.h"
static BOOL JSONParseError(NSError *error) {
if ([error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840) {
return YES;
}
return NO;
}
@implementation SWGJSONResponseSerializer
///
/// When customize a response serializer,
/// the serializer must conform the protocol `AFURLResponseSerialization`
/// and implements the protocol method `responseObjectForResponse:error:`
///
/// @param response The response to be processed.
/// @param data The response data to be decoded.
/// @param error The error that occurred while attempting to decode the respnse data.
///
/// @return The object decoded from the specified response data.
///
- (id) responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error {
NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error];
// if response data is not a valid json, return string of data.
if (JSONParseError(*error)) {
*error = nil;
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return responseString;
}
return responseJson;
}
@end

View File

@ -15,98 +15,92 @@
+(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath;
/**
Update an existing pet
@param body Pet object that needs to be added to the store
return type:
*/
///
///
/// Update an existing pet
///
///
/// @param body Pet object that needs to be added to the store
///
///
/// @return
-(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Add a new pet to the store
@param body Pet object that needs to be added to the store
return type:
*/
///
///
/// Add a new pet to the store
///
///
/// @param body Pet object that needs to be added to the store
///
///
/// @return
-(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Finds Pets by status
Multiple status values can be provided with comma seperated strings
@param status Status values that need to be considered for filter
return type: NSArray<SWGPet>*
*/
///
///
/// Finds Pets by status
/// Multiple status values can be provided with comma seperated strings
///
/// @param status Status values that need to be considered for filter
///
///
/// @return NSArray<SWGPet>*
-(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock;
/**
Finds Pets by tags
Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
@param tags Tags to filter by
return type: NSArray<SWGPet>*
*/
///
///
/// Finds Pets by tags
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
///
/// @param tags Tags to filter by
///
///
/// @return NSArray<SWGPet>*
-(NSNumber*) findPetsByTagsWithCompletionBlock :(NSArray*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock;
/**
Find pet by ID
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
@param petId ID of pet that needs to be fetched
return type: SWGPet*
*/
///
///
/// Find pet by ID
/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
///
/// @param petId ID of pet that needs to be fetched
///
///
/// @return SWGPet*
-(NSNumber*) getPetByIdWithCompletionBlock :(NSNumber*) petId
completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock;
/**
Updates a pet in the store with form data
@param petId ID of pet that needs to be updated
@param name Updated name of the pet
@param status Updated status of the pet
return type:
*/
///
///
/// Updates a pet in the store with form data
///
///
/// @param petId ID of pet that needs to be updated
/// @param name Updated name of the pet
/// @param status Updated status of the pet
///
///
/// @return
-(NSNumber*) updatePetWithFormWithCompletionBlock :(NSString*) petId
name:(NSString*) name
status:(NSString*) status
@ -115,17 +109,16 @@
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Deletes a pet
@param apiKey
@param petId Pet id to delete
return type:
*/
///
///
/// Deletes a pet
///
///
/// @param apiKey
/// @param petId Pet id to delete
///
///
/// @return
-(NSNumber*) deletePetWithCompletionBlock :(NSString*) apiKey
petId:(NSNumber*) petId
@ -133,18 +126,17 @@
completionHandler: (void (^)(NSError* error))completionBlock;
/**
uploads an image
@param petId ID of pet to update
@param additionalMetadata Additional data to pass to server
@param file file to upload
return type:
*/
///
///
/// uploads an image
///
///
/// @param petId ID of pet to update
/// @param additionalMetadata Additional data to pass to server
/// @param file file to upload
///
///
/// @return
-(NSNumber*) uploadFileWithCompletionBlock :(NSNumber*) petId
additionalMetadata:(NSString*) additionalMetadata
file:(SWGFile*) file

View File

@ -71,13 +71,15 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
return [SWGApiClient requestQueueSize];
}
#pragma mark - Api Methods
/*!
* Update an existing pet
*
* \param body Pet object that needs to be added to the store
* \returns void
*/
///
/// Update an existing pet
///
/// @param body Pet object that needs to be added to the store
///
/// @returns void
///
-(NSNumber*) updatePetWithCompletionBlock: (SWGPet*) body
@ -153,38 +155,28 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"PUT"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"PUT"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock(error);
}
];
}
/*!
* Add a new pet to the store
*
* \param body Pet object that needs to be added to the store
* \returns void
*/
///
/// Add a new pet to the store
///
/// @param body Pet object that needs to be added to the store
///
/// @returns void
///
-(NSNumber*) addPetWithCompletionBlock: (SWGPet*) body
@ -260,38 +252,28 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock(error);
}
];
}
/*!
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* \param status Status values that need to be considered for filter
* \returns NSArray<SWGPet>*
*/
///
/// Finds Pets by status
/// Multiple status values can be provided with comma seperated strings
/// @param status Status values that need to be considered for filter
///
/// @returns NSArray<SWGPet>*
///
-(NSNumber*) findPetsByStatusWithCompletionBlock: (NSArray*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock
@ -350,52 +332,28 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// response is in a container
// array container response type
return [self.apiClient dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
if([data isKindOfClass:[NSArray class]]){
NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]];
for (NSDictionary* dict in (NSArray*)data) {
SWGPet* d = [[SWGPet alloc] initWithDictionary:dict error:nil];
[objs addObject:d];
}
completionBlock((NSArray<SWGPet>*)objs, nil);
}
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock([self.apiClient deserialize: data class:@"NSArray<SWGPet>*"], error);
}
];
}
/*!
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* \param tags Tags to filter by
* \returns NSArray<SWGPet>*
*/
///
/// Finds Pets by tags
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
/// @param tags Tags to filter by
///
/// @returns NSArray<SWGPet>*
///
-(NSNumber*) findPetsByTagsWithCompletionBlock: (NSArray*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock
@ -454,52 +412,28 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// response is in a container
// array container response type
return [self.apiClient dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
if([data isKindOfClass:[NSArray class]]){
NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]];
for (NSDictionary* dict in (NSArray*)data) {
SWGPet* d = [[SWGPet alloc] initWithDictionary:dict error:nil];
[objs addObject:d];
}
completionBlock((NSArray<SWGPet>*)objs, nil);
}
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock([self.apiClient deserialize: data class:@"NSArray<SWGPet>*"], error);
}
];
}
/*!
* Find pet by ID
* Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
* \param petId ID of pet that needs to be fetched
* \returns SWGPet*
*/
///
/// Find pet by ID
/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
/// @param petId ID of pet that needs to be fetched
///
/// @returns SWGPet*
///
-(NSNumber*) getPetByIdWithCompletionBlock: (NSNumber*) petId
completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock
@ -556,54 +490,32 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// non container response
// complex response
// comples response type
return [self.apiClient dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
SWGPet* result = nil;
if (data) {
result = [[SWGPet alloc] initWithDictionary:data error:nil];
}
completionBlock(result , nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock([self.apiClient deserialize: data class:@"SWGPet*"], error);
}
];
}
/*!
* Updates a pet in the store with form data
*
* \param petId ID of pet that needs to be updated
* \param name Updated name of the pet
* \param status Updated status of the pet
* \returns void
*/
///
/// Updates a pet in the store with form data
///
/// @param petId ID of pet that needs to be updated
///
/// @param name Updated name of the pet
///
/// @param status Updated status of the pet
///
/// @returns void
///
-(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId
name: (NSString*) name
status: (NSString*) status
@ -678,39 +590,30 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock(error);
}
];
}
/*!
* Deletes a pet
*
* \param apiKey
* \param petId Pet id to delete
* \returns void
*/
///
/// Deletes a pet
///
/// @param apiKey
///
/// @param petId Pet id to delete
///
/// @returns void
///
-(NSNumber*) deletePetWithCompletionBlock: (NSString*) apiKey
petId: (NSNumber*) petId
@ -770,40 +673,32 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"DELETE"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"DELETE"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock(error);
}
];
}
/*!
* uploads an image
*
* \param petId ID of pet to update
* \param additionalMetadata Additional data to pass to server
* \param file file to upload
* \returns void
*/
///
/// uploads an image
///
/// @param petId ID of pet to update
///
/// @param additionalMetadata Additional data to pass to server
///
/// @param file file to upload
///
/// @returns void
///
-(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId
additionalMetadata: (NSString*) additionalMetadata
file: (SWGFile*) file
@ -885,30 +780,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock(error);
}
];
}

View File

@ -14,62 +14,58 @@
+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath;
/**
Returns pet inventories by status
Returns a map of status codes to quantities
return type: NSDictionary*
*/
///
///
/// Returns pet inventories by status
/// Returns a map of status codes to quantities
///
///
///
/// @return NSDictionary* /* NSString, NSNumber */
-(NSNumber*) getInventoryWithCompletionBlock :
(void (^)(NSDictionary* output, NSError* error))completionBlock;
(void (^)(NSDictionary* /* NSString, NSNumber */ output, NSError* error))completionBlock;
/**
Place an order for a pet
@param body order placed for purchasing the pet
return type: SWGOrder*
*/
///
///
/// Place an order for a pet
///
///
/// @param body order placed for purchasing the pet
///
///
/// @return SWGOrder*
-(NSNumber*) placeOrderWithCompletionBlock :(SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock;
/**
Find purchase order by ID
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
@param orderId ID of pet that needs to be fetched
return type: SWGOrder*
*/
///
///
/// Find purchase order by ID
/// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
///
/// @param orderId ID of pet that needs to be fetched
///
///
/// @return SWGOrder*
-(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock;
/**
Delete purchase order by ID
For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
@param orderId ID of the order that needs to be deleted
return type:
*/
///
///
/// Delete purchase order by ID
/// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
///
/// @param orderId ID of the order that needs to be deleted
///
///
/// @return
-(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId

View File

@ -70,14 +70,15 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
return [SWGApiClient requestQueueSize];
}
#pragma mark - Api Methods
/*!
* Returns pet inventories by status
* Returns a map of status codes to quantities
* \returns NSDictionary*
*/
///
/// Returns pet inventories by status
/// Returns a map of status codes to quantities
/// @returns NSDictionary* /* NSString, NSNumber */
///
-(NSNumber*) getInventoryWithCompletionBlock:
(void (^)(NSDictionary* output, NSError* error))completionBlock
(void (^)(NSDictionary* /* NSString, NSNumber */ output, NSError* error))completionBlock
{
@ -127,45 +128,28 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// response is in a container
// map container response type
return [self.apiClient dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
NSDictionary *result = nil;
if (data) {
result = [[NSDictionary alloc]initWithDictionary: data];
}
completionBlock(data, nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock([self.apiClient deserialize: data class:@"NSDictionary* /* NSString, NSNumber */"], error);
}
];
}
/*!
* Place an order for a pet
*
* \param body order placed for purchasing the pet
* \returns SWGOrder*
*/
///
/// Place an order for a pet
///
/// @param body order placed for purchasing the pet
///
/// @returns SWGOrder*
///
-(NSNumber*) placeOrderWithCompletionBlock: (SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock
@ -241,52 +225,28 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// non container response
// complex response
// comples response type
return [self.apiClient dictionary: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
SWGOrder* result = nil;
if (data) {
result = [[SWGOrder alloc] initWithDictionary:data error:nil];
}
completionBlock(result , nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock([self.apiClient deserialize: data class:@"SWGOrder*"], error);
}
];
}
/*!
* Find purchase order by ID
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* \param orderId ID of pet that needs to be fetched
* \returns SWGOrder*
*/
///
/// Find purchase order by ID
/// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
/// @param orderId ID of pet that needs to be fetched
///
/// @returns SWGOrder*
///
-(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock
@ -343,52 +303,28 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// non container response
// complex response
// comples response type
return [self.apiClient dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
SWGOrder* result = nil;
if (data) {
result = [[SWGOrder alloc] initWithDictionary:data error:nil];
}
completionBlock(result , nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock([self.apiClient deserialize: data class:@"SWGOrder*"], error);
}
];
}
/*!
* Delete purchase order by ID
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* \param orderId ID of the order that needs to be deleted
* \returns void
*/
///
/// Delete purchase order by ID
/// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
/// @param orderId ID of the order that needs to be deleted
///
/// @returns void
///
-(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId
@ -445,30 +381,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"DELETE"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"DELETE"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock(error);
}
];
}

View File

@ -14,65 +14,61 @@
+(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath;
/**
Create user
This can only be done by the logged in user.
@param body Created user object
return type:
*/
///
///
/// Create user
/// This can only be done by the logged in user.
///
/// @param body Created user object
///
///
/// @return
-(NSNumber*) createUserWithCompletionBlock :(SWGUser*) body
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Creates list of users with given input array
@param body List of user object
return type:
*/
///
///
/// Creates list of users with given input array
///
///
/// @param body List of user object
///
///
/// @return
-(NSNumber*) createUsersWithArrayInputWithCompletionBlock :(NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Creates list of users with given input array
@param body List of user object
return type:
*/
///
///
/// Creates list of users with given input array
///
///
/// @param body List of user object
///
///
/// @return
-(NSNumber*) createUsersWithListInputWithCompletionBlock :(NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Logs user into the system
@param username The user name for login
@param password The password for login in clear text
return type: NSString*
*/
///
///
/// Logs user into the system
///
///
/// @param username The user name for login
/// @param password The password for login in clear text
///
///
/// @return NSString*
-(NSNumber*) loginUserWithCompletionBlock :(NSString*) username
password:(NSString*) password
@ -80,47 +76,44 @@
/**
Logs out current logged in user session
return type:
*/
///
///
/// Logs out current logged in user session
///
///
///
///
/// @return
-(NSNumber*) logoutUserWithCompletionBlock :
(void (^)(NSError* error))completionBlock;
/**
Get user by user name
@param username The name that needs to be fetched. Use user1 for testing.
return type: SWGUser*
*/
///
///
/// Get user by user name
///
///
/// @param username The name that needs to be fetched. Use user1 for testing.
///
///
/// @return SWGUser*
-(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username
completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock;
/**
Updated user
This can only be done by the logged in user.
@param username name that need to be deleted
@param body Updated user object
return type:
*/
///
///
/// Updated user
/// This can only be done by the logged in user.
///
/// @param username name that need to be deleted
/// @param body Updated user object
///
///
/// @return
-(NSNumber*) updateUserWithCompletionBlock :(NSString*) username
body:(SWGUser*) body
@ -128,16 +121,15 @@
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Delete user
This can only be done by the logged in user.
@param username The name that needs to be deleted
return type:
*/
///
///
/// Delete user
/// This can only be done by the logged in user.
///
/// @param username The name that needs to be deleted
///
///
/// @return
-(NSNumber*) deleteUserWithCompletionBlock :(NSString*) username

View File

@ -70,13 +70,15 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
return [SWGApiClient requestQueueSize];
}
#pragma mark - Api Methods
/*!
* Create user
* This can only be done by the logged in user.
* \param body Created user object
* \returns void
*/
///
/// Create user
/// This can only be done by the logged in user.
/// @param body Created user object
///
/// @returns void
///
-(NSNumber*) createUserWithCompletionBlock: (SWGUser*) body
@ -152,38 +154,28 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock(error);
}
];
}
/*!
* Creates list of users with given input array
*
* \param body List of user object
* \returns void
*/
///
/// Creates list of users with given input array
///
/// @param body List of user object
///
/// @returns void
///
-(NSNumber*) createUsersWithArrayInputWithCompletionBlock: (NSArray<SWGUser>*) body
@ -259,38 +251,28 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock(error);
}
];
}
/*!
* Creates list of users with given input array
*
* \param body List of user object
* \returns void
*/
///
/// Creates list of users with given input array
///
/// @param body List of user object
///
/// @returns void
///
-(NSNumber*) createUsersWithListInputWithCompletionBlock: (NSArray<SWGUser>*) body
@ -366,39 +348,30 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock(error);
}
];
}
/*!
* Logs user into the system
*
* \param username The user name for login
* \param password The password for login in clear text
* \returns NSString*
*/
///
/// Logs user into the system
///
/// @param username The user name for login
///
/// @param password The password for login in clear text
///
/// @returns NSString*
///
-(NSNumber*) loginUserWithCompletionBlock: (NSString*) username
password: (NSString*) password
@ -460,50 +433,26 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// non container response
// primitive response
// primitive response type
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
NSString *result = data ? [[NSString alloc]initWithString: data] : nil;
completionBlock(result, nil);
}];
// complex response
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock([self.apiClient deserialize: data class:@"NSString*"], error);
}
];
}
/*!
* Logs out current logged in user session
*
* \returns void
*/
///
/// Logs out current logged in user session
///
/// @returns void
///
-(NSNumber*) logoutUserWithCompletionBlock:
(void (^)(NSError* error))completionBlock {
@ -555,38 +504,28 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock(error);
}
];
}
/*!
* Get user by user name
*
* \param username The name that needs to be fetched. Use user1 for testing.
* \returns SWGUser*
*/
///
/// Get user by user name
///
/// @param username The name that needs to be fetched. Use user1 for testing.
///
/// @returns SWGUser*
///
-(NSNumber*) getUserByNameWithCompletionBlock: (NSString*) username
completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock
@ -643,53 +582,30 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// non container response
// complex response
// comples response type
return [self.apiClient dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
SWGUser* result = nil;
if (data) {
result = [[SWGUser alloc] initWithDictionary:data error:nil];
}
completionBlock(result , nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock([self.apiClient deserialize: data class:@"SWGUser*"], error);
}
];
}
/*!
* Updated user
* This can only be done by the logged in user.
* \param username name that need to be deleted
* \param body Updated user object
* \returns void
*/
///
/// Updated user
/// This can only be done by the logged in user.
/// @param username name that need to be deleted
///
/// @param body Updated user object
///
/// @returns void
///
-(NSNumber*) updateUserWithCompletionBlock: (NSString*) username
body: (SWGUser*) body
@ -770,38 +686,28 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"PUT"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"PUT"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock(error);
}
];
}
/*!
* Delete user
* This can only be done by the logged in user.
* \param username The name that needs to be deleted
* \returns void
*/
///
/// Delete user
/// This can only be done by the logged in user.
/// @param username The name that needs to be deleted
///
/// @returns void
///
-(NSNumber*) deleteUserWithCompletionBlock: (NSString*) username
@ -858,30 +764,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"DELETE"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"DELETE"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
completionBlock(error);
}
];
}