Skip to content

Commit cc1aec0

Browse files
committed
chore: convert swift/nsurlsession to CodeBuilder
1 parent c0a967d commit cc1aec0

1 file changed

Lines changed: 57 additions & 58 deletions

File tree

‎src/targets/swift/nsurlsession.js‎

Lines changed: 57 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
'use strict'
1212

1313
var util = require('util')
14-
var swiftHelpers = require('./helpers')
14+
var helpers = require('./helpers')
15+
var CodeBuilder = require('../../helpers/code-builder')
1516

1617
module.exports = function (source, options) {
1718
var opts = util._extend({
@@ -20,45 +21,43 @@ module.exports = function (source, options) {
2021
pretty: true
2122
}, options)
2223

23-
var code = []
24+
var code = new CodeBuilder(opts.indent)
2425

2526
// Markers for headers to be created as litteral objects and later be set on the NSURLRequest if exist
2627
var req = {
2728
hasHeaders: false,
2829
hasBody: false
2930
}
3031

31-
var indent = opts.indent
32-
3332
// We just want to make sure people understand that is the only dependency
3433
code.push('import Foundation')
3534

3635
if (Object.keys(source.allHeaders).length) {
3736
req.hasHeaders = true
38-
code.push(null)
39-
code.push(swiftHelpers.literalDeclaration('headers', source.allHeaders, opts))
37+
code.blank()
38+
.push(helpers.literalDeclaration('headers', source.allHeaders, opts))
4039
}
4140

4241
if (source.postData.text || source.postData.jsonObj || source.postData.params) {
4342
req.hasBody = true
4443

4544
switch (source.postData.mimeType) {
4645
case 'application/x-www-form-urlencoded':
47-
code.push(null)
4846
// By appending parameters one by one in the resulting snippet,
4947
// we make it easier for the user to edit it according to his or her needs after pasting.
5048
// The user can just add/remove lines adding/removing body parameters.
51-
code.push(util.format('var postData = NSMutableData(data: "%s=%s".dataUsingEncoding(NSUTF8StringEncoding)!)', source.postData.params[0].name, source.postData.params[0].value))
49+
code.blank()
50+
.push(util.format('var postData = NSMutableData(data: "%s=%s".dataUsingEncoding(NSUTF8StringEncoding)!)', source.postData.params[0].name, source.postData.params[0].value))
5251
for (var i = 1, len = source.postData.params.length; i < len; i++) {
5352
code.push(util.format('postData.appendData("&%s=%s".dataUsingEncoding(NSUTF8StringEncoding)!)', source.postData.params[i].name, source.postData.params[i].value))
5453
}
5554
break
5655

5756
case 'application/json':
5857
if (source.postData.jsonObj) {
59-
code.push(swiftHelpers.literalDeclaration('parameters', source.postData.jsonObj, opts))
60-
code.push(null)
61-
code.push('let postData = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: nil)')
58+
code.push(helpers.literalDeclaration('parameters', source.postData.jsonObj, opts))
59+
.blank()
60+
.push('let postData = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: nil)')
6261
}
6362
break
6463

@@ -68,43 +67,43 @@ module.exports = function (source, options) {
6867
* we make it easier for the user to edit it according to his or her needs after pasting.
6968
* The user can just edit the parameters NSDictionary or put this part of a snippet in a multipart builder method.
7069
*/
71-
code.push(swiftHelpers.literalDeclaration('parameters', source.postData.params, opts))
72-
code.push(null)
73-
code.push(util.format('let boundary = "%s"', source.postData.boundary))
74-
code.push(null)
75-
code.push('var body = ""')
76-
code.push('var error: NSError? = nil')
77-
code.push('for param in parameters {')
78-
code.push(indent + 'let paramName = param["name"]!')
79-
code.push(indent + 'body += "--\\(boundary)\\r\\n"')
80-
code.push(indent + 'body += "Content-Disposition:form-data; name=\\"\\(paramName)\\""')
81-
code.push(indent + 'if let filename = param["fileName"] {')
82-
code.push(indent + indent + 'let contentType = param["content-type"]!')
83-
code.push(indent + indent + 'let fileContent = String(contentsOfFile: filename, encoding: NSUTF8StringEncoding, error: &error)')
84-
code.push(indent + indent + 'if (error != nil) {')
85-
code.push(indent + indent + indent + 'println(error)')
86-
code.push(indent + indent + '}')
87-
code.push(indent + indent + 'body += "; filename=\\"\\(filename)\\"\\r\\n"')
88-
code.push(indent + indent + 'body += "Content-Type: \\(contentType)\\r\\n\\r\\n"')
89-
code.push(indent + indent + 'body += fileContent!')
90-
code.push(indent + '} else if let paramValue = param["value"] {')
91-
code.push(indent + indent + 'body += "\\r\\n\\r\\n\\(paramValue)"')
92-
code.push(indent + '}')
93-
code.push('}')
70+
code.push(helpers.literalDeclaration('parameters', source.postData.params, opts))
71+
.blank()
72+
.push(util.format('let boundary = "%s"', source.postData.boundary))
73+
.blank()
74+
.push('var body = ""')
75+
.push('var error: NSError? = nil')
76+
.push('for param in parameters {')
77+
.push(1, 'let paramName = param["name"]!')
78+
.push(1, 'body += "--\\(boundary)\\r\\n"')
79+
.push(1, 'body += "Content-Disposition:form-data; name=\\"\\(paramName)\\""')
80+
.push(1, 'if let filename = param["fileName"] {')
81+
.push(2, 'let contentType = param["content-type"]!')
82+
.push(2, 'let fileContent = String(contentsOfFile: filename, encoding: NSUTF8StringEncoding, error: &error)')
83+
.push(2, 'if (error != nil) {')
84+
.push(3, 'println(error)')
85+
.push(2, '}')
86+
.push(2, 'body += "; filename=\\"\\(filename)\\"\\r\\n"')
87+
.push(2, 'body += "Content-Type: \\(contentType)\\r\\n\\r\\n"')
88+
.push(2, 'body += fileContent!')
89+
.push(1, '} else if let paramValue = param["value"] {')
90+
.push(2, 'body += "\\r\\n\\r\\n\\(paramValue)"')
91+
.push(1, '}')
92+
.push('}')
9493
break
9594

9695
default:
97-
code.push(null)
98-
code.push(util.format('let postData = NSData(data: "%s".dataUsingEncoding(NSUTF8StringEncoding)!)', source.postData.text))
96+
code.blank()
97+
.push(util.format('let postData = NSData(data: "%s".dataUsingEncoding(NSUTF8StringEncoding)!)', source.postData.text))
9998
}
10099
}
101100

102-
code.push(null)
103-
// NSURLRequestUseProtocolCachePolicy is the default policy, let's just always set it to avoid confusion.
104-
code.push(util.format('var request = NSMutableURLRequest(URL: NSURL(string: "%s")!,', source.fullUrl))
105-
code.push(' cachePolicy: .UseProtocolCachePolicy,')
106-
code.push(util.format(' timeoutInterval: %s)', parseInt(opts.timeout, 10).toFixed(1)))
107-
code.push(util.format('request.HTTPMethod = "%s"', source.method))
101+
code.blank()
102+
// NSURLRequestUseProtocolCachePolicy is the default policy, let's just always set it to avoid confusion.
103+
.push(util.format('var request = NSMutableURLRequest(URL: NSURL(string: "%s")!,', source.fullUrl))
104+
.push(' cachePolicy: .UseProtocolCachePolicy,')
105+
.push(util.format(' timeoutInterval: %s)', parseInt(opts.timeout, 10).toFixed(1)))
106+
.push(util.format('request.HTTPMethod = "%s"', source.method))
108107

109108
if (req.hasHeaders) {
110109
code.push('request.allHTTPHeaderFields = headers')
@@ -114,22 +113,22 @@ module.exports = function (source, options) {
114113
code.push('request.HTTPBody = postData')
115114
}
116115

117-
code.push(null)
118-
// Retrieving the shared session will be less verbose than creating a new one.
119-
code.push('let session = NSURLSession.sharedSession()')
120-
code.push('let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in')
121-
code.push(opts.indent + 'if (error != nil) {')
122-
code.push(opts.indent + opts.indent + 'println(error)')
123-
code.push(opts.indent + '} else {')
124-
// Casting the NSURLResponse to NSHTTPURLResponse so the user can see the status code.
125-
code.push(opts.indent + opts.indent + 'let httpResponse = response as? NSHTTPURLResponse')
126-
code.push(opts.indent + opts.indent + 'println(httpResponse)')
127-
code.push(opts.indent + '}')
128-
code.push('})')
129-
code.push(null)
130-
code.push('dataTask.resume()')
131-
132-
return code.join('\n')
116+
code.blank()
117+
// Retrieving the shared session will be less verbose than creating a new one.
118+
.push('let session = NSURLSession.sharedSession()')
119+
.push('let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in')
120+
.push(1, 'if (error != nil) {')
121+
.push(2, 'println(error)')
122+
.push(1, '} else {')
123+
// Casting the NSURLResponse to NSHTTPURLResponse so the user can see the status .
124+
.push(2, 'let httpResponse = response as? NSHTTPURLResponse')
125+
.push(2, 'println(httpResponse)')
126+
.push(1, '}')
127+
.push('})')
128+
.blank()
129+
.push('dataTask.resume()')
130+
131+
return code.join()
133132
}
134133

135134
module.exports.info = {

0 commit comments

Comments
 (0)