-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy path_write.js
151 lines (129 loc) · 4.41 KB
/
_write.js
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
var qs = require('querystring')
var http = require('http')
var https = require('https')
var FormData = require('@brianleroux/form-data')
var url = require('url')
module.exports = function _write(httpMethod, options, callback) {
// deep copy options if no buffers being passed in
let formopts = options.data || options.body
let notplain = k => typeof formopts[k] != 'string'
let basic = formopts && Object.keys(formopts).some(notplain) === false
if (basic) {
options = JSON.parse(JSON.stringify(options))
}
// alias body = data
if (options.body && !options.data) {
options.data = options.body
}
// require options.url or fail noisily
if (!options.url) {
throw Error('options.url required')
}
// setup promise if there is no callback
var promise
if (!callback) {
promise = new Promise(function(res, rej) {
callback = function(err, result) {
err ? rej(err) : res(result)
}
})
}
// parse out the options from options.url
var opts = url.parse(options.url)
var method = opts.protocol === 'https:'? https.request : http.request
var defaultContentType = 'application/json; charset=utf-8'
// add timeout
if (options.timeout) {
opts.timeout = timeout
}
// wrangle defaults
opts.method = httpMethod
opts.headers = options.headers || {}
opts.headers['user-agent'] = opts.headers['user-agent'] || opts.headers['User-Agent'] || 'tiny-http'
opts.headers['content-type'] = opts.headers['content-type'] || opts.headers['Content-Type'] || defaultContentType
// default to regular POST body (url enc)
var postData = qs.stringify(options.data || {})
function is(headers, type) {
var regex = type instanceof RegExp
var upper = headers['Content-Type']
var lower = headers['content-type']
var isU = upper && (regex ? upper.match(type) : upper.startsWith(type))
var isL = lower && (regex ? lower.match(type) : lower.startsWith(type))
return isU || isL
}
// if we're posting JSON stringify options.data
var isJSON = is(opts.headers, /^application\/.*json/)
if (isJSON) {
postData = JSON.stringify(options.data || {})
}
// if we're doing a application/x-www-form-urlencoded to upload files
// we'll overload `method` and use the custom form-data submit instead of http.request
var isUrlEncoded = is(opts.headers, 'application/x-www-form-urlencoded')
if (isUrlEncoded) {
postData = Object.keys(options.data)
.map(k => `${encodeURI(k)}=${encodeURI(options.data[k])}`)
.join('&')
}
// ensure we know the len ~after~ we set the postData
opts.headers['Content-Length'] = Buffer.byteLength(postData)
// if we're doing a mutipart/form-data to upload files
// we'll overload `method` and use the custom form-data submit instead of http.request
var isMultipart = is(opts.headers, 'multipart/form-data')
if (isMultipart) {
method = function _multiPartFormDataPost(params, streamback) {
var form = new FormData
Object.keys(options.data).forEach(k=> {
form.append(k, options.data[k])
})
// remove stuff generated by form.submit
delete opts.headers['Content-Type']
delete opts.headers['content-type']
delete opts.headers['Content-Length']
delete opts.headers['content-length']
// perform a multipart/form-data POST request
form.submit(opts, function _submit(err, res) {
if (err) callback(err)
else streamback(res)
})
}
}
// make a request
var req = method(opts, function(res) {
var raw = [] // keep our buffers here
var ok = res.statusCode >= 200 && res.statusCode < 303
res.on('data', function _data(chunk) {
raw.push(chunk)
})
res.on('end', function _end() {
var err = null
var result = null
try {
result = Buffer.concat(raw)
if (!options.buffer) {
var isJSON = is(res.headers, /^application\/.*json/)
var strRes = result.toString()
result = strRes && isJSON ? JSON.parse(strRes) : strRes
}
}
catch (e) {
err = e
}
if (!ok) {
err = Error(httpMethod + ' failed with: ' + res.statusCode)
err.raw = res
err.body = result
err.statusCode = res.statusCode
callback(err)
}
else {
callback(err, {body:result, headers:res.headers})
}
})
})
if (!isMultipart) {
req.on('error', callback)
req.write(postData)
req.end()
}
return promise
}