-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
69 lines (62 loc) · 1.57 KB
/
index.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
const request = require('request-promise')
const line0Regex = /^([A-z]+) ([\S]+)/
module.exports = function (strings, ...values) {
var params, headers, body
try {
// split out the lines
const lines = String.raw(strings, ...values).trim().split('\n')
// separate the header and body lines
const line0 = lines.shift()
var headerLines = []
var bodyLines = []
var isConsumingHeaders = true
lines.forEach(line => {
if (!line.trim()) {
isConsumingHeaders = false
return
}
if (isConsumingHeaders) {
headerLines.push(line)
} else {
bodyLines.push(line.trim())
}
})
// parse
params = parseLine0(line0)
headers = parseHeaders(headerLines)
if (bodyLines.length > 0) body = bodyLines.join('\n')
} catch (err) {
return Promise.reject(err)
}
var opts = {
resolveWithFullResponse: true,
simple: false,
url: params.url,
method: params.method,
headers
}
if (body) opts.body = body
return request(opts)
}
function parseLine0 (str) {
try {
const match = line0Regex.exec(str)
return {
method: match[1],
url: match[2]
}
} catch (e) {
throw new Error(`Parse error: ${str} is invalid, must be "{METHOD} {URL}". ${e.toString()}`)
}
}
function parseHeaders (lines) {
var headers = {}
lines.forEach(line => {
var parts = line.split(':')
if (parts.length <= 1) {
throw new Error(`Parsing error: ${line} is not a valid header K/V`)
}
headers[parts[0].trim()] = parts.slice(1).join(':').trim()
})
return headers
}