-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathfetch.js
More file actions
101 lines (82 loc) · 2.44 KB
/
fetch.js
File metadata and controls
101 lines (82 loc) · 2.44 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
94
95
96
97
98
99
100
101
/**
* @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 CodeBuilder = require('../../helpers/code-builder')
module.exports = function (source, options) {
const opts = Object.assign(
{
indent: ' ',
credentials: null
},
options
)
const stringifyObject = require('../../helpers/stringify-js-object')
const 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/x-www-form-urlencoded':
options.body = source.postData.paramsObj
? source.postData.paramsObj
: source.postData.text
break
case 'application/json':
options.body = JSON.stringify(source.postData.jsonObj)
break
case 'multipart/form-data':
code.push('const 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('const options = %s;', stringifyObject(options, {
indent: opts.indent,
inlineCharacterLimit: 80,
transform: (object, property, originalResult) => {
if (property === 'body' && source.postData.mimeType === 'application/x-www-form-urlencoded') {
return `new URLSearchParams(${originalResult})`
}
return originalResult
}
}))
.blank()
if (source.postData.mimeType === 'multipart/form-data') {
code.push('options.body = form;')
.blank()
}
code.push('fetch(%s, options)', stringifyObject(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'
}