|
| 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 | + |
| 15 | +module.exports = function (source, options) { |
| 16 | + var opts = util._extend({ |
| 17 | + indent: ' ', |
| 18 | + cors: true |
| 19 | + }, options) |
| 20 | + |
| 21 | + var code = [] |
| 22 | + |
| 23 | + switch (source.postData.mimeType) { |
| 24 | + case 'application/json': |
| 25 | + code.push(util.format('var data = JSON.stringify(%s);', JSON.stringify(source.postData.jsonObj, null, opts.indent))) |
| 26 | + code.push(null) |
| 27 | + break |
| 28 | + |
| 29 | + case 'multipart/form-data': |
| 30 | + code.push('var data = new FormData();') |
| 31 | + |
| 32 | + source.postData.params.map(function (param) { |
| 33 | + code.push(util.format('data.append(%s, %s);', JSON.stringify(param.name), JSON.stringify(param.value || param.fileName || ''))) |
| 34 | + }) |
| 35 | + |
| 36 | + // remove the contentType header |
| 37 | + if (source.allHeaders['content-type'].indexOf('boundary')) { |
| 38 | + delete source.allHeaders['content-type'] |
| 39 | + } |
| 40 | + |
| 41 | + code.push(null) |
| 42 | + break |
| 43 | + |
| 44 | + default: |
| 45 | + code.push(util.format('var data = %s;', JSON.stringify(source.postData.text || null))) |
| 46 | + code.push(null) |
| 47 | + } |
| 48 | + |
| 49 | + code.push('var xhr = new XMLHttpRequest();') |
| 50 | + |
| 51 | + if (opts.cors) { |
| 52 | + code.push('xhr.withCredentials = true;') |
| 53 | + } |
| 54 | + |
| 55 | + code.push(null) |
| 56 | + |
| 57 | + code.push('xhr.addEventListener("readystatechange", function () {\n\tif (this.readyState === this.DONE) {\n\t\tconsole.log(this.responseText);\n\t}\n});'.replace(/\t/g, opts.indent)) |
| 58 | + |
| 59 | + code.push(null) |
| 60 | + |
| 61 | + code.push(util.format('xhr.open(%s, %s);', JSON.stringify(source.method), JSON.stringify(source.fullUrl))) |
| 62 | + |
| 63 | + Object.keys(source.allHeaders).map(function (key) { |
| 64 | + code.push(util.format('xhr.setRequestHeader(%s, %s);', JSON.stringify(key), JSON.stringify(source.allHeaders[key]))) |
| 65 | + }) |
| 66 | + |
| 67 | + code.push(null) |
| 68 | + |
| 69 | + code.push('xhr.send(data);') |
| 70 | + |
| 71 | + return code.join('\n') |
| 72 | +} |
| 73 | + |
| 74 | +module.exports.info = { |
| 75 | + key: 'xhr', |
| 76 | + title: 'XMLHttpRequest', |
| 77 | + link: 'https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest', |
| 78 | + description: 'W3C Standard API that provides scripted client functionality' |
| 79 | +} |
0 commit comments