-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathaxios.js
More file actions
89 lines (71 loc) · 2.13 KB
/
axios.js
File metadata and controls
89 lines (71 loc) · 2.13 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
/**
* @description
* HTTP code snippet generator for Javascript & Node.js using Axios.
*
* @author
* @rohit-gohri
*
* for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
*/
'use strict'
const util = require('util')
const stringifyObject = require('stringify-object')
const CodeBuilder = require('../../helpers/code-builder')
module.exports = function (source, options) {
const opts = Object.assign({
indent: ' '
}, options)
const code = new CodeBuilder(opts.indent)
code.push('import axios from "axios";')
.blank()
const reqOpts = {
method: source.method,
url: source.url
}
if (Object.keys(source.queryObj).length) {
reqOpts.params = source.queryObj
}
if (Object.keys(source.allHeaders).length) {
reqOpts.headers = source.allHeaders
}
switch (source.postData.mimeType) {
case 'application/x-www-form-urlencoded':
reqOpts.data = source.postData.paramsObj
break
case 'application/json':
if (source.postData.jsonObj) {
reqOpts.data = 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()
reqOpts.data = '[form]'
break
default:
if (source.postData.text) {
reqOpts.data = source.postData.text
}
}
code.push('const options = %s;', stringifyObject(reqOpts, { indent: ' ', inlineCharacterLimit: 80 }).replace('"[form]"', 'form'))
.blank()
code.push(util.format('axios.request(options).then(%s', 'function (response) {'))
.push(1, 'console.log(response.data);')
.push('}).catch(%s', 'function (error) {')
.push(1, 'console.error(error);')
.push('});')
return code.join()
}
module.exports.info = {
key: 'axios',
title: 'Axios',
link: 'https://github.com/axios/axios',
description: 'Promise based HTTP client for the browser and node.js'
}