Skip to content

Commit 3a30a5d

Browse files
committed
Merge pull request Kong#48 from Mashape/chore/code-builder
Chore/code builder
2 parents 69efbe7 + bf781be commit 3a30a5d

18 files changed

Lines changed: 333 additions & 239 deletions

File tree

‎src/helpers/code-builder.js‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
'use strict'
2+
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+
*/
12+
var CodeBuilder = function (indentation, join) {
13+
this.code = []
14+
this.indentation = indentation
15+
this.lineJoin = join ? join : '\n'
16+
}
17+
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) {
25+
var lineIndentation = ''
26+
if (Object.prototype.toString.call(indentationLevel) === '[object String]') {
27+
line = indentationLevel
28+
indentationLevel = 0
29+
} else if (indentationLevel === null) {
30+
return null
31+
}
32+
33+
while (indentationLevel) {
34+
lineIndentation += this.indentation
35+
indentationLevel--
36+
}
37+
38+
return lineIndentation + line
39+
}
40+
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+
*/
47+
CodeBuilder.prototype.unshift = function (indentationLevel, str) {
48+
this.code.unshift(this.buildLine(indentationLevel, str))
49+
50+
return this
51+
}
52+
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+
*/
59+
CodeBuilder.prototype.push = function (indentationLevel, str) {
60+
this.code.push(this.buildLine(indentationLevel, str))
61+
62+
return this
63+
}
64+
65+
/**
66+
* Add an empty line at the end of current lines
67+
* @return {this}
68+
*/
69+
CodeBuilder.prototype.blank = function () {
70+
this.code.push(null)
71+
72+
return this
73+
}
74+
75+
/**
76+
* Concatenate all current lines using the given lineJoin
77+
* @return {string}
78+
*/
79+
CodeBuilder.prototype.join = function () {
80+
return this.code.join(this.lineJoin)
81+
}
82+
83+
module.exports = CodeBuilder

‎src/targets/go/native.js‎

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,11 @@
1111
'use strict'
1212

1313
var util = require('util')
14+
var CodeBuilder = require('../../helpers/code-builder')
1415

1516
module.exports = function (source, options) {
1617
// Let's Go!
17-
var code = []
18+
var code = new CodeBuilder('\t')
1819

1920
// Define Options
2021
var opts = util._extend({
@@ -28,87 +29,89 @@ module.exports = function (source, options) {
2829
var errorCheck = function () {
2930
if (opts.checkErrors) {
3031
code.push('\tif err != nil {')
31-
code.push('\t\tpanic(err)')
32-
code.push('\t}')
32+
.push('\t\tpanic(err)')
33+
.push('\t}')
3334
}
3435
}
3536

3637
// Create boilerplate
3738
code.push('package main\n')
38-
code.push('import (')
39-
code.push('\t"fmt"')
39+
.push('import (')
40+
.push(1, '"fmt"')
4041

4142
if (opts.timeout > 0) {
42-
code.push('\t"time"')
43+
code.push(1, '"time"')
4344
}
4445

4546
if (source.postData.text) {
46-
code.push('\t"strings"')
47+
code.push(1, '"strings"')
4748
}
4849

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

5152
if (opts.printBody) {
52-
code.push('\t"io/ioutil"')
53+
code.push(1, '"io/ioutil"')
5354
}
5455

5556
code.push(')\n')
56-
57-
code.push('func main() {\n')
57+
.push('func main() {\n')
5858

5959
// Create client
6060
var client
6161
if (opts.timeout > 0) {
6262
client = 'client'
63-
code.push('\tclient := http.Client{')
64-
code.push(util.format('\t\tTimeout: time.Duration(%s * time.Second),', opts.timeout))
65-
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')
6666
} else {
6767
client = 'http.DefaultClient'
6868
}
6969

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

7272
// If we have body content or not create the var and reader or nil
7373
if (source.postData.text) {
74-
code.push(util.format('\tpayload := strings.NewReader(%s)\n', JSON.stringify(source.postData.text)))
75-
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))
7676
} else {
77-
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))
7878
}
7979

8080
errorCheck()
8181

8282
// Add headers
8383
if (Object.keys(source.allHeaders).length) {
8484
Object.keys(source.allHeaders).map(function (key) {
85-
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]))
8686
})
87-
code.push(null)
87+
code.blank()
8888
}
8989

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

9494
// Get Body
9595
if (opts.printBody) {
96-
code.push('\n\tdefer res.Body.Close()')
97-
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))
9899
errorCheck()
99100
}
100101

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

104106
if (opts.printBody) {
105-
code.push('\tfmt.Println(string(body))')
107+
code.push(1, 'fmt.Println(string(body))')
106108
}
107109

108110
// End main block
109-
code.push('\n}')
111+
code.blank()
112+
.push('}')
110113

111-
return code.join('\n')
114+
return code.join()
112115
}
113116

114117
module.exports.info = {

‎src/targets/java/unirest.js‎

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,39 +11,40 @@
1111
'use strict'
1212

1313
var util = require('util')
14+
var CodeBuilder = require('../../helpers/code-builder')
1415

15-
module.exports = function (options) {
16-
var self = this
16+
module.exports = function (source, options) {
1717
var opts = util._extend({
1818
indent: ' '
1919
}, options)
2020

21-
var code = []
21+
var code = new CodeBuilder(opts.indent)
2222

2323
var methods = [ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS' ]
2424

25-
if (methods.indexOf(self.source.method.toUpperCase()) === -1) {
26-
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))
2727
} else {
28-
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))
2929
}
3030

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

3434
// construct headers
3535
if (headers.length) {
3636
headers.map(function (key) {
37-
code.push(opts.indent + util.format('.header("%s", "%s")', key, self.source.allHeaders[key]))
37+
code.push(1, util.format('.header("%s", "%s")', key, source.allHeaders[key]))
3838
})
3939
}
4040

41-
if (self.source.postData.text) {
42-
code.push(opts.indent + 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)))
4343
}
4444

45-
code.push(opts.indent + '.asString();')
46-
return code.join('\n')
45+
code.push(1, '.asString();')
46+
47+
return code.join()
4748
}
4849

4950
module.exports.info = {

‎src/targets/javascript/jquery.js‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,14 @@
1111
'use strict'
1212

1313
var util = require('util')
14+
var CodeBuilder = require('../../helpers/code-builder')
1415

1516
module.exports = function (source, options) {
1617
var opts = util._extend({
1718
indent: ' '
1819
}, options)
1920

20-
var code = []
21+
var code = new CodeBuilder(opts.indent)
2122

2223
var settings = {
2324
async: true,
@@ -53,7 +54,7 @@ module.exports = function (source, options) {
5354
if (~settings.headers['content-type'].indexOf('boundary')) {
5455
delete settings.headers['content-type']
5556
}
56-
code.push(null)
57+
code.blank()
5758
break
5859

5960
default:
@@ -63,12 +64,12 @@ module.exports = function (source, options) {
6364
}
6465

6566
code.push('var settings = ' + JSON.stringify(settings, null, opts.indent).replace('"[form]"', 'form'))
67+
.blank()
68+
.push('$.ajax(settings).done(function (response) {')
69+
.push(1, 'console.log(response);')
70+
.push('});')
6671

67-
code.push(null)
68-
69-
code.push('$.ajax(settings).done(function (response) {\n\tconsole.log(response);\n});'.replace(/\t/g, opts.indent))
70-
71-
return code.join('\n')
72+
return code.join()
7273
}
7374

7475
module.exports.info = {

‎src/targets/javascript/xhr.js‎

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,20 @@
1111
'use strict'
1212

1313
var util = require('util')
14+
var CodeBuilder = require('../../helpers/code-builder')
1415

1516
module.exports = function (source, options) {
1617
var opts = util._extend({
1718
indent: ' ',
1819
cors: true
1920
}, options)
2021

21-
var code = []
22+
var code = new CodeBuilder(opts.indent)
2223

2324
switch (source.postData.mimeType) {
2425
case 'application/json':
2526
code.push(util.format('var data = JSON.stringify(%s);', JSON.stringify(source.postData.jsonObj, null, opts.indent)))
26-
code.push(null)
27+
.push(null)
2728
break
2829

2930
case 'multipart/form-data':
@@ -38,12 +39,12 @@ module.exports = function (source, options) {
3839
delete source.allHeaders['content-type']
3940
}
4041

41-
code.push(null)
42+
code.blank()
4243
break
4344

4445
default:
4546
code.push(util.format('var data = %s;', JSON.stringify(source.postData.text || null)))
46-
code.push(null)
47+
.blank()
4748
}
4849

4950
code.push('var xhr = new XMLHttpRequest();')
@@ -52,23 +53,23 @@ module.exports = function (source, options) {
5253
code.push('xhr.withCredentials = true;')
5354
}
5455

55-
code.push(null)
56-
57-
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))
58-
59-
code.push(null)
60-
61-
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)))
6264

6365
Object.keys(source.allHeaders).map(function (key) {
6466
code.push(util.format('xhr.setRequestHeader(%s, %s);', JSON.stringify(key), JSON.stringify(source.allHeaders[key])))
6567
})
6668

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

71-
return code.join('\n')
72+
return code.join()
7273
}
7374

7475
module.exports.info = {

0 commit comments

Comments
 (0)