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
83 lines (68 loc) · 1.83 KB
/
fetch.js
File metadata and controls
83 lines (68 loc) · 1.83 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
/**
* @description
* HTTP code snippet generator for fetch
*
* @author
* @pmdroid
*
* for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
*/
'use strict'
var CodeBuilder = require('../../helpers/code-builder')
module.exports = function (source, options) {
var opts = Object.assign(
{
indent: ' ',
credentials: null
},
options
)
var code = new CodeBuilder(opts.indent)
options = {
method: source.method,
headers: source.allHeaders
}
if (opts.credentials !== null) {
options.credentials = opts.credentials
}
switch (source.postData.mimeType) {
case 'application/x-www-form-urlencoded':
options.body = source.postData.paramsObj
? source.postData.paramsObj
: source.postData.text
break
case 'application/json':
options.body = source.postData.jsonObj
break
case 'multipart/form-data':
code.push('var 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 || '')
)
})
code.blank()
break
default:
if (source.postData.text) {
options.body = source.postData.text
}
}
code
.push(`fetch("${source.fullUrl}", ${JSON.stringify(options, null, opts.indent)})`)
.push('.then(response => {')
.push(1, 'console.log(response);')
.push('})')
.push('.catch(err => {')
.push(1, 'console.error(err);')
.push('});')
return code.join()
}
module.exports.info = {
key: 'fetch',
title: 'fetch',
link: 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch',
description: 'Perform asynchronous HTTP requests with the Fetch API'
}