-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
73 lines (60 loc) · 1.84 KB
/
script.js
File metadata and controls
73 lines (60 loc) · 1.84 KB
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
async function run(sql) {
const tokenInfo = await grist.docApi.getAccessToken({readOnly: true});
console.log(tokenInfo);
const url = tokenInfo.baseUrl + `/sql?auth=${tokenInfo.token}`;
const result = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
sql
}),
});
const result2 = await result.json();
console.log(result2);
makeTable(result2.records);
}
function makeTable(data) {
const tableHeadersRow = document.getElementById('table-headers');
const tableBody = document.getElementById('table-body');
tableHeadersRow.innerHTML = "";
tableBody.innerHTML = "";
// Extract the headers from the first object in the data array
const firstItem = data[0];
const headers = Object.keys(firstItem.fields);
// Create table headers dynamically
headers.forEach(headerText => {
const th = document.createElement('th');
th.textContent = headerText;
tableHeadersRow.appendChild(th);
});
// Populate the table body
data.forEach(item => {
const fields = item.fields;
const row = document.createElement('tr');
headers.forEach(header => {
const cell = document.createElement('td');
cell.textContent = fields[header];
row.appendChild(cell);
});
tableBody.appendChild(row);
});
}
function init() {
document.getElementById('run').addEventListener('click', async function() {
const sql = document.getElementById('query').value;
await run(sql);
});
}
grist.ready({
requiredAccess: 'full'
});
function ready(fn) {
if (document.readyState !== 'loading') {
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
ready(init);