forked from mongodb-developer/EDEE_Frontend_Development
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
291 lines (224 loc) · 7.93 KB
/
main.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
let code, response, endpointName, databox, infobox;
let codeChanged;
let _exampleName = []; //Examples used for different orgs
let _saveFileName = null;
let __exsection = null;
const serviceHostname = "https://edee.mongodb.com/v1/";
async function onLoad() {
// If we supplied an org name in the URL then write that to Localstorage
const myURL = new URL(window.location);
if (myURL.searchParams && myURL.searchParams.get("org")) {
localStorage.setItem("organization", myURL.searchParams.get("org"));
}
if (myURL.searchParams && myURL.searchParams.get("s")) {
__exsection = myURL.searchParams.get("s")
}
// If an org name is in LocalStorage then use it to set the examples page
// This lets us have different examples based on the last link you used with org
if (localStorage.getItem("organization") && document.getElementById("exampleLink")) {
document.getElementById("exampleLink").href = `examples/${localStorage.getItem("organization")}.html`
}
var editor = ace.edit("editor");
editor.setTheme("ace/theme/pastel_on_dark");
editor.session.setMode("ace/mode/javascript");
editor.session.setUseWorker(false);
editor.setOptions({
fontFamily: "Source Code Pro",
fontSize: "12pt"
});
editor.getSession().on('change', function () {
codeChangeHandler()
});
var outputFormatted = ace.edit("response");
outputFormatted.setTheme("ace/theme/eclipse");
outputFormatted.setOption("highlightActiveLine", false)
outputFormatted.renderer.setShowGutter(false);
outputFormatted.session.setMode("ace/mode/json");
outputFormatted.session.setUseWrapMode(true);
outputFormatted.setOptions({
fontFamily: "Source Code Pro",
fontSize: "12pt"
});
_code = editor;
//_output = document.getElementById("response");
_output = outputFormatted
_postdata = document.getElementById("postdata");
endpointName = document.getElementById("endpoint");
document.getElementById("url").innerText = serviceHostname;
codeChanged = true;
// we can feed index.html with a different src file each time
// we extract the code and put it in the code element
if (myURL.searchParams && myURL.searchParams.get("src")) {
await loadTemplateCode(myURL.searchParams.get("src"));
if (myURL.searchParams.get("title")) {
document.title = myURL.searchParams.get("title");
} else {
document.title = myURL.searchParams.get("src").split("_").join("/");
}
}
setTimeout(codeChangeHandler, 0);
}
function loadLocalCode(filePath) {
let reader = new FileReader(); // no arguments
reader.readAsText(filePath);
//_output.innerText = "";
_output.setValue("", -1);
_postdata.innerText = "";
reader.onload = function () {
_code.setValue(reader.result, -1);
};
reader.onerror = function () {
alert(reader.error);
};
}
function insertTextAtCursor(text) {
let selection = window.getSelection();
let range = selection.getRangeAt(0);
range.deleteContents();
let node = document.createTextNode(text);
range.insertNode(node);
selection.collapseToEnd();
}
function messageBox(str) {
document.getElementById("infobox").innerText = str;
}
async function callService(method) {
conso1e.contents = "";
try {
// loader.style.visibility = "visible";
_output.setValue("", -1);
const fullURL = serviceHostname + endpointName.innerText;
MongoClient._nServerCalls = 0;
const startTime = Date.now();
const response = await callVirtualEndpoint(fullURL, method);
const endTime = Date.now();
let timeToShow = Math.floor((endTime - startTime) - (MongoClient._serverLatency * MongoClient._nServerCalls));
if (timeToShow < 1) timeToShow = 1;
let renderOut = "";
if (conso1e.contents) {
renderOut += "-------------------------- Console --------------------------\n";
renderOut += conso1e.contents;
renderOut += "\n-------------------------------------------------------------\n\n";
}
renderOut += `\n"ResponseTime": ${timeToShow}ms\n`
renderOut += `"StatusCode": ${response._status}\n`;
for (const key in response._headers) {
renderOut += `"${key}": ${response._headers[key]}\n\n`;
}
if (
typeof response._data === "string" ||
response._data instanceof String
) {
renderOut += `${response._data}`;
} else {
renderOut += JSON.stringify(response._data, null, 2);
}
_output.setValue(renderOut, -1);
// Was this a winner?
if (window.__verify_challenge && typeof window.__verify_challenge == "function") {
window.__verify_challenge(response);
}
} catch (error) {
console.error(error);
messageBox(error); // Fatal problem
}
}
//Load a JS file and populate the code side
async function loadTemplateCode(fname) {
const parts = fname.split("_");
_exampleName = parts;
url = "examples/" + parts.join("/") + "/" + parts[parts.length - 1];
let response = await fetch(`${url}.js`);
if (response.status == 200) {
_code.setValue(await response.text(), -1);
} else {
//We don't really care if it's missing
_code.setValue("// EXAMPLE CODE MISSING - Is URL Correct", -1);
}
response = await fetch(`${url}.json`);
if (response.status == 200) {
_postdata.innerText = await response.text();
} else {
_postdata.innerText = "";
}
response = await fetch(`${url}.url`);
if (response.status == 200) {
endpointName.innerText = await response.text();
} else {
endpointName.innerText = "";
}
response = await fetch(`${url}.buttons`);
if (response.status == 200) {
buttons = await response.text();
const buttonData = JSON.parse(buttons);
for (let button in buttonData) {
container = document.getElementById("buttons");
newButton = document.createElement("button");
newButton.innerText = button
newButton.addEventListener("click", () => { showInfo(buttonData[button]) }, false);
newButton.classList.add("button");
container.appendChild(newButton);
//<button class="button" onclick="callService('GET')" id="callServiceGET"> GET </button>
}
//Fetch a challenge tester if it exists
response = await fetch(`${url}_challenge.js`);
if (response.status == 200) {
challengeCode = await response.text();
const challengeHandler = document.createElement("script");
challengeHandler.id = "chandler";
document.body.appendChild(challengeHandler);
window.addEventListener("error", (event) => {
console.log(event);
syntaxOKFlag = false;
syntaxErrorMessage = `${event.message} : Line ${event.lineno} Col: ${event.colno}`;
});
syntaxOKFlag = true;
challengeHandler.innerHTML = challengeCode;
if (!syntaxOKFlag) {
console.error(`Server Error ocurred: ${syntaxErrorMessage}`);
}
}
}
}
// This can get more fancy over time if needs be
async function showInfo(file) {
const url = "examples/" + _exampleName.join("/") + "/";
const response = await fetch(url + file);
if (response.status == 200) {
_output.setValue(r = await response.text(), -1)
}
}
function saveToClipboard() {
navigator.clipboard.writeText(_code.getValue());
}
function saveCode() {
let data = "";
data = _code.getValue();
if (_saveFileName == null) {
_saveFileName = prompt("Please enter a filename");
}
var file = new Blob([data], { type: "application/javascript" });
var a = document.createElement("a");
var url = URL.createObjectURL(file);
a.href = url;
a.download = _saveFileName;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
function codeChangeHandler() {
data = _code.getValue();
const getButton = document.getElementById("callServiceGET");
const postButton = document.getElementById("callServicePOST");
getButton.hidden = true;
postButton.hidden = true
if (data.search(" get_") != -1) {
getButton.hidden = false;
}
if (data.search(" post_") != -1) {
postButton.hidden = false;
}
}