| 1 |
import * as FakeFetch from 'whatwg-fetch'; |
| 2 |
import FakeXMLHttpRequest from 'fake-xml-http-request'; |
| 3 |
import { Params, QueryParams } from 'route-recognizer'; |
| 4 |
import { ResponseHandler, ResponseHandlerInstance } from '../index.d'; |
| 5 |
import Hosts from './hosts'; |
| 6 |
import parseURL from './parse-url'; |
| 7 |
import Registry from './registry'; |
| 8 |
import { interceptor } from './interceptor'; |
| 9 |
|
| 10 |
interface ExtraRequestData { |
| 11 |
url: string; |
| 12 |
method: string; |
| 13 |
params: Params; |
| 14 |
queryParams: QueryParams; |
| 15 |
} |
| 16 |
type FakeRequest = FakeXMLHttpRequest & ExtraRequestData; |
| 17 |
|
| 18 |
type Verb = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'; |
| 19 |
|
| 20 |
class NoopArray { |
| 21 |
length = 0; |
| 22 |
push(..._items: any[]) { |
| 23 |
return 0; |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
function scheduleProgressEvent(request, startTime, totalTime) { |
| 28 |
let totalSize = 0; |
| 29 |
const body = request.requestBody; |
| 30 |
if (body) { |
| 31 |
if (body instanceof FormData) { |
| 32 |
body.forEach((value) => { |
| 33 |
if (value instanceof File) { |
| 34 |
totalSize += value.size; |
| 35 |
} else { |
| 36 |
totalSize += value.length; |
| 37 |
} |
| 38 |
}); |
| 39 |
} else { |
| 40 |
// Support Blob, BufferSource, USVString, ArrayBufferView |
| 41 |
totalSize = body.byteLength || body.size || body.length || 0; |
| 42 |
} |
| 43 |
} |
| 44 |
setTimeout(function () { |
| 45 |
if (!request.aborted && !request.status) { |
| 46 |
let elapsedTime = new Date().getTime() - startTime.getTime(); |
| 47 |
let progressTransmitted = |
| 48 |
totalTime <= 0 ? 0 : (elapsedTime / totalTime) * totalSize; |
| 49 |
// ProgressEvent expects loaded, total |
| 50 |
// https://xhr.spec.whatwg.org/#interface-progressevent |
| 51 |
request.upload._progress(true, progressTransmitted, totalSize); |
| 52 |
request._progress(true, progressTransmitted, totalSize); |
| 53 |
scheduleProgressEvent(request, startTime, totalTime); |
| 54 |
} else if (request.status) { |
| 55 |
// we're done, send a final progress event with loaded === total |
| 56 |
request.upload._progress(true, totalSize, totalSize); |
| 57 |
request._progress(true, totalSize, totalSize); |
| 58 |
} |
| 59 |
}, 50); |
| 60 |
} |
| 61 |
|
| 62 |
function isArray(array) { |
| 63 |
return Object.prototype.toString.call(array) === '[object Array]'; |
| 64 |
} |
| 65 |
|
| 66 |
const PASSTHROUGH = {}; |
| 67 |
|
| 68 |
function verbify(verb: Verb) { |
| 69 |
return function ( |
| 70 |
this: Pretender, |
| 71 |
path: string, |
| 72 |
handler: ResponseHandler, |
| 73 |
async: boolean |
| 74 |
) { |
| 75 |
return this.register(verb, path, handler, async); |
| 76 |
}; |
| 77 |
} |
| 78 |
|
| 79 |
export default class Pretender { |
| 80 |
static parseURL = parseURL; |
| 81 |
static Hosts = Hosts; |
| 82 |
static Registry = Registry; |
| 83 |
|
| 84 |
hosts = new Hosts(); |
| 85 |
handlers: ResponseHandler[] = []; |
| 86 |
handledRequests: any[] | NoopArray; |
| 87 |
passthroughRequests: any[] | NoopArray; |
| 88 |
unhandledRequests: any[] | NoopArray; |
| 89 |
requestReferences: any[]; |
| 90 |
forcePassthrough: boolean; |
| 91 |
disableUnhandled: boolean; |
| 92 |
|
| 93 |
ctx: { pretender?: Pretender }; |
| 94 |
running: boolean; |
| 95 |
|
| 96 |
private _nativeXMLHttpRequest: any; |
| 97 |
private _fetchProps: string[]; |
| 98 |
|
| 99 |
constructor() { |
| 100 |
let lastArg = arguments[arguments.length - 1]; |
| 101 |
let options = typeof lastArg === 'object' ? lastArg : null; |
| 102 |
let shouldNotTrack = options && options.trackRequests === false; |
| 103 |
|
| 104 |
this.handledRequests = shouldNotTrack ? new NoopArray() : []; |
| 105 |
this.passthroughRequests = shouldNotTrack ? new NoopArray() : []; |
| 106 |
this.unhandledRequests = shouldNotTrack ? new NoopArray() : []; |
| 107 |
this.requestReferences = []; |
| 108 |
this.forcePassthrough = options && options.forcePassthrough === true; |
| 109 |
this.disableUnhandled = options && options.disableUnhandled === true; |
| 110 |
|
| 111 |
// reference the native XMLHttpRequest object so |
| 112 |
// it can be restored later |
| 113 |
this._nativeXMLHttpRequest = (<any>self).XMLHttpRequest; |
| 114 |
this.running = false; |
| 115 |
let ctx = { pretender: this }; |
| 116 |
this.ctx = ctx; |
| 117 |
|
| 118 |
// capture xhr requests, channeling them into |
| 119 |
// the route map. |
| 120 |
(<any>self).XMLHttpRequest = interceptor(ctx); |
| 121 |
|
| 122 |
// polyfill fetch when xhr is ready |
| 123 |
this._fetchProps = FakeFetch |
| 124 |
? ['fetch', 'Headers', 'Request', 'Response'] |
| 125 |
: []; |
| 126 |
this._fetchProps.forEach((name) => { |
| 127 |
(<any>this)['_native' + name] = self[name]; |
| 128 |
self[name] = FakeFetch[name]; |
| 129 |
}, this); |
| 130 |
|
| 131 |
// 'start' the server |
| 132 |
this.running = true; |
| 133 |
|
| 134 |
// trigger the route map DSL. |
| 135 |
let argLength = options ? arguments.length - 1 : arguments.length; |
| 136 |
for (let i = 0; i < argLength; i++) { |
| 137 |
this.map(arguments[i]); |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
get = verbify('GET'); |
| 142 |
post = verbify('POST'); |
| 143 |
put = verbify('PUT'); |
| 144 |
delete = verbify('DELETE'); |
| 145 |
patch = verbify('PATCH'); |
| 146 |
head = verbify('HEAD'); |
| 147 |
options = verbify('OPTIONS'); |
| 148 |
|
| 149 |
map(maps: (pretender: Pretender) => void) { |
| 150 |
maps.call(this); |
| 151 |
} |
| 152 |
|
| 153 |
register( |
| 154 |
verb: string, |
| 155 |
url: string, |
| 156 |
handler: ResponseHandler, |
| 157 |
async: boolean |
| 158 |
): ResponseHandlerInstance { |
| 159 |
if (!handler) { |
| 160 |
throw new Error( |
| 161 |
'The function you tried passing to Pretender to handle ' + |
| 162 |
verb + |
| 163 |
' ' + |
| 164 |
url + |
| 165 |
' is undefined or missing.' |
| 166 |
); |
| 167 |
} |
| 168 |
|
| 169 |
const handlerInstance = handler as ResponseHandlerInstance; |
| 170 |
|
| 171 |
handlerInstance.numberOfCalls = 0; |
| 172 |
handlerInstance.async = async; |
| 173 |
this.handlers.push(handlerInstance); |
| 174 |
|
| 175 |
let registry = this.hosts.forURL(url)[verb]; |
| 176 |
|
| 177 |
registry.add([ |
| 178 |
{ |
| 179 |
path: parseURL(url).fullpath, |
| 180 |
handler: handlerInstance, |
| 181 |
}, |
| 182 |
]); |
| 183 |
|
| 184 |
return handlerInstance; |
| 185 |
} |
| 186 |
|
| 187 |
passthrough = PASSTHROUGH; |
| 188 |
|
| 189 |
checkPassthrough(request: FakeRequest) { |
| 190 |
let verb = request.method.toUpperCase() as Verb; |
| 191 |
let path = parseURL(request.url).fullpath; |
| 192 |
let recognized = this.hosts.forURL(request.url)[verb].recognize(path); |
| 193 |
let match = recognized && recognized[0]; |
| 194 |
|
| 195 |
if ((match && match.handler === PASSTHROUGH) || this.forcePassthrough) { |
| 196 |
this.passthroughRequests.push(request); |
| 197 |
this.passthroughRequest(verb, path, request); |
| 198 |
return true; |
| 199 |
} |
| 200 |
|
| 201 |
return false; |
| 202 |
} |
| 203 |
|
| 204 |
handleRequest(request: FakeRequest) { |
| 205 |
let verb = request.method.toUpperCase(); |
| 206 |
let path = request.url; |
| 207 |
|
| 208 |
let handler = this._handlerFor(verb, path, request); |
| 209 |
|
| 210 |
if (handler) { |
| 211 |
handler.handler.numberOfCalls++; |
| 212 |
let async = handler.handler.async; |
| 213 |
this.handledRequests.push(request); |
| 214 |
|
| 215 |
let pretender = this; |
| 216 |
|
| 217 |
let _handleRequest = function (statusHeadersAndBody) { |
| 218 |
if (!isArray(statusHeadersAndBody)) { |
| 219 |
let note = |
| 220 |
'Remember to `return [status, headers, body];` in your route handler.'; |
| 221 |
throw new Error( |
| 222 |
'Nothing returned by handler for ' + path + '. ' + note |
| 223 |
); |
| 224 |
} |
| 225 |
|
| 226 |
let status = statusHeadersAndBody[0]; |
| 227 |
let headers = pretender.prepareHeaders(statusHeadersAndBody[1]); |
| 228 |
let body = pretender.prepareBody(statusHeadersAndBody[2], headers); |
| 229 |
|
| 230 |
pretender.handleResponse(request, async, function () { |
| 231 |
request.respond(status, headers, body); |
| 232 |
pretender.handledRequest(verb, path, request); |
| 233 |
}); |
| 234 |
}; |
| 235 |
|
| 236 |
try { |
| 237 |
let result = handler.handler(request); |
| 238 |
if (result && typeof result.then === 'function') { |
| 239 |
// `result` is a promise, resolve it |
| 240 |
result.then(function (resolvedResult) { |
| 241 |
_handleRequest(resolvedResult); |
| 242 |
}); |
| 243 |
} else { |
| 244 |
_handleRequest(result); |
| 245 |
} |
| 246 |
} catch (error) { |
| 247 |
this.erroredRequest(verb, path, request, error); |
| 248 |
this.resolve(request); |
| 249 |
} |
| 250 |
} else { |
| 251 |
if (!this.disableUnhandled) { |
| 252 |
this.unhandledRequests.push(request); |
| 253 |
this.unhandledRequest(verb, path, request); |
| 254 |
} |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
handleResponse(request: FakeRequest, strategy, callback: Function) { |
| 259 |
let delay = typeof strategy === 'function' ? strategy() : strategy; |
| 260 |
delay = typeof delay === 'boolean' || typeof delay === 'number' ? delay : 0; |
| 261 |
|
| 262 |
if (delay === false) { |
| 263 |
callback(); |
| 264 |
} else { |
| 265 |
let pretender = this; |
| 266 |
pretender.requestReferences.push({ |
| 267 |
request: request, |
| 268 |
callback: callback, |
| 269 |
}); |
| 270 |
|
| 271 |
if (delay !== true) { |
| 272 |
scheduleProgressEvent(request, new Date(), delay); |
| 273 |
setTimeout(function () { |
| 274 |
pretender.resolve(request); |
| 275 |
}, delay); |
| 276 |
} |
| 277 |
} |
| 278 |
} |
| 279 |
|
| 280 |
resolve(request: FakeRequest) { |
| 281 |
for (let i = 0, len = this.requestReferences.length; i < len; i++) { |
| 282 |
let res = this.requestReferences[i]; |
| 283 |
if (res.request === request) { |
| 284 |
res.callback(); |
| 285 |
this.requestReferences.splice(i, 1); |
| 286 |
break; |
| 287 |
} |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
requiresManualResolution(verb: string, path: string) { |
| 292 |
let handler = this._handlerFor(verb.toUpperCase(), path, {}); |
| 293 |
if (!handler) { |
| 294 |
return false; |
| 295 |
} |
| 296 |
|
| 297 |
let async = handler.handler.async; |
| 298 |
return typeof async === 'function' ? async() === true : async === true; |
| 299 |
} |
| 300 |
prepareBody(body, _headers) { |
| 301 |
return body; |
| 302 |
} |
| 303 |
prepareHeaders(headers) { |
| 304 |
return headers; |
| 305 |
} |
| 306 |
handledRequest(_verb, _path, _request) { |
| 307 |
/* no-op */ |
| 308 |
} |
| 309 |
passthroughRequest(_verb, _path, _request) { |
| 310 |
/* no-op */ |
| 311 |
} |
| 312 |
unhandledRequest(verb, path, _request) { |
| 313 |
throw new Error( |
| 314 |
'Pretender intercepted ' + |
| 315 |
verb + |
| 316 |
' ' + |
| 317 |
path + |
| 318 |
' but no handler was defined for this type of request' |
| 319 |
); |
| 320 |
} |
| 321 |
erroredRequest(verb, path, _request, error) { |
| 322 |
error.message = |
| 323 |
'Pretender intercepted ' + |
| 324 |
verb + |
| 325 |
' ' + |
| 326 |
path + |
| 327 |
' but encountered an error: ' + |
| 328 |
error.message; |
| 329 |
throw error; |
| 330 |
} |
| 331 |
shutdown() { |
| 332 |
(<any>self).XMLHttpRequest = this._nativeXMLHttpRequest; |
| 333 |
this._fetchProps.forEach((name) => { |
| 334 |
self[name] = this['_native' + name]; |
| 335 |
}, this); |
| 336 |
this.ctx.pretender = undefined; |
| 337 |
// 'stop' the server |
| 338 |
this.running = false; |
| 339 |
} |
| 340 |
|
| 341 |
private _handlerFor(verb: Verb, url: string, request: FakeRequest) { |
| 342 |
let registry = this.hosts.forURL(url)[verb]; |
| 343 |
let matches = registry.recognize(parseURL(url).fullpath); |
| 344 |
|
| 345 |
let match = matches ? matches[0] : null; |
| 346 |
if (match) { |
| 347 |
request.params = match.params; |
| 348 |
request.queryParams = matches.queryParams; |
| 349 |
} |
| 350 |
|
| 351 |
return match; |
| 352 |
} |
| 353 |
} |