Skip to content

Commit bf781be

Browse files
committed
chore: convert each target to CodeBuilder + docs
1 parent 9883fd4 commit bf781be

16 files changed

Lines changed: 226 additions & 202 deletions

File tree

src/helpers/code-builder.js

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,30 @@
11
'use strict'
22

3+
/**
4+
* Helper object to format and aggragate lines of code.
5+
* Lines are aggregated in a `code` array, and need to be joined to obtain a proper code snippet.
6+
*
7+
* @class
8+
*
9+
* @param {string} indentation Desired indentation character for aggregated lines of code
10+
* @param {string} join Desired character to join each line of code
11+
*/
312
var CodeBuilder = function (indentation, join) {
413
this.code = []
514
this.indentation = indentation
615
this.lineJoin = join ? join : '\n'
716
}
817

9-
CodeBuilder.prototype.buildLine = function (indentationLevel, str) {
18+
/**
19+
* Add given indentation level to given string
20+
* @param {number} [indentationLevel=0] Desired level of indentation for this line
21+
* @param {string} line Line of code
22+
* @return {string}
23+
*/
24+
CodeBuilder.prototype.buildLine = function (indentationLevel, line) {
1025
var lineIndentation = ''
1126
if (Object.prototype.toString.call(indentationLevel) === '[object String]') {
12-
str = indentationLevel
27+
line = indentationLevel
1328
indentationLevel = 0
1429
} else if (indentationLevel === null) {
1530
return null
@@ -20,27 +35,47 @@ CodeBuilder.prototype.buildLine = function (indentationLevel, str) {
2035
indentationLevel--
2136
}
2237

23-
return lineIndentation + str
38+
return lineIndentation + line
2439
}
2540

41+
/**
42+
* Add a line at the top of current lines with given indentation level
43+
* @param {number} [indentationLevel=0] Desired level of indentation for this line
44+
* @param {string} line Line of code
45+
* @return {this}
46+
*/
2647
CodeBuilder.prototype.unshift = function (indentationLevel, str) {
2748
this.code.unshift(this.buildLine(indentationLevel, str))
2849

2950
return this
3051
}
3152

53+
/**
54+
* Add a line at the end of current lines with given indentation level
55+
* @param {number} [indentationLevel=0] Desired level of indentation for this line
56+
* @param {string} line Line of code
57+
* @return {this}
58+
*/
3259
CodeBuilder.prototype.push = function (indentationLevel, str) {
3360
this.code.push(this.buildLine(indentationLevel, str))
3461

3562
return this
3663
}
3764

65+
/**
66+
* Add an empty line at the end of current lines
67+
* @return {this}
68+
*/
3869
CodeBuilder.prototype.blank = function () {
3970
this.code.push(null)
4071

4172
return this
4273
}
4374

75+
/**
76+
* Concatenate all current lines using the given lineJoin
77+
* @return {string}
78+
*/
4479
CodeBuilder.prototype.join = function () {
4580
return this.code.join(this.lineJoin)
4681
}

src/targets/go/native.js

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ var CodeBuilder = require('../../helpers/code-builder')
1515

1616
module.exports = function (source, options) {
1717
// Let's Go!
18-
var code = new CodeBuilder()
18+
var code = new CodeBuilder('\t')
1919

2020
// Define Options
2121
var opts = util._extend({
@@ -29,85 +29,87 @@ module.exports = function (source, options) {
2929
var errorCheck = function () {
3030
if (opts.checkErrors) {
3131
code.push('\tif err != nil {')
32-
code.push('\t\tpanic(err)')
33-
code.push('\t}')
32+
.push('\t\tpanic(err)')
33+
.push('\t}')
3434
}
3535
}
3636

3737
// Create boilerplate
3838
code.push('package main\n')
39-
code.push('import (')
40-
code.push('\t"fmt"')
39+
.push('import (')
40+
.push(1, '"fmt"')
4141

4242
if (opts.timeout > 0) {
43-
code.push('\t"time"')
43+
code.push(1, '"time"')
4444
}
4545

4646
if (source.postData.text) {
47-
code.push('\t"strings"')
47+
code.push(1, '"strings"')
4848
}
4949

50-
code.push('\t"net/http"')
50+
code.push(1, '"net/http"')
5151

5252
if (opts.printBody) {
53-
code.push('\t"io/ioutil"')
53+
code.push(1, '"io/ioutil"')
5454
}
5555

5656
code.push(')\n')
57-
58-
code.push('func main() {\n')
57+
.push('func main() {\n')
5958

6059
// Create client
6160
var client
6261
if (opts.timeout > 0) {
6362
client = 'client'
64-
code.push('\tclient := http.Client{')
65-
code.push(util.format('\t\tTimeout: time.Duration(%s * time.Second),', opts.timeout))
66-
code.push('\t}\n')
63+
code.push(1, 'client := http.Client{')
64+
.push(2, util.format('Timeout: time.Duration(%s * time.Second),', opts.timeout))
65+
.push(1, '}\n')
6766
} else {
6867
client = 'http.DefaultClient'
6968
}
7069

71-
code.push(util.format('\turl := "%s"\n', source.fullUrl))
70+
code.push(1, util.format('url := "%s"\n', source.fullUrl))
7271

7372
// If we have body content or not create the var and reader or nil
7473
if (source.postData.text) {
75-
code.push(util.format('\tpayload := strings.NewReader(%s)\n', JSON.stringify(source.postData.text)))
76-
code.push(util.format('\treq, %s := http.NewRequest("%s", url, payload)\n', errorPlaceholder, source.method))
74+
code.push(1, util.format('payload := strings.NewReader(%s)\n', JSON.stringify(source.postData.text)))
75+
.push(1, util.format('req, %s := http.NewRequest("%s", url, payload)\n', errorPlaceholder, source.method))
7776
} else {
78-
code.push(util.format('\treq, %s := http.NewRequest("%s", url, nil)\n', errorPlaceholder, source.method))
77+
code.push(1, util.format('req, %s := http.NewRequest("%s", url, nil)\n', errorPlaceholder, source.method))
7978
}
8079

8180
errorCheck()
8281

8382
// Add headers
8483
if (Object.keys(source.allHeaders).length) {
8584
Object.keys(source.allHeaders).map(function (key) {
86-
code.push(util.format('\treq.Header.Add("%s", "%s")', key, source.allHeaders[key]))
85+
code.push(1, util.format('req.Header.Add("%s", "%s")', key, source.allHeaders[key]))
8786
})
88-
code.push(null)
87+
code.blank()
8988
}
9089

9190
// Make request
92-
code.push(util.format('\tres, %s := %s.Do(req)', errorPlaceholder, client))
91+
code.push(1, util.format('res, %s := %s.Do(req)', errorPlaceholder, client))
9392
errorCheck()
9493

9594
// Get Body
9695
if (opts.printBody) {
97-
code.push('\n\tdefer res.Body.Close()')
98-
code.push(util.format('\tbody, %s := ioutil.ReadAll(res.Body)', errorPlaceholder))
96+
code.blank()
97+
.push(1, 'defer res.Body.Close()')
98+
.push(1, util.format('body, %s := ioutil.ReadAll(res.Body)', errorPlaceholder))
9999
errorCheck()
100100
}
101101

102102
// Print it
103-
code.push('\n\tfmt.Println(res)')
103+
code.blank()
104+
.push(1, 'fmt.Println(res)')
104105

105106
if (opts.printBody) {
106-
code.push('\tfmt.Println(string(body))')
107+
code.push(1, 'fmt.Println(string(body))')
107108
}
108109

109110
// End main block
110-
code.push('\n}')
111+
code.blank()
112+
.push('}')
111113

112114
return code.join()
113115
}

src/targets/java/unirest.js

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@
1313
var util = require('util')
1414
var CodeBuilder = require('../../helpers/code-builder')
1515

16-
module.exports = function (options) {
17-
var self = this
16+
module.exports = function (source, options) {
1817
var opts = util._extend({
1918
indent: ' '
2019
}, options)
@@ -23,24 +22,24 @@ module.exports = function (options) {
2322

2423
var methods = [ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS' ]
2524

26-
if (methods.indexOf(self.source.method.toUpperCase()) === -1) {
27-
code.push(util.format('HttpResponse<String> response = Unirest.customMethod("%s","%s")', self.source.method.toUpperCase(), self.source.fullUrl))
25+
if (methods.indexOf(source.method.toUpperCase()) === -1) {
26+
code.push(util.format('HttpResponse<String> response = Unirest.customMethod("%s","%s")', source.method.toUpperCase(), source.fullUrl))
2827
} else {
29-
code.push(util.format('HttpResponse<String> response = Unirest.%s("%s")', self.source.method.toLowerCase(), self.source.fullUrl))
28+
code.push(util.format('HttpResponse<String> response = Unirest.%s("%s")', source.method.toLowerCase(), source.fullUrl))
3029
}
3130

3231
// Add headers, including the cookies
33-
var headers = Object.keys(self.source.allHeaders)
32+
var headers = Object.keys(source.allHeaders)
3433

3534
// construct headers
3635
if (headers.length) {
3736
headers.map(function (key) {
38-
code.push(1, util.format('.header("%s", "%s")', key, self.source.allHeaders[key]))
37+
code.push(1, util.format('.header("%s", "%s")', key, source.allHeaders[key]))
3938
})
4039
}
4140

42-
if (self.source.postData.text) {
43-
code.push(1, util.format('.body(%s)', JSON.stringify(self.source.postData.text)))
41+
if (source.postData.text) {
42+
code.push(1, util.format('.body(%s)', JSON.stringify(source.postData.text)))
4443
}
4544

4645
code.push(1, '.asString();')

src/targets/javascript/jquery.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ module.exports = function (source, options) {
5454
if (~settings.headers['content-type'].indexOf('boundary')) {
5555
delete settings.headers['content-type']
5656
}
57-
code.push(null)
57+
code.blank()
5858
break
5959

6060
default:
@@ -64,10 +64,10 @@ module.exports = function (source, options) {
6464
}
6565

6666
code.push('var settings = ' + JSON.stringify(settings, null, opts.indent).replace('"[form]"', 'form'))
67-
68-
code.push(null)
69-
70-
code.push('$.ajax(settings).done(function (response) {\n\tconsole.log(response);\n});'.replace(/\t/g, opts.indent))
67+
.blank()
68+
.push('$.ajax(settings).done(function (response) {')
69+
.push(1, 'console.log(response);')
70+
.push('});')
7171

7272
return code.join()
7373
}

src/targets/javascript/xhr.js

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ module.exports = function (source, options) {
2424
switch (source.postData.mimeType) {
2525
case 'application/json':
2626
code.push(util.format('var data = JSON.stringify(%s);', JSON.stringify(source.postData.jsonObj, null, opts.indent)))
27-
code.push(null)
27+
.push(null)
2828
break
2929

3030
case 'multipart/form-data':
@@ -39,12 +39,12 @@ module.exports = function (source, options) {
3939
delete source.allHeaders['content-type']
4040
}
4141

42-
code.push(null)
42+
code.blank()
4343
break
4444

4545
default:
4646
code.push(util.format('var data = %s;', JSON.stringify(source.postData.text || null)))
47-
code.push(null)
47+
.blank()
4848
}
4949

5050
code.push('var xhr = new XMLHttpRequest();')
@@ -53,21 +53,21 @@ module.exports = function (source, options) {
5353
code.push('xhr.withCredentials = true;')
5454
}
5555

56-
code.push(null)
57-
58-
code.push('xhr.addEventListener("readystatechange", function () {\n\tif (this.readyState === this.DONE) {\n\t\tconsole.log(this.responseText);\n\t}\n});'.replace(/\t/g, opts.indent))
59-
60-
code.push(null)
61-
62-
code.push(util.format('xhr.open(%s, %s);', JSON.stringify(source.method), JSON.stringify(source.fullUrl)))
56+
code.blank()
57+
.push('xhr.addEventListener("readystatechange", function () {')
58+
.push(1, 'if (this.readyState === this.DONE) {')
59+
.push(2, 'console.log(this.responseText);')
60+
.push(1, '}')
61+
.push('});')
62+
.blank()
63+
.push(util.format('xhr.open(%s, %s);', JSON.stringify(source.method), JSON.stringify(source.fullUrl)))
6364

6465
Object.keys(source.allHeaders).map(function (key) {
6566
code.push(util.format('xhr.setRequestHeader(%s, %s);', JSON.stringify(key), JSON.stringify(source.allHeaders[key])))
6667
})
6768

68-
code.push(null)
69-
70-
code.push('xhr.send(data);')
69+
code.blank()
70+
.push('xhr.send(data);')
7171

7272
return code.join()
7373
}

src/targets/node/native.js

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -34,31 +34,22 @@ module.exports = function (source, options) {
3434
code.push('var querystring = require("querystring");')
3535
}
3636

37-
code.push(null)
38-
39-
code.push(util.format('var options = %s;', JSON.stringify(reqOpts, null, opts.indent)))
40-
41-
code.push(null)
42-
43-
code.push('var req = http.request(options, function (res) {')
44-
45-
code.push(1, 'var chunks = [];')
46-
47-
code.push(null)
48-
49-
code.push(1, 'res.on("data", function (chunk) {')
50-
code.push(2, 'chunks.push(chunk);')
51-
code.push(1, '});')
52-
53-
code.push(null)
54-
55-
code.push(opts.indent + 'res.on("end", function () {')
56-
code.push(opts.indent + opts.indent + 'var body = Buffer.concat(chunks);')
57-
code.push(opts.indent + opts.indent + 'console.log(body.toString());')
58-
code.push(opts.indent + '});')
59-
code.push('});')
60-
61-
code.push(null)
37+
code.blank()
38+
.push(util.format('var options = %s;', JSON.stringify(reqOpts, null, opts.indent)))
39+
.blank()
40+
.push('var req = http.request(options, function (res) {')
41+
.push(1, 'var chunks = [];')
42+
.blank()
43+
.push(1, 'res.on("data", function (chunk) {')
44+
.push(2, 'chunks.push(chunk);')
45+
.push(1, '});')
46+
.blank()
47+
.push(1, 'res.on("end", function () {')
48+
.push(2, 'var body = Buffer.concat(chunks);')
49+
.push(2, 'console.log(body.toString());')
50+
.push(1, '});')
51+
.push('});')
52+
.blank()
6253

6354
if (source.postData.text) {
6455
code.push(util.format('req.write(%s);', JSON.stringify(source.postData.text)))

0 commit comments

Comments
 (0)