Skip to content

Commit

Permalink
Merge d75c9f8 into 9f4b0dc
Browse files Browse the repository at this point in the history
  • Loading branch information
JacksonTian committed May 28, 2019
2 parents 9f4b0dc + d75c9f8 commit 9e65965
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 7 deletions.
19 changes: 19 additions & 0 deletions lib/index.d.ts
@@ -0,0 +1,19 @@
import { IncomingMessage, Agent, OutgoingHttpHeaders } from "http";

export interface Options {
'method'?: string;
'headers'?: {[key: string]: string};
'readTimeout'?: number;
'connectTimeout'?: number;
'timeout'?: number;
'agent'?: Agent;
'headers'?: OutgoingHttpHeaders;
'rejectUnauthorized'?: boolean;
'compression'?: boolean;
'beforeRequest'?(options: Options): void;
'data'?: string|Buffer|undefined;
}

export function request<T>(url: string, options: Options): Promise<IncomingMessage>;

export function read(response: IncomingMessage, encoding: string): Promise<string|Buffer>;
16 changes: 10 additions & 6 deletions lib/index.js
Expand Up @@ -108,7 +108,10 @@ exports.request = function (url, opts) {

const startResponseTimer = function (socket) {
const timer = setTimeout(() => {
socket[READ_TIMER] = null;
if (socket[READ_TIMER]) {
clearTimeout(socket[READ_TIMER]);
socket[READ_TIMER] = null;
}
var err = new Error();
var message = `ReadTimeout(${readTimeout})`;
abort(append(err, 'RequestTimeout', message));
Expand Down Expand Up @@ -159,27 +162,28 @@ exports.read = function (response, encoding) {
}

return new Promise((resolve, reject) => {
const makeReadTimeoutError = (err) => {
const makeReadTimeoutError = () => {
const req = response.req;
var err = new Error();
err.name = 'RequestTimeoutError';
err.message = `ReadTimeout: ${response.socket[READ_TIME_OUT]}. ${req.method} ${req.path} failed.`;
return err;
}
};
// check read-timer
let readTimer;
const oldReadTimer = response.socket[READ_TIMER];
if (!oldReadTimer) {
reject(makeReadTimeoutError(new Error()));
reject(makeReadTimeoutError());
return;
}
const remainTime = response.socket[READ_TIME_OUT] - (Date.now() - oldReadTimer.startTime);
clearTimeout(oldReadTimer);
if (remainTime <= 0) {
reject(makeReadTimeoutError(new Error()));
reject(makeReadTimeoutError());
return;
}
readTimer = setTimeout(function () {
reject(makeReadTimeoutError(new Error()));
reject(makeReadTimeoutError());
}, remainTime);

// start reading data
Expand Down
4 changes: 3 additions & 1 deletion package.json
Expand Up @@ -3,6 +3,7 @@
"version": "2.1.4",
"description": "http(s) module with power",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"scripts": {
"lint": "eslint --fix lib",
"test": "mocha --reporter spec --timeout 3000 test/*.test.js",
Expand All @@ -26,7 +27,8 @@
"nyc": "^12.0.2"
},
"dependencies": {
"debug": "^2.2.0"
"@types/node": "^12.0.2",
"debug": "^4.1.1"
},
"files": [
"lib"
Expand Down

0 comments on commit 9e65965

Please sign in to comment.