-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
197 lines (178 loc) · 4.96 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
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
var client = new FamilySearch({
appKey: 'a02j000000KSuIBAA1',
redirectUri: window.location.href
}),
$url = document.getElementById('url'),
$method = document.getElementById('method'),
$output = document.getElementById('output'),
$requestBody = document.getElementById('request-body'),
$authStatus = document.getElementById('auth-status'),
$tokenDisplay = document.getElementById('access-token-display'),
$expectRedirect = document.getElementById('expectRedirect'),
$followRedirect = document.getElementById('followRedirect');
// Setup event listeners
document.getElementById('load-button').addEventListener('click', makeRequest);
$url.addEventListener('keypress', function(e){
var key = e.which || e.keyCode;
if(key === 13){
makeRequest();
}
});
$method.addEventListener('change', function(){
if($method.value === 'POST'){
$requestBody.style.display = 'block';
} else {
$requestBody.style.display = 'none';
}
});
document.getElementById('login-btn').addEventListener('click', function(){
client.oauthRedirect();
});
document.getElementById('logout-btn').addEventListener('click', function(){
client.deleteAccessToken();
window.location.reload();
});
// Handle an OAuth2 response if we're in that state. Otherwise we initialize the
// app with a request on load.
var oauthResponseState = client.oauthResponse(function(error, response){
if(response){
displayResponse(response);
// On success, reload the page to remove the code from the url
if(response.statusCode === 200){
window.location = window.location.pathname;
}
} else {
genericError();
}
});
if(!oauthResponseState){
makeRequest();
}
/**
* Send a request to the API and display the response
*/
function makeRequest(){
output('Sending the request...');
var options = {
method: $method.value,
headers: {
Accept: document.getElementById('accept').value
},
expectRedirect: $expectRedirect.checked,
followRedirect: $followRedirect.checked
};
if(options.method === 'POST'){
options.body = $requestBody.value;
}
client.request($url.value, options, function(error, response){
if(error){
genericError();
} else {
displayResponse(response);
if(response.statusCode === 401){
$authStatus.classList.remove('loggedin');
$tokenDisplay.value = '';
} else {
$authStatus.classList.add('loggedin');
$tokenDisplay.value = 'Bearer ' + client.getAccessToken();
}
}
});
}
/**
* Display a generic error since XHR gives us no details.
*/
function genericError(){
output('Fatal error. Open the browser\'s developer console for more details.');
}
/**
* Display an API response
*
* @param {Object} response
*/
function displayResponse(response){
// Gather and display HTTP response data
var lines = [
response.statusCode + ' ' + response.statusText,
headersToString(response.headers)
];
if(response.data){
lines.push('');
lines.push(prettyPrint(response.data));
}
output(lines.join('\n'));
// Attach listeners to links so that clicking a link will auto-populate
// the url field
Array.from($output.querySelectorAll('.link')).forEach(function(link){
link.addEventListener('click', function(){
// Remove leading and trailing "
$url.value = link.innerHTML.slice(1,-1);
window.scrollTo(0, 0);
});
});
}
/**
* Convert a headers map into a multi-line string
*
* @param {Object} headers
* @return {String}
*/
function headersToString(headers){
var lines = [];
for(var name in headers){
lines.push(name + ': ' + headers[name]);
}
return lines.join('\n');
}
/**
* Display HTML in the response output container
*
* @param {String} html
*/
function output(html){
$output.innerHTML = html;
}
/**
* Pretty print a JSON object
*
* @param {Object} obj
* @return {String} html string
*/
function prettyPrint(obj){
return syntaxHighlight(JSON.stringify(obj, null, 4));
}
/**
* Parse a JSON string and wrap data in spans to enable syntax highlighting.
*
* http://stackoverflow.com/a/7220510
*
* @param {String} JSON string
* @returns {String}
*/
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number',
url = false;
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
if(match.indexOf('"https://') === 0){
// url = true;
cls += ' link';
}
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
var html = '<span class="' + cls + '">' + match + '</span>';
if(url){
html = '<a href>' + html + '</a>';
}
return html;
});
}