WIP: initial prototype

- Added error parameter to request and response event
- Dropped error event
- Updated typescript indentation
This commit is contained in:
delvedor
2018-12-05 22:16:16 +01:00
parent 7e35f6a903
commit aa5977b153
8 changed files with 202 additions and 204 deletions

1
index.d.ts vendored
View File

@ -466,7 +466,6 @@ declare class Client extends EventEmitter {
declare const events: {
RESPONSE: string;
REQUEST: string;
ERROR: string;
SNIFF: string;
};

View File

@ -23,12 +23,6 @@ class Client extends EventEmitter {
this.on('error', console.log)
}
// The logging is exposed via events, which the user can
// listen to and log the message its preferred way
// we add a fake listener to the error event to avoid
// the "unhandled error event" error.
this.on('error', () => {})
const options = Object.assign({}, {
Connection,
ConnectionPool,
@ -95,7 +89,6 @@ class Client extends EventEmitter {
const events = {
RESPONSE: 'response',
REQUEST: 'request',
ERROR: 'error',
SNIFF: 'sniff'
}

View File

@ -99,7 +99,7 @@ class Transport {
params.timeout = toMs(params.requestTimeout || this.requestTimeout)
meta.request = params
this.emit('request', meta)
this.emit('request', null, meta)
// perform the actual http request
return meta.connection.request(params, onResponse)
@ -127,7 +127,7 @@ class Transport {
? err
: new ConnectionError(err.message, params)
this.emit('error', error, meta)
this.emit('response', error, meta)
return callback(error, result)
}
@ -142,7 +142,7 @@ class Transport {
if (params.asStream === true) {
result.body = response
meta.response = result
this.emit('response', meta)
this.emit('response', null, meta)
callback(null, result)
return
}
@ -151,7 +151,11 @@ class Transport {
// collect the payload
response.setEncoding('utf8')
response.on('data', chunk => { payload += chunk })
response.on('error', err => callback(new ConnectionError(err.message, params), result))
response.on('error', err => {
const error = new ConnectionError(err.message, params)
this.emit('response', error, meta)
callback(error, result)
})
response.on('end', () => {
const isHead = params.method === 'HEAD'
// we should attempt the payload deserialization only if:
@ -166,7 +170,7 @@ class Transport {
try {
result.body = this.serializer.deserialize(payload)
} catch (err) {
this.emit('error', err, meta)
this.emit('response', err, meta)
return callback(err, result)
}
} else {
@ -198,14 +202,16 @@ class Transport {
}
meta.response = result
this.emit('response', meta)
if (ignoreStatusCode === false && statusCode >= 400) {
callback(new ResponseError(result), result)
const error = new ResponseError(result)
this.emit('response', error, meta)
callback(error, result)
} else {
// cast to boolean if the request method was HEAD
if (isHead === true && statusCode === 404) {
result.body = false
}
this.emit('response', null, meta)
callback(null, result)
}
})