UNPKG

2.01 kBJavaScriptView Raw
1var Request = require('./Request');
2var constants = require('../shared/constants');
3var inherits = require('../shared/inherits');
4var buildURL = require('../shared/buildURL');
5var handleOptions = require('../shared/handleOptions');
6var callRequestCreatedCallback = require('../shared/callRequestCreatedCallback');
7var addEventListeners = require('../http/addEventListeners');
8var handleXhrProps = require('../http/handleXhrProps');
9var handleHeaders = require('../http/handleHeaders');
10var handleRequestBody = require('../http/handleRequestBody');
11var callXhrHook = require('../http/callXhrHook');
12
13/**
14 * http request.
15 *
16 * @class
17 * @extends {Request}
18 * @param {RequestOptions} options The request options.
19 * @param {RequestSuccessCallback} onsuccess The callback to call on success.
20 * @param {RequestErrorCallback} onerror The callback to call on error.
21 */
22function HttpRequest(options, onsuccess, onerror) {
23 var xhr;
24 var body;
25 var url;
26
27 // Call the super constructor.
28 Request.call(this, constants.HTTP_REQUEST, options, onsuccess, onerror);
29
30 // Call `options.handleOptions` to handle options.
31 handleOptions(options);
32
33 xhr = this.xhr = options.createXHR.call(null, options);
34 body = handleRequestBody(options);
35 url = buildURL(options);
36
37 // Set properties to the xhr.
38 handleXhrProps(xhr, options);
39
40 // Call onXhrCreated.
41 callXhrHook(options.onXhrCreated, xhr, options);
42
43 // Open the request.
44 xhr.open(options.method || 'GET', url, true, options.username, options.password);
45
46 // Add event listeners.
47 addEventListeners(this);
48
49 // Call onXhrOpened.
50 callXhrHook(options.onXhrOpened, xhr, options);
51
52 // Hanlde headers.
53 handleHeaders(xhr, options);
54
55 // Send the body to the server.
56 xhr.send(body);
57
58 // Call onXhrSent.
59 callXhrHook(options.onXhrSent, xhr, options);
60
61 // Call onRequestCreated
62 callRequestCreatedCallback(options, this);
63}
64
65inherits(HttpRequest, Request);
66
67module.exports = HttpRequest;