Skip to content

Commit b365910

Browse files
committed
Merge pull request #31 from Mashape/refactor/objc/native
refactor: objc/native enhancements
2 parents 55c91ef + a0282ae commit b365910

5 files changed

Lines changed: 53 additions & 43 deletions

File tree

src/targets/objc/helpers.js

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,37 +14,28 @@ module.exports = {
1414
},
1515

1616
/**
17-
* Create a string corresponding to a valid NSDictionary declaration and initialization for Objective-C.
17+
* Create a string corresponding to a valid declaration and initialization of an Objective-C object litteral.
1818
*
19-
* @param {string} name Desired name of the NSDictionary instance
20-
* @param {Object} parameters Key-value object of parameters to translate to an Objective-C NSDictionary litearal
21-
* @param {boolean} indent If true, will declare the NSDictionary litteral by indenting each new key/value pair.
22-
* @return {string} A valid Objective-C declaration and initialization of an NSDictionary.
19+
* @param {string} nsClass Class of the litteral
20+
* @param {string} name Desired name of the instance
21+
* @param {Object} parameters Key-value object of parameters to translate to an Objective-C object litearal
22+
* @param {boolean} indent If true, will declare the litteral by indenting each new key/value pair.
23+
* @return {string} A valid Objective-C declaration and initialization of an Objective-C object litteral.
2324
*
2425
* @example
25-
* nsDictionaryBuilder('params', {a: 'b', c: 'd'}, true)
26+
* nsDeclarationBuilder('NSDictionary', 'params', {a: 'b', c: 'd'}, true)
2627
* // returns:
2728
* NSDictionary *params = @{ @"a": @"b",
2829
* @"c": @"d" };
2930
*
30-
* nsDictionaryBuilder('params', {a: 'b', c: 'd'})
31+
* nsDeclarationBuilder('NSDictionary', 'params', {a: 'b', c: 'd'})
3132
* // returns:
3233
* NSDictionary *params = @{ @"a": @"b", @"c": @"d" };
3334
*/
34-
nsDictionaryBuilder: function (name, parameters, indent) {
35-
var dicOpening = 'NSDictionary *' + name + ' = '
36-
var dicLiteral = this.literalRepresentation(parameters, indent ? dicOpening.length : undefined)
37-
return dicOpening + dicLiteral + ';'
38-
},
39-
40-
/**
41-
* Similar to nsDictionaryBuilder but for NSArray literals.
42-
* @see nsDictionaryBuilder
43-
*/
44-
nsArrayBuilder: function (name, parameters, indent) {
45-
var arrOpening = 'NSArray *' + name + ' = '
46-
var arrLiteral = this.literalRepresentation(parameters, indent ? arrOpening.length : undefined)
47-
return arrOpening + arrLiteral + ';'
35+
nsDeclarationBuilder: function (nsClass, name, parameters, indent) {
36+
var opening = nsClass + ' *' + name + ' = '
37+
var literal = this.literalRepresentation(parameters, indent ? opening.length : undefined)
38+
return opening + literal + ';'
4839
},
4940

5041
/**

src/targets/objc/native.js

Lines changed: 35 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,16 @@
1+
/**
2+
* This file is part of the httpsnippet project (https://github.com/Mashape/httpsnippet)
3+
* If you have questions or issues regarding its implementation, please open an issue.
4+
* If you have questions or issues regarding the generated code snippet, please open an issue mentioning its author/contributors.
5+
*
6+
* @description
7+
* HTTP code snippet generator for Objective-C using NSURLSession.
8+
* This file tries to generate a flexible snippet than can easily be edited once pasted by the user.
9+
*
10+
* @author
11+
* @thibaultCha
12+
*/
13+
114
'use strict'
215

316
var util = require('util')
@@ -10,21 +23,21 @@ module.exports = function (source, options) {
1023
pretty: true
1124
}, options)
1225

26+
var indent = opts.indent
1327
var code = []
14-
28+
// Markers for headers to be created as litteral objects and later be set on the NSURLRequest if exist
1529
var req = {
1630
hasHeaders: false,
1731
hasBody: false
1832
}
1933

20-
var indent = opts.indent
21-
34+
// We just want to make sure people understand that is the only dependency
2235
code.push('#import <Foundation/Foundation.h>')
2336

2437
if (Object.keys(source.allHeaders).length) {
2538
req.hasHeaders = true
2639
code.push(null)
27-
code.push(objcHelpers.nsDictionaryBuilder('headers', source.allHeaders, opts.pretty))
40+
code.push(objcHelpers.nsDeclarationBuilder('NSDictionary', 'headers', source.allHeaders, opts.pretty))
2841
}
2942

3043
if (source.postData.text || source.postData.jsonObj || source.postData.params) {
@@ -33,23 +46,30 @@ module.exports = function (source, options) {
3346
switch (source.postData.mimeType) {
3447
case 'application/x-www-form-urlencoded':
3548
code.push(null)
36-
// Makes it easier to implement logice than just putting the entire body string
37-
code.push(util.format('NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];', source.postData.params[0].name, source.postData.params[0].value))
49+
// By appending parameters one by one in the resulting snippet,
50+
// we make it easier for the user to edit it according to his or her needs after pasting.
51+
// The user can just add/remove lines adding/removing body parameters.
52+
code.push(util.format('NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];',
53+
source.postData.params[0].name, source.postData.params[0].value))
3854
for (var i = 1, len = source.postData.params.length; i < len; i++) {
39-
code.push(util.format('[postData appendData:[@"&%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];', source.postData.params[i].name, source.postData.params[i].value))
55+
code.push(util.format('[postData appendData:[@"&%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];',
56+
source.postData.params[i].name, source.postData.params[i].value))
4057
}
4158
break
4259

4360
case 'application/json':
4461
if (source.postData.jsonObj) {
45-
code.push(objcHelpers.nsDictionaryBuilder('parameters', source.postData.jsonObj, opts.pretty))
62+
code.push(objcHelpers.nsDeclarationBuilder('NSDictionary', 'parameters', source.postData.jsonObj, opts.pretty))
4663
code.push(null)
4764
code.push('NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];')
4865
}
4966
break
5067

5168
case 'multipart/form-data':
52-
code.push(objcHelpers.nsArrayBuilder('parameters', source.postData.params, opts.pretty))
69+
// By appending multipart parameters one by one in the resulting snippet,
70+
// we make it easier for the user to edit it according to his or her needs after pasting.
71+
// The user can just edit the parameters NSDictionary or put this part of a snippet in a multipart builder method.
72+
code.push(objcHelpers.nsDeclarationBuilder('NSArray', 'parameters', source.postData.params, opts.pretty))
5373
code.push(util.format('NSString *boundary = @"%s";', source.postData.boundary))
5474
code.push(null)
5575
code.push('NSError *error;')
@@ -59,8 +79,7 @@ module.exports = function (source, options) {
5979
code.push(indent + 'if (param[@"fileName"]) {')
6080
code.push(indent + indent + '[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"; filename=\\"%@\\"\\r\\n", param[@"name"], param[@"fileName"]];')
6181
code.push(indent + indent + '[body appendFormat:@"Content-Type: %@\\r\\n\\r\\n", param[@"contentType"]];')
62-
code.push(indent + indent + '[body appendFormat:@"%@", [[NSString alloc] initWithContentsOfFile:param[@"fileName"]')
63-
code.push(indent + indent + ' encoding:NSUTF8StringEncoding error:&error]];')
82+
code.push(indent + indent + '[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];')
6483
code.push(indent + indent + 'if (error) {')
6584
code.push(indent + indent + indent + 'NSLog(@"%@", error);')
6685
code.push(indent + indent + '}')
@@ -70,7 +89,7 @@ module.exports = function (source, options) {
7089
code.push(indent + '}')
7190
code.push('}')
7291
code.push('[body appendFormat:@"\\r\\n--%@--\\r\\n", boundary];')
73-
code.push('NSData *postData = [[NSData alloc] initWithData:[body dataUsingEncoding:NSUTF8StringEncoding]];')
92+
code.push('NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];')
7493
break
7594

7695
default:
@@ -81,6 +100,7 @@ module.exports = function (source, options) {
81100

82101
code.push(null)
83102
code.push('NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"' + source.fullUrl + '"]')
103+
// NSURLRequestUseProtocolCachePolicy is the default policy, let's just always set it to avoid confusion.
84104
code.push(' cachePolicy:NSURLRequestUseProtocolCachePolicy')
85105
code.push(' timeoutInterval:' + parseInt(opts.timeout, 10).toFixed(1) + '];')
86106
code.push('[request setHTTPMethod:@"' + source.method + '"];')
@@ -94,12 +114,14 @@ module.exports = function (source, options) {
94114
}
95115

96116
code.push(null)
97-
code.push('NSURLSession *session = [NSURLSession sharedSession];') // Retrieve shared session for simplicity
117+
// Retrieving the shared session will be less verbose than creating a new one.
118+
code.push('NSURLSession *session = [NSURLSession sharedSession];')
98119
code.push('NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request')
99120
code.push(' completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {')
100121
code.push(' ' + indent + 'if (error) {')
101122
code.push(' ' + indent + indent + 'NSLog(@"%@", error);')
102123
code.push(' ' + indent + '} else {')
124+
// Casting the NSURLResponse to NSHTTPURLResponse so the user can see the status code.
103125
code.push(' ' + indent + indent + 'NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;')
104126
code.push(' ' + indent + indent + 'NSLog(@"%@", httpResponse);')
105127
code.push(' ' + indent + '}')

test/fixtures/output/objc/native/multipart-data.m

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
if (param[@"fileName"]) {
1212
[body appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", param[@"name"], param[@"fileName"]];
1313
[body appendFormat:@"Content-Type: %@\r\n\r\n", param[@"contentType"]];
14-
[body appendFormat:@"%@", [[NSString alloc] initWithContentsOfFile:param[@"fileName"]
15-
encoding:NSUTF8StringEncoding error:&error]];
14+
[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];
1615
if (error) {
1716
NSLog(@"%@", error);
1817
}
@@ -22,7 +21,7 @@
2221
}
2322
}
2423
[body appendFormat:@"\r\n--%@--\r\n", boundary];
25-
NSData *postData = [[NSData alloc] initWithData:[body dataUsingEncoding:NSUTF8StringEncoding]];
24+
NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];
2625

2726
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"]
2827
cachePolicy:NSURLRequestUseProtocolCachePolicy

test/fixtures/output/objc/native/multipart-file.m

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
if (param[@"fileName"]) {
1212
[body appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", param[@"name"], param[@"fileName"]];
1313
[body appendFormat:@"Content-Type: %@\r\n\r\n", param[@"contentType"]];
14-
[body appendFormat:@"%@", [[NSString alloc] initWithContentsOfFile:param[@"fileName"]
15-
encoding:NSUTF8StringEncoding error:&error]];
14+
[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];
1615
if (error) {
1716
NSLog(@"%@", error);
1817
}
@@ -22,7 +21,7 @@
2221
}
2322
}
2423
[body appendFormat:@"\r\n--%@--\r\n", boundary];
25-
NSData *postData = [[NSData alloc] initWithData:[body dataUsingEncoding:NSUTF8StringEncoding]];
24+
NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];
2625

2726
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"]
2827
cachePolicy:NSURLRequestUseProtocolCachePolicy

test/fixtures/output/objc/native/multipart-form-data.m

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
if (param[@"fileName"]) {
1212
[body appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", param[@"name"], param[@"fileName"]];
1313
[body appendFormat:@"Content-Type: %@\r\n\r\n", param[@"contentType"]];
14-
[body appendFormat:@"%@", [[NSString alloc] initWithContentsOfFile:param[@"fileName"]
15-
encoding:NSUTF8StringEncoding error:&error]];
14+
[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];
1615
if (error) {
1716
NSLog(@"%@", error);
1817
}
@@ -22,7 +21,7 @@
2221
}
2322
}
2423
[body appendFormat:@"\r\n--%@--\r\n", boundary];
25-
NSData *postData = [[NSData alloc] initWithData:[body dataUsingEncoding:NSUTF8StringEncoding]];
24+
NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];
2625

2726
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"]
2827
cachePolicy:NSURLRequestUseProtocolCachePolicy

0 commit comments

Comments
 (0)