2020-08-24 17:26:00 +02:00
|
|
|
import api from "./api"
|
|
|
|
|
|
|
|
export default async function fetchData(datasource) {
|
2020-10-09 19:49:23 +02:00
|
|
|
const { isTable, name } = datasource
|
2020-08-24 17:26:00 +02:00
|
|
|
|
|
|
|
if (name) {
|
2020-10-09 20:10:28 +02:00
|
|
|
const rows = isTable ? await fetchTableData() : await fetchViewData()
|
2020-10-06 19:01:23 +02:00
|
|
|
|
2020-10-09 20:10:28 +02:00
|
|
|
// Fetch table schema so we can check for linked rows
|
|
|
|
if (rows && rows.length) {
|
|
|
|
const table = await fetchTable(rows[0].tableId)
|
2020-10-09 19:49:23 +02:00
|
|
|
const keys = Object.keys(table.schema)
|
2020-10-09 20:10:28 +02:00
|
|
|
rows.forEach(row => {
|
2020-10-06 19:01:23 +02:00
|
|
|
for (let key of keys) {
|
2020-10-09 19:49:23 +02:00
|
|
|
if (table.schema[key].type === "link") {
|
2020-10-09 20:10:28 +02:00
|
|
|
row[key] = Array.isArray(row[key]) ? row[key].length : 0
|
2020-10-06 19:01:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-10-09 20:10:28 +02:00
|
|
|
return rows
|
2020-10-06 19:01:23 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 19:49:23 +02:00
|
|
|
async function fetchTable(id) {
|
|
|
|
const FETCH_TABLE_URL = `/api/tables/${id}`
|
|
|
|
const response = await api.get(FETCH_TABLE_URL)
|
2020-10-06 19:01:23 +02:00
|
|
|
return await response.json()
|
2020-08-24 17:26:00 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 19:49:23 +02:00
|
|
|
async function fetchTableData() {
|
2020-08-24 17:26:00 +02:00
|
|
|
if (!name.startsWith("all_")) {
|
2020-10-09 19:49:23 +02:00
|
|
|
throw new Error("Incorrect table convention - must begin with all_")
|
2020-08-24 17:26:00 +02:00
|
|
|
}
|
2020-10-09 19:49:23 +02:00
|
|
|
const tablesResponse = await api.get(`/api/views/${name}`)
|
|
|
|
return await tablesResponse.json()
|
2020-08-24 17:26:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async function fetchViewData() {
|
|
|
|
const { field, groupBy } = datasource
|
|
|
|
const params = new URLSearchParams()
|
|
|
|
|
2020-09-02 12:52:32 +02:00
|
|
|
if (field) {
|
|
|
|
params.set("field", field)
|
|
|
|
params.set("stats", true)
|
|
|
|
}
|
2020-08-24 17:26:00 +02:00
|
|
|
if (groupBy) params.set("group", groupBy)
|
2020-09-02 12:52:32 +02:00
|
|
|
|
|
|
|
let QUERY_VIEW_URL = field
|
|
|
|
? `/api/views/${name}?${params}`
|
|
|
|
: `/api/views/${name}`
|
2020-08-24 17:26:00 +02:00
|
|
|
|
|
|
|
const response = await api.get(QUERY_VIEW_URL)
|
|
|
|
return await response.json()
|
|
|
|
}
|
|
|
|
}
|