Debian Codegraph @

pretender/src/interceptor.ts

raw
1 import FakeXMLHttpRequest from 'fake-xml-http-request';
2 import { createPassthrough } from './create-passthrough';
3
4 export function interceptor(ctx) {
5 function FakeRequest() {
6 // super()
7 FakeXMLHttpRequest.call(this);
8 }
9 FakeRequest.prototype = Object.create(FakeXMLHttpRequest.prototype);
10 FakeRequest.prototype.constructor = FakeRequest;
11
12 // extend
13 FakeRequest.prototype.send = function send() {
14 this.sendArguments = arguments;
15 if (!ctx.pretender.running) {
16 throw new Error('You shut down a Pretender instance while there was a pending request. ' +
17 'That request just tried to complete. Check to see if you accidentally shut down ' +
18 'a pretender earlier than you intended to');
19 }
20
21 FakeXMLHttpRequest.prototype.send.apply(this, arguments);
22
23 if (ctx.pretender.checkPassthrough(this)) {
24 this.passthrough();
25 } else {
26 ctx.pretender.handleRequest(this);
27 }
28 };
29
30 FakeRequest.prototype.passthrough = function passthrough() {
31 if (!this.sendArguments) {
32 throw new Error('You attempted to passthrough a FakeRequest that was never sent. ' +
33 'Call `.send()` on the original request first');
34 }
35 var xhr = createPassthrough(this, ctx.pretender._nativeXMLHttpRequest);
36 xhr.send.apply(xhr, this.sendArguments);
37 return xhr;
38 };
39
40 FakeRequest.prototype._passthroughCheck = function(method, args) {
41 if (this._passthroughRequest) {
42 return this._passthroughRequest[method].apply(this._passthroughRequest, args);
43 }
44 return FakeXMLHttpRequest.prototype[method].apply(this, args);
45 };
46
47 FakeRequest.prototype.abort = function abort() {
48 return this._passthroughCheck('abort', arguments);
49 };
50
51 FakeRequest.prototype.getResponseHeader = function getResponseHeader() {
52 return this._passthroughCheck('getResponseHeader', arguments);
53 };
54
55 FakeRequest.prototype.getAllResponseHeaders = function getAllResponseHeaders() {
56 return this._passthroughCheck('getAllResponseHeaders', arguments);
57 };
58
59 if (ctx.pretender._nativeXMLHttpRequest.prototype._passthroughCheck) {
60 // eslint-disable-next-line no-console
61 console.warn('You created a second Pretender instance while there was already one running. ' +
62 'Running two Pretender servers at once will lead to unexpected results and will ' +
63 'be removed entirely in a future major version.' +
64 'Please call .shutdown() on your instances when you no longer need them to respond.');
65 }
66 return FakeRequest;
67 }