2021-07-05 17:54:00 +00:00
|
|
|
import http from 'http'
|
|
|
|
import { URL } from 'url'
|
2021-10-09 00:12:56 +00:00
|
|
|
import { defaults } from './helper.mjs'
|
2021-07-05 17:54:00 +00:00
|
|
|
|
|
|
|
export default function Client(port, opts) {
|
|
|
|
this.options = defaults(opts, {})
|
|
|
|
this.prefix = `http://localhost:${port}`
|
|
|
|
}
|
|
|
|
|
|
|
|
Client.prototype.customRequest = function(method = 'GET', path, body, options) {
|
|
|
|
if (path.slice(0, 4) !== 'http') {
|
|
|
|
path = this.prefix + path
|
|
|
|
}
|
|
|
|
let urlObj = new URL(path)
|
|
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const opts = defaults(defaults(options, {
|
2021-10-09 00:12:56 +00:00
|
|
|
agent: false,
|
2021-07-05 17:54:00 +00:00
|
|
|
method: method,
|
|
|
|
timeout: 500,
|
|
|
|
protocol: urlObj.protocol,
|
|
|
|
username: urlObj.username,
|
|
|
|
password: urlObj.password,
|
|
|
|
host: urlObj.hostname,
|
|
|
|
port: Number(urlObj.port),
|
|
|
|
path: urlObj.pathname + urlObj.search,
|
|
|
|
}))
|
|
|
|
|
|
|
|
const req = http.request(opts)
|
|
|
|
if (body) {
|
|
|
|
req.write(body)
|
|
|
|
}
|
|
|
|
|
|
|
|
req.on('error', reject)
|
2021-10-09 00:12:56 +00:00
|
|
|
req.on('timeout', function() {
|
|
|
|
console.log(req.destroy())
|
|
|
|
reject(new Error(`Request ${method} ${path} timed out`))
|
|
|
|
})
|
2021-07-05 17:54:00 +00:00
|
|
|
req.on('response', res => {
|
|
|
|
res.setEncoding('utf8')
|
|
|
|
let output = ''
|
|
|
|
|
|
|
|
res.on('data', function (chunk) {
|
|
|
|
output += chunk.toString()
|
|
|
|
})
|
|
|
|
|
|
|
|
res.on('end', function () {
|
|
|
|
try {
|
|
|
|
output = JSON.parse(output)
|
|
|
|
} catch (e) {
|
|
|
|
return reject(new Error(`${e.message} while decoding: ${output}`))
|
|
|
|
}
|
2021-10-09 00:12:56 +00:00
|
|
|
if (output.status && typeof(output.status) === 'number') {
|
2021-07-05 17:54:00 +00:00
|
|
|
let err = new Error(`Request failed [${output.status}]: ${output.message}`)
|
|
|
|
err.body = output
|
|
|
|
return reject(err)
|
|
|
|
}
|
|
|
|
resolve(output)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
req.end()
|
2021-10-09 00:12:56 +00:00
|
|
|
return req
|
2021-07-05 17:54:00 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
Client.prototype.get = function(path = '/') {
|
|
|
|
return this.customRequest('GET', path, null)
|
|
|
|
}
|