UNPKG

amazon-sp-api-node8

Version:

Amazon Selling Partner API client for Node version 8x

70 lines (63 loc) 2.07 kB
const CustomError = require("./CustomError"); class TimeoutManager { constructor({ response, idle, deadline } = {}) { this._req = null; this._response = response; this._idle = idle; this._deadline = deadline; this._timeouts = {}; this._setTimeout = { response: () => { return setTimeout(() => { this._req.destroy( new CustomError({ code: "API_RESPONSE_TIMEOUT", message: `No data received within specified response timeout (${this._response}ms).`, timeout: this._response, }) ); }, this._response); }, deadline: () => { return setTimeout(() => { this._req.destroy( new CustomError({ code: "API_DEADLINE_TIMEOUT", message: `Response was not completely received within specified deadline timeout (${this._deadline}ms).`, timeout: this._deadline, }) ); }, this._deadline); }, idle: () => { return setTimeout(() => { this._req.destroy( new CustomError({ code: "API_IDLE_TIMEOUT", message: `Next chunk of response was not received within specified idle timeout (${this._idle}ms).`, timeout: this._idle, }) ); }, this._idle); } }; } init(req) { this._req = req; if (this._response) this._timeouts.response = this._setTimeout.response(); if (this._deadline) this._timeouts.deadline = this._setTimeout.deadline(); } onResData() { if (this._timeouts.response) { clearTimeout(this._timeouts.response); delete this._timeouts.response; } if (this._timeouts.idle) clearTimeout(this._timeouts.idle); if (this._idle) this._timeouts.idle = this._setTimeout.idle(); } onResEnd() { if (this._timeouts.idle) clearTimeout(this._timeouts.idle); if (this._timeouts.deadline) clearTimeout(this._timeouts.deadline); } } module.exports = TimeoutManager;