-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstoclog.js
104 lines (80 loc) · 2.41 KB
/
stoclog.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'use strict';
(function () {
var GLOBAL_NAME = 'Stoclog';
var SPECIAL_HEADER_NAME = 'x-operation-with-serverside-logs';
var NATIVE_METHODS = Object.keys(console);
var DEFAULT_NUMBER_TO_FETCH = 5;
window[GLOBAL_NAME] = makeRequest;
makeRequest.get = function (pointerName) {
makeRequest(null, pointerName, 'getstate');
}
makeRequest.defaultFetchNumber = function (number) {
DEFAULT_NUMBER_TO_FETCH = number;
}
makeRequest.renameTo = function (newGlogalName) {
window[newGlogalName] = makeRequest;
delete window[GLOBAL_NAME];
GLOBAL_NAME = newGlogalName;
}
makeRequest.remove = function () {
makeRequest(null, null, 'remove');
}
decorate(NATIVE_METHODS);
makeRequest.$ = {};
makeRequest(null, null, 'connect');
function makeRequest (number, type, operation) {
operation = operation || 'get';
type = type || 'all';
number = number || DEFAULT_NUMBER_TO_FETCH;
var xhr = new XMLHttpRequest();
xhr.open('GET', '/', true);
xhr.setRequestHeader(SPECIAL_HEADER_NAME, [operation, type, number].join(','));
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status !== 200) {
return console.error(
'Error occured while fetching server logs.\nCode: %s\n%s',
xhr.status,
xhr.responseText
);
}
var response = JSON.parse(xhr.response);
switch (operation) {
case 'get':
log(response);
break;
case 'getstate':
makeRequest.$[type] = response;
console.log(response);
break;
case 'remove':
console.warn(type + ' logs were removed');
break;
case 'connect':
decorate(response);
break;
}
}
};
xhr.send();
}
function decorate (methodNames) {
methodNames.forEach((methodName) => {
makeRequest[methodName] = function (number) {
makeRequest(number, methodName, 'get');
}
makeRequest[methodName].remove = function () {
makeRequest(null, methodName, 'remove');
}
});
}
function log (logs) {
logs.forEach((log) => {
var method = isNativeMethod(log.method) ? log.method : 'log';
console[method].apply(console, log.args)
});
}
function isNativeMethod (method) {
return !!~NATIVE_METHODS.indexOf(method);
}
})();