UNPKG

@freemework/hosting

Version:

Hosting library of the Freemework Project.

62 lines 2.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FHttpRequestCancellationToken = void 0; const common_1 = require("@freemework/common"); class FHttpRequestCancellationToken { _onClientDisconnectBound; _cancelListeners = []; _request; _isCancellationRequested; constructor(request) { this._isCancellationRequested = false; this._onClientDisconnectBound = this._onClientDisconnect.bind(this); this._request = request; // According to https://nodejs.org/api/http.html // v16.0.0 The close event is now emitted when the request has been completed and not when the underlying socket is closed. // // So We switch to listen "close" event on underlying socket this._request.socket.on("close", this._onClientDisconnectBound); // this._request.on("end", this._onClientDisconnectBound); } get isCancellationRequested() { return this._isCancellationRequested; } addCancelListener(cb) { this._cancelListeners.push(cb); } removeCancelListener(cb) { const cbIndex = this._cancelListeners.indexOf(cb); if (cbIndex !== -1) { this._cancelListeners.splice(cbIndex, 1); } } throwIfCancellationRequested() { if (this.isCancellationRequested) { throw new common_1.FCancellationException(); } } _onClientDisconnect() { this._request.socket.removeListener("close", this._onClientDisconnectBound); // this._request.removeListener("end", this._onClientDisconnectBound); this._isCancellationRequested = true; let errors = null; if (this._cancelListeners.length > 0) { // Release callback. We do not need its anymore const cancelListeners = this._cancelListeners.splice(0); for (const cancelListener of cancelListeners) { try { cancelListener(); } catch (e) { if (errors === null) { errors = []; } errors.push(common_1.FException.wrapIfNeeded(e)); } } } if (errors !== null && errors.length > 0) { throw new common_1.FExceptionAggregate(errors); } } } exports.FHttpRequestCancellationToken = FHttpRequestCancellationToken; //# sourceMappingURL=FHttpRequestCancellationToken.js.map