|
| 1 | +/** |
| 2 | + * @description |
| 3 | + * HTTP code snippet generator for native XMLHttpRequest |
| 4 | + * |
| 5 | + * @author |
| 6 | + * @AhmadNassri |
| 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 CodeBuilder = require('../../helpers/code-builder') |
| 15 | + |
| 16 | +module.exports = function (source, options) { |
| 17 | + var opts = util._extend({ |
| 18 | + indent: ' ' |
| 19 | + }, options) |
| 20 | + |
| 21 | + var code = new CodeBuilder(opts.indent) |
| 22 | + |
| 23 | + var settings = { |
| 24 | + async: true, |
| 25 | + crossDomain: true, |
| 26 | + url: source.fullUrl, |
| 27 | + method: source.method, |
| 28 | + headers: source.allHeaders |
| 29 | + } |
| 30 | + |
| 31 | + switch (source.postData.mimeType) { |
| 32 | + case 'application/x-www-form-urlencoded': |
| 33 | + settings.data = source.postData.paramsObj ? source.postData.paramsObj : source.postData.text |
| 34 | + break |
| 35 | + |
| 36 | + case 'application/json': |
| 37 | + settings.processData = false |
| 38 | + settings.data = source.postData.text |
| 39 | + break |
| 40 | + |
| 41 | + case 'multipart/form-data': |
| 42 | + code.push('var form = new FormData();') |
| 43 | + |
| 44 | + source.postData.params.forEach(function (param) { |
| 45 | + code.push('form.append(%s, %s);', JSON.stringify(param.name), JSON.stringify(param.value || param.fileName || '')) |
| 46 | + }) |
| 47 | + |
| 48 | + settings.processData = false |
| 49 | + settings.contentType = false |
| 50 | + settings.mimeType = 'multipart/form-data' |
| 51 | + settings.data = '[form]' |
| 52 | + |
| 53 | + // remove the contentType header |
| 54 | + if (~settings.headers['content-type'].indexOf('boundary')) { |
| 55 | + delete settings.headers['content-type'] |
| 56 | + } |
| 57 | + code.blank() |
| 58 | + break |
| 59 | + |
| 60 | + default: |
| 61 | + if (source.postData.text) { |
| 62 | + settings.data = source.postData.text |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + code.push('var settings = ' + JSON.stringify(settings, null, opts.indent).replace('"[form]"', 'form')) |
| 67 | + .blank() |
| 68 | + .push('$.ajax(settings).done(function (response) {') |
| 69 | + .push(1, 'console.log(response);') |
| 70 | + .push('});') |
| 71 | + |
| 72 | + return code.join() |
| 73 | +} |
| 74 | + |
| 75 | +module.exports.info = { |
| 76 | + key: 'jquery', |
| 77 | + title: 'jQuery', |
| 78 | + link: 'http://api.jquery.com/jquery.ajax/', |
| 79 | + description: 'Perform an asynchronous HTTP (Ajax) requests with jQuery' |
| 80 | +} |
0 commit comments