2021-12-17 10:52:12 +01:00
|
|
|
import DataFetch from "./DataFetch.js"
|
2021-12-17 09:22:04 +01:00
|
|
|
import { executeQuery, fetchQueryDefinition } from "api"
|
2021-12-17 10:52:12 +01:00
|
|
|
import { cloneDeep } from "lodash/fp"
|
2021-12-17 19:39:48 +01:00
|
|
|
import { get } from "svelte/store"
|
2021-12-17 09:22:04 +01:00
|
|
|
|
2021-12-17 19:39:48 +01:00
|
|
|
export default class QueryFetch extends DataFetch {
|
|
|
|
determineFeatureFlags(definition) {
|
2021-12-17 19:53:57 +01:00
|
|
|
console.log("pagination config", definition?.fields?.pagination)
|
2021-12-17 19:39:48 +01:00
|
|
|
this.supportsPagination =
|
|
|
|
definition?.fields?.pagination?.type != null &&
|
|
|
|
definition?.fields?.pagination?.pageParam != null
|
|
|
|
}
|
|
|
|
|
|
|
|
static async getDefinition(datasource) {
|
2021-12-17 09:22:04 +01:00
|
|
|
if (!datasource?._id) {
|
|
|
|
return null
|
|
|
|
}
|
2021-12-17 19:39:48 +01:00
|
|
|
return await fetchQueryDefinition(datasource._id)
|
2021-12-17 09:22:04 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
async getData() {
|
2021-12-17 19:39:48 +01:00
|
|
|
const { datasource, limit } = this.options
|
2021-12-17 09:22:04 +01:00
|
|
|
|
|
|
|
// Set the default query params
|
|
|
|
let parameters = cloneDeep(datasource?.queryParams || {})
|
|
|
|
for (let param of datasource?.parameters || {}) {
|
|
|
|
if (!parameters[param.name]) {
|
|
|
|
parameters[param.name] = param.default
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-17 19:39:48 +01:00
|
|
|
// Add pagination to query if supported
|
|
|
|
let queryPayload = { queryId: datasource?._id, parameters }
|
|
|
|
if (this.supportsPagination) {
|
|
|
|
const { cursor, definition, pageNumber } = get(this.store)
|
2021-12-17 19:53:57 +01:00
|
|
|
const { type } = definition.fields.pagination
|
2021-12-17 19:39:48 +01:00
|
|
|
const page = type === "page" ? pageNumber : cursor
|
|
|
|
queryPayload.pagination = { page, limit }
|
|
|
|
}
|
|
|
|
|
|
|
|
const { data, pagination, ...rest } = await executeQuery(queryPayload)
|
2021-12-17 09:22:04 +01:00
|
|
|
return {
|
2021-12-17 14:12:28 +01:00
|
|
|
rows: data || [],
|
|
|
|
info: rest,
|
2021-12-17 19:39:48 +01:00
|
|
|
cursor: pagination?.page,
|
|
|
|
hasNextPage: data?.length === limit && limit > 0,
|
2021-12-17 09:22:04 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|