Files
Quizalarm/server/baserow.js
T

49 lines
1.6 KiB
JavaScript

const { getEnvConfig } = require('./config');
async function baserowFetch(endpoint, options = {}) {
const { baserowUrl, baserowToken } = getEnvConfig();
const url = `${baserowUrl}/api${endpoint}`;
const res = await fetch(url, {
...options,
headers: {
Authorization: `Token ${baserowToken}`,
'Content-Type': 'application/json',
...(options.headers || {}),
},
});
if (!res.ok) {
const body = await res.text().catch(() => '');
throw new Error(`Baserow ${res.status}: ${body.substring(0, 200)}`);
}
return res.json();
}
async function listRows(tableId, filters = {}) {
let all = [];
let page = 1;
while (true) {
let url = `/database/rows/table/${tableId}/?user_field_names=true&size=200&page=${page}`;
for (const [field, value] of Object.entries(filters)) {
url += `&filter__${encodeURIComponent(field)}__equal=${encodeURIComponent(value)}`;
}
const data = await baserowFetch(url);
all = all.concat(data.results || []);
if (!data.next) break;
page++;
}
return all;
}
async function batchCreateRows(tableId, rows) {
if (!rows.length) return;
// Baserow limit: 200 per batch
for (let i = 0; i < rows.length; i += 200) {
const chunk = rows.slice(i, i + 200);
await baserowFetch(`/database/rows/table/${tableId}/batch/?user_field_names=true`, {
method: 'POST',
body: JSON.stringify({ items: chunk }),
});
}
}
module.exports = { listRows, batchCreateRows };