unmock-core
Version:
[][npmjs] [](https://circleci.com/gh/unmock/unmock-js) [](h
44 lines • 1.96 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const debug_1 = require("debug");
const http_1 = require("http");
const shimmer = require("shimmer");
const uuid_1 = require("uuid");
const debugLog = debug_1.default("unmock:client-request-tracker");
const UNMOCK_INTERNAL_HTTP_HEADER = "x-unmock-req-id";
class ClientRequestTracker {
static start() {
shimmer.wrap(http_1.ClientRequest.prototype, "onSocket", (original) => function (socket) {
const requestId = uuid_1.v4();
debugLog(`New socket assigned to client request, assigned ID: ${requestId}`);
ClientRequestTracker.clientRequests[requestId] = this;
this.setHeader(UNMOCK_INTERNAL_HTTP_HEADER, requestId);
return original.apply(this, [socket]);
});
}
static stop() {
if (!ClientRequestTracker.active) {
return;
}
shimmer.unwrap(http_1.ClientRequest.prototype, "onSocket");
}
static pop(incomingMessage) {
const { [UNMOCK_INTERNAL_HTTP_HEADER]: reqId } = incomingMessage.headers;
debugLog(`Intercepted incoming request with ID ${reqId}, matching to existing IDs:`, Object.keys(ClientRequestTracker.clientRequests));
if (typeof reqId !== "string") {
throw Error(`Expected to find a string request ID in request header, got type: ${typeof reqId}`);
}
const clientRequest = ClientRequestTracker.clientRequests[reqId];
if (clientRequest === undefined) {
throw Error(`Expected to find a client request for request ID ${reqId}`);
}
delete ClientRequestTracker.clientRequests[reqId];
return clientRequest;
}
static get active() {
return http_1.ClientRequest.prototype.onSocket.__wrapped !== undefined;
}
}
exports.default = ClientRequestTracker;
ClientRequestTracker.clientRequests = {};
//# sourceMappingURL=client-request-tracker.js.map