-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (55 loc) · 1.91 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'use strict'
const debug = require('debug')('engine.io-sticky-headers')
let initialized = false
let socket = null
function initialize (XHR, stickyHeader, requestAsQueryParam) {
if (initialized) return
if (stickyHeader == null) {
stickyHeader = 'Session-Id'
}
const queryParamKey = stickyHeader.replace(new RegExp('-', 'g'), '')
if (XHR == null || typeof XHR !== 'function') {
throw new Error('Please provide XHR function constructor ie require("engine.io-client/lib/transports/polling-xhr"')
}
const Request = XHR.Request
const originalXHRRequest = XHR.prototype.request
if (originalXHRRequest == null) {
throw new Error('XHR.prototype.request is not set')
}
const originalOnLoad = Request.prototype.onLoad
if (originalOnLoad == null) {
throw new Error('Request.prototype.onLoad is not set')
}
Request.prototype.onLoad = function () {
this.emit('onLoad')
originalOnLoad.call(this)
}
XHR.prototype.request = function (opts) {
let request = originalXHRRequest.call(this, opts)
request.once('onLoad', createStickyUpdater(this))
return request
}
// Update sticky header after every successful request
function createStickyUpdater (xhr) {
return function updateSticky () {
let newStickyValue = this.xhr.getResponseHeader(stickyHeader)
if (newStickyValue != null) {
if (requestAsQueryParam && socket) {
socket.io.engine.transport.query[queryParamKey] = socket.io.engine.query[queryParamKey] = newStickyValue
} else {
debug('setting header %s to %s', stickyHeader, newStickyValue)
if (xhr.extraHeaders == null) {
xhr.extraHeaders = {}
}
xhr.extraHeaders[stickyHeader] = newStickyValue
}
}
}
}
initialized = true
}
// reference to socket is needed if sending a query param
initialize.setSocket = function (s) {
socket = s
}
module.exports = initialize