forked from Kong/httpsnippet
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfetch.js
More file actions
93 lines (75 loc) · 2.54 KB
/
Copy pathfetch.js
File metadata and controls
93 lines (75 loc) · 2.54 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
85
86
87
88
89
90
91
92
93
/**
* @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'
const stringifyObject = require('stringify-object')
const CodeBuilder = require('../../helpers/code-builder')
const { removeProperty } = require('../../helpers/general')
const { constructAppendedParamsCode } = require('../../helpers/params')
module.exports = function (source, options) {
const opts = Object.assign(
{
indent: ' ',
credentials: null
},
options
)
let code = new CodeBuilder(opts.indent)
options = {
method: source.method
}
if (Object.keys(source.allHeaders).length) {
options.headers = source.allHeaders
}
if (opts.credentials !== null) {
options.credentials = opts.credentials
}
switch (source.postData.mimeType) {
case 'application/json': {
options.body = JSON.stringify(source.postData.jsonObj)
break
}
case 'application/x-www-form-urlencoded': {
code.push('const encodedParams = new URLSearchParams();')
code = constructAppendedParamsCode(code, source.postData.params, { isBrowser: true, dataVarName: 'encodedParams' })
code.blank();
options.body = 'encodedParams'
break
}
case 'multipart/form-data': {
// when a web api's form-data is sent in a request, application/form-data media type is automatically inserted
// into the headers with the right boundary
options.headers = removeProperty(options.headers, 'content-type')
code.push('const data = new FormData();')
code = constructAppendedParamsCode(code, source.postData.params, { isBrowser: true, dataVarName: 'data' })
code.blank()
options.body = 'data';
break
}
default: {
if (source.postData.text) {
options.body = source.postData.text
}
}
}
code.push('const options = %s;', stringifyObject(options, { indent: opts.indent, inlineCharacterLimit: 80 })
.replace(/'encodedParams'/, 'encodedParams').replace(/'data'/, 'data'))
.blank()
code.push("fetch('%s', options)", source.fullUrl)
.push(1, '.then(response => response.json())')
.push(1, '.then(response => console.log(response))')
.push(1, '.catch(err => console.error(err));')
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'
}