UNPKG

@freemework/hosting

Version:

Hosting library of the Freemework Project.

58 lines 2.31 kB
import { FException, FCancellationException, FExceptionAggregate } from "@freemework/common"; export 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 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(FException.wrapIfNeeded(e)); } } } if (errors !== null && errors.length > 0) { throw new FExceptionAggregate(errors); } } } //# sourceMappingURL=FHttpRequestCancellationToken.js.map