-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathnative.js
More file actions
86 lines (73 loc) · 2.25 KB
/
native.js
File metadata and controls
86 lines (73 loc) · 2.25 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
/**
* @description
* HTTP code snippet generator for native Node.js.
*
* @author
* @AhmadNassri
*
* for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
*/
'use strict'
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)
const reqOpts = {
method: source.method,
hostname: source.uriObj.hostname,
port: source.uriObj.port,
path: source.uriObj.path,
headers: source.allHeaders
}
code.push('const http = require("%s");', source.uriObj.protocol.replace(':', ''))
code.blank()
.push('const options = %s;', JSON.stringify(reqOpts, null, opts.indent))
.blank()
.push('const req = http.request(options, function (res) {')
.push(1, 'const chunks = [];')
.blank()
.push(1, 'res.on("data", function (chunk) {')
.push(2, 'chunks.push(chunk);')
.push(1, '});')
.blank()
.push(1, 'res.on("end", function () {')
.push(2, 'const body = Buffer.concat(chunks);')
.push(2, 'console.log(body.toString());')
.push(1, '});')
.push('});')
.blank()
switch (source.postData.mimeType) {
case 'application/x-www-form-urlencoded':
if (source.postData.paramsObj) {
code.unshift('const qs = require("querystring");')
code.push('req.write(qs.stringify(%s));', stringifyObject(source.postData.paramsObj, {
indent: ' ',
inlineCharacterLimit: 80
}))
}
break
case 'application/json':
if (source.postData.jsonObj) {
code.push('req.write(JSON.stringify(%s));', stringifyObject(source.postData.jsonObj, {
indent: ' ',
inlineCharacterLimit: 80
}))
}
break
default:
if (source.postData.text) {
code.push('req.write(%s);', JSON.stringify(source.postData.text, null, opts.indent))
}
}
code.push('req.end();')
return code.join()
}
module.exports.info = {
key: 'native',
title: 'HTTP',
link: 'http://nodejs.org/api/http.html#http_http_request_options_callback',
description: 'Node.js native HTTP interface'
}