2020-08-24 17:26:00 +02:00
|
|
|
import api from "./api"
|
|
|
|
|
2020-10-09 13:24:18 +02:00
|
|
|
export default async function fetchData(datasource, _bb) {
|
|
|
|
const { type, name } = datasource
|
2020-08-24 17:26:00 +02:00
|
|
|
|
|
|
|
if (name) {
|
2020-10-09 13:24:18 +02:00
|
|
|
let records
|
|
|
|
if (type === "model") {
|
|
|
|
records = await fetchModelData()
|
|
|
|
} else if (type === "view") {
|
|
|
|
records = await fetchViewData()
|
|
|
|
} else if (type === "link") {
|
|
|
|
records = await fetchLinkedRecordsData()
|
|
|
|
}
|
2020-10-06 19:01:23 +02:00
|
|
|
|
|
|
|
// Fetch model schema so we can check for linked records
|
|
|
|
if (records && records.length) {
|
|
|
|
const model = await fetchModel(records[0].modelId)
|
|
|
|
const keys = Object.keys(model.schema)
|
|
|
|
records.forEach(record => {
|
|
|
|
for (let key of keys) {
|
|
|
|
if (model.schema[key].type === "link") {
|
|
|
|
record[key] = Array.isArray(record[key]) ? record[key].length : 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return records
|
|
|
|
}
|
|
|
|
|
|
|
|
async function fetchModel(id) {
|
|
|
|
const FETCH_MODEL_URL = `/api/models/${id}`
|
|
|
|
const response = await api.get(FETCH_MODEL_URL)
|
|
|
|
return await response.json()
|
2020-08-24 17:26:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async function fetchModelData() {
|
|
|
|
if (!name.startsWith("all_")) {
|
|
|
|
throw new Error("Incorrect model convention - must begin with all_")
|
|
|
|
}
|
|
|
|
const modelsResponse = await api.get(`/api/views/${name}`)
|
|
|
|
return await modelsResponse.json()
|
|
|
|
}
|
|
|
|
|
|
|
|
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()
|
|
|
|
}
|
2020-10-09 13:24:18 +02:00
|
|
|
|
|
|
|
async function fetchLinkedRecordsData() {
|
|
|
|
if (
|
|
|
|
!_bb.store.state ||
|
|
|
|
!_bb.store.state.data ||
|
|
|
|
!_bb.store.state.data._id
|
|
|
|
) {
|
|
|
|
return []
|
|
|
|
}
|
|
|
|
const QUERY_URL = `/api/${_bb.store.state.data.modelId}/${_bb.store.state.data._id}/enrich`
|
|
|
|
const response = await api.get(QUERY_URL)
|
|
|
|
const record = await response.json()
|
|
|
|
return record[datasource.fieldName]
|
|
|
|
}
|
2020-08-24 17:26:00 +02:00
|
|
|
}
|