|
| 1 | +/** |
| 2 | + * @description |
| 3 | + * HTTP code snippet generator for Swift using NSURLSession. |
| 4 | + * |
| 5 | + * @author |
| 6 | + * @thibaultCha |
| 7 | + * |
| 8 | + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. |
| 9 | + */ |
| 10 | + |
| 11 | +'use strict' |
| 12 | + |
| 13 | +var util = require('util') |
| 14 | +var helpers = require('./helpers') |
| 15 | +var CodeBuilder = require('../../helpers/code-builder') |
| 16 | + |
| 17 | +module.exports = function (source, options) { |
| 18 | + var opts = util._extend({ |
| 19 | + timeout: '10', |
| 20 | + indent: ' ', |
| 21 | + pretty: true |
| 22 | + }, options) |
| 23 | + |
| 24 | + var code = new CodeBuilder(opts.indent) |
| 25 | + |
| 26 | + // Markers for headers to be created as litteral objects and later be set on the NSURLRequest if exist |
| 27 | + var req = { |
| 28 | + hasHeaders: false, |
| 29 | + hasBody: false |
| 30 | + } |
| 31 | + |
| 32 | + // We just want to make sure people understand that is the only dependency |
| 33 | + code.push('import Foundation') |
| 34 | + |
| 35 | + if (Object.keys(source.allHeaders).length) { |
| 36 | + req.hasHeaders = true |
| 37 | + code.blank() |
| 38 | + .push(helpers.literalDeclaration('headers', source.allHeaders, opts)) |
| 39 | + } |
| 40 | + |
| 41 | + if (source.postData.text || source.postData.jsonObj || source.postData.params) { |
| 42 | + req.hasBody = true |
| 43 | + |
| 44 | + switch (source.postData.mimeType) { |
| 45 | + case 'application/x-www-form-urlencoded': |
| 46 | + // By appending parameters one by one in the resulting snippet, |
| 47 | + // we make it easier for the user to edit it according to his or her needs after pasting. |
| 48 | + // The user can just add/remove lines adding/removing body parameters. |
| 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)) |
| 51 | + for (var i = 1, len = source.postData.params.length; i < len; i++) { |
| 52 | + code.push(util.format('postData.appendData("&%s=%s".dataUsingEncoding(NSUTF8StringEncoding)!)', source.postData.params[i].name, source.postData.params[i].value)) |
| 53 | + } |
| 54 | + break |
| 55 | + |
| 56 | + case 'application/json': |
| 57 | + if (source.postData.jsonObj) { |
| 58 | + code.push(helpers.literalDeclaration('parameters', source.postData.jsonObj, opts)) |
| 59 | + .blank() |
| 60 | + .push('let postData = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: nil)') |
| 61 | + } |
| 62 | + break |
| 63 | + |
| 64 | + case 'multipart/form-data': |
| 65 | + /** |
| 66 | + * By appending multipart parameters one by one in the resulting snippet, |
| 67 | + * we make it easier for the user to edit it according to his or her needs after pasting. |
| 68 | + * The user can just edit the parameters NSDictionary or put this part of a snippet in a multipart builder method. |
| 69 | + */ |
| 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('}') |
| 93 | + break |
| 94 | + |
| 95 | + default: |
| 96 | + code.blank() |
| 97 | + .push(util.format('let postData = NSData(data: "%s".dataUsingEncoding(NSUTF8StringEncoding)!)', source.postData.text)) |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 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)) |
| 107 | + |
| 108 | + if (req.hasHeaders) { |
| 109 | + code.push('request.allHTTPHeaderFields = headers') |
| 110 | + } |
| 111 | + |
| 112 | + if (req.hasBody) { |
| 113 | + code.push('request.HTTPBody = postData') |
| 114 | + } |
| 115 | + |
| 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() |
| 132 | +} |
| 133 | + |
| 134 | +module.exports.info = { |
| 135 | + key: 'nsurlsession', |
| 136 | + title: 'NSURLSession', |
| 137 | + link: 'https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html', |
| 138 | + description: 'Foundation\'s NSURLSession request' |
| 139 | +} |
0 commit comments