forked from Kong/httpsnippet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.js
More file actions
84 lines (70 loc) · 1.94 KB
/
Copy pathfetch.js
File metadata and controls
84 lines (70 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* @description
* HTTP code snippet generator for the browser Fetch API
*
* @author
* @peoplenarthax
*
* for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
*/
'use strict'
var util = require('util')
var CodeBuilder = require('../../helpers/code-builder')
module.exports = function (source, options) {
var opts = util._extend(
{
indent: ' '
},
options
)
var code = new CodeBuilder(opts.indent)
var url = source.fullUrl
var fetchOptions = {
mode: 'cors',
method: source.method,
headers: source.allHeaders
}
switch (source.postData.mimeType) {
case 'application/x-www-form-urlencoded':
fetchOptions.body = source.postData.paramsObj
? source.postData.paramsObj
: source.postData.text
break
case 'application/json':
fetchOptions.body = source.postData.text
break
case 'multipart/form-data':
code.push('let form = new FormData();')
source.postData.params.forEach(function (param) {
code.push(
'form.append(%s, %s);',
JSON.stringify(param.name),
JSON.stringify(param.value || param.fileName || '')
)
})
delete fetchOptions.headers
fetchOptions.body = '[form]'
code.blank()
break
default:
if (source.postData.text) {
fetchOptions.data = source.postData.text
}
}
code
.push(
'const fetchOptions = ' +
JSON.stringify(fetchOptions, null, opts.indent).replace('"[form]"', 'form')
)
.blank()
.push('fetch("' + url + '", fetchOptions)')
.push(1, '.then(response => response.json())')
.push(1, '.then(data => console.log(data));')
return code.join()
}
module.exports.info = {
key: 'fetch',
title: 'Fetch API',
link: 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API',
description: 'Browser API that offers a simple interface for fetching resources'
}