Skip to content

Commit f022d05

Browse files
committed
Add Javascript Axios target
1 parent e026327 commit f022d05

File tree

2 files changed

+91
-1
lines changed

2 files changed

+91
-1
lines changed

src/targets/javascript/axios.js

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/**
2+
* @description
3+
* HTTP code snippet generator for Javascript & Node.js using Axios.
4+
*
5+
* @author
6+
* @rohit-gohri
7+
*
8+
* for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
9+
*/
10+
'use strict'
11+
12+
var util = require('util')
13+
var stringifyObject = require('stringify-object')
14+
var CodeBuilder = require('../../helpers/code-builder')
15+
16+
module.exports = function (source, options) {
17+
var opts = Object.assign({
18+
indent: ' '
19+
}, options)
20+
21+
var code = new CodeBuilder(opts.indent)
22+
23+
code.push('import axios from "axios";')
24+
.blank()
25+
26+
var reqOpts = {
27+
method: source.method,
28+
url: source.url
29+
}
30+
31+
if (Object.keys(source.queryObj).length) {
32+
reqOpts.params = source.queryObj
33+
}
34+
35+
if (Object.keys(source.allHeaders).length) {
36+
reqOpts.headers = source.allHeaders
37+
}
38+
39+
switch (source.postData.mimeType) {
40+
case 'application/x-www-form-urlencoded':
41+
reqOpts.data = source.postData.paramsObj
42+
break
43+
44+
case 'application/json':
45+
if (source.postData.jsonObj) {
46+
reqOpts.data = source.postData.jsonObj
47+
}
48+
break
49+
50+
case 'multipart/form-data':
51+
code.push('const form = new FormData();')
52+
53+
source.postData.params.forEach(function (param) {
54+
code.push(
55+
'form.append(%s, %s);',
56+
JSON.stringify(param.name),
57+
JSON.stringify(param.value || param.fileName || '')
58+
)
59+
})
60+
61+
code.blank()
62+
63+
reqOpts.data = '[form]'
64+
break
65+
66+
default:
67+
if (source.postData.text) {
68+
reqOpts.data = source.postData.text
69+
}
70+
}
71+
72+
code.push('const options = %s;', stringifyObject(reqOpts, { indent: ' ', inlineCharacterLimit: 80 }).replace('"[form]"', 'form'))
73+
.blank()
74+
75+
code.push(util.format('axios.request(options).then(%s', 'function (response) {'))
76+
.push(1, 'console.log(response.data);')
77+
.push('}).catch(%s', 'function (error) {')
78+
.push(1, 'console.error(error);')
79+
.push('});')
80+
81+
return code.join()
82+
}
83+
84+
module.exports.info = {
85+
key: 'axios',
86+
title: 'Axios',
87+
link: 'https://github.com/axios/axios',
88+
description: 'Promise based HTTP client for the browser and node.js'
89+
}

src/targets/javascript/index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,6 @@ module.exports = {
1010

1111
jquery: require('./jquery'),
1212
fetch: require('./fetch'),
13-
xhr: require('./xhr')
13+
xhr: require('./xhr'),
14+
axios: require('./axios')
1415
}

0 commit comments

Comments
 (0)