|
| 1 | +/** |
| 2 | + * @description |
| 3 | + * HTTP code snippet generator for Objective-C 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 | + // Markers for headers to be created as litteral objects and later be set on the NSURLRequest if exist |
| 26 | + var req = { |
| 27 | + hasHeaders: false, |
| 28 | + hasBody: false |
| 29 | + } |
| 30 | + |
| 31 | + // We just want to make sure people understand that is the only dependency |
| 32 | + code.push('#import <Foundation/Foundation.h>') |
| 33 | + |
| 34 | + if (Object.keys(source.allHeaders).length) { |
| 35 | + req.hasHeaders = true |
| 36 | + code.blank() |
| 37 | + .push(helpers.nsDeclaration('NSDictionary', 'headers', source.allHeaders, opts.pretty)) |
| 38 | + } |
| 39 | + |
| 40 | + if (source.postData.text || source.postData.jsonObj || source.postData.params) { |
| 41 | + req.hasBody = true |
| 42 | + |
| 43 | + switch (source.postData.mimeType) { |
| 44 | + case 'application/x-www-form-urlencoded': |
| 45 | + // By appending parameters one by one in the resulting snippet, |
| 46 | + // we make it easier for the user to edit it according to his or her needs after pasting. |
| 47 | + // The user can just add/remove lines adding/removing body parameters. |
| 48 | + code.blank() |
| 49 | + .push(util.format('NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];', |
| 50 | + 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]];', |
| 53 | + source.postData.params[i].name, source.postData.params[i].value)) |
| 54 | + } |
| 55 | + break |
| 56 | + |
| 57 | + case 'application/json': |
| 58 | + if (source.postData.jsonObj) { |
| 59 | + code.push(helpers.nsDeclaration('NSDictionary', 'parameters', source.postData.jsonObj, opts.pretty)) |
| 60 | + .blank() |
| 61 | + .push('NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];') |
| 62 | + } |
| 63 | + break |
| 64 | + |
| 65 | + case 'multipart/form-data': |
| 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 | + code.push(helpers.nsDeclaration('NSArray', 'parameters', source.postData.params, opts.pretty)) |
| 70 | + .push(util.format('NSString *boundary = @"%s";', source.postData.boundary)) |
| 71 | + .blank() |
| 72 | + .push('NSError *error;') |
| 73 | + .push('NSMutableString *body = [NSMutableString string];') |
| 74 | + .push('for (NSDictionary *param in parameters) {') |
| 75 | + .push(1, '[body appendFormat:@"--%@\\r\\n", boundary];') |
| 76 | + .push(1, 'if (param[@"fileName"]) {') |
| 77 | + .push(2, '[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"; filename=\\"%@\\"\\r\\n", param[@"name"], param[@"fileName"]];') |
| 78 | + .push(2, '[body appendFormat:@"Content-Type: %@\\r\\n\\r\\n", param[@"contentType"]];') |
| 79 | + .push(2, '[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];') |
| 80 | + .push(2, 'if (error) {') |
| 81 | + .push(3, 'NSLog(@"%@", error);') |
| 82 | + .push(2, '}') |
| 83 | + .push(1, '} else {') |
| 84 | + .push(2, '[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"\\r\\n\\r\\n", param[@"name"]];') |
| 85 | + .push(2, '[body appendFormat:@"%@", param[@"value"]];') |
| 86 | + .push(1, '}') |
| 87 | + .push('}') |
| 88 | + .push('[body appendFormat:@"\\r\\n--%@--\\r\\n", boundary];') |
| 89 | + .push('NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];') |
| 90 | + break |
| 91 | + |
| 92 | + default: |
| 93 | + code.blank() |
| 94 | + .push('NSData *postData = [[NSData alloc] initWithData:[@"' + source.postData.text + '" dataUsingEncoding:NSUTF8StringEncoding]];') |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + code.blank() |
| 99 | + .push('NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"' + source.fullUrl + '"]') |
| 100 | + // NSURLRequestUseProtocolCachePolicy is the default policy, let's just always set it to avoid confusion. |
| 101 | + .push(' cachePolicy:NSURLRequestUseProtocolCachePolicy') |
| 102 | + .push(' timeoutInterval:' + parseInt(opts.timeout, 10).toFixed(1) + '];') |
| 103 | + .push('[request setHTTPMethod:@"' + source.method + '"];') |
| 104 | + |
| 105 | + if (req.hasHeaders) { |
| 106 | + code.push('[request setAllHTTPHeaderFields:headers];') |
| 107 | + } |
| 108 | + |
| 109 | + if (req.hasBody) { |
| 110 | + code.push('[request setHTTPBody:postData];') |
| 111 | + } |
| 112 | + |
| 113 | + code.blank() |
| 114 | + // Retrieving the shared session will be less verbose than creating a new one. |
| 115 | + .push('NSURLSession *session = [NSURLSession sharedSession];') |
| 116 | + .push('NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request') |
| 117 | + .push(' completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {') |
| 118 | + .push(1, ' if (error) {') |
| 119 | + .push(2, ' NSLog(@"%@", error);') |
| 120 | + .push(1, ' } else {') |
| 121 | + // Casting the NSURLResponse to NSHTTPURLResponse so the user can see the status . |
| 122 | + .push(2, ' NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;') |
| 123 | + .push(2, ' NSLog(@"%@", httpResponse);') |
| 124 | + .push(1, ' }') |
| 125 | + .push(' }];') |
| 126 | + .push('[dataTask resume];') |
| 127 | + |
| 128 | + return code.join() |
| 129 | +} |
| 130 | + |
| 131 | +module.exports.info = { |
| 132 | + key: 'nsurlsession', |
| 133 | + title: 'NSURLSession', |
| 134 | + link: 'https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html', |
| 135 | + description: 'Foundation\'s NSURLSession request' |
| 136 | +} |
0 commit comments