generated from gitea_admin/default
102 lines
2.6 KiB
JavaScript
102 lines
2.6 KiB
JavaScript
export function useStrapi(endpoint, options = {}) {
|
|
const queryString = computed(() => {
|
|
const locale = unref(options.locale) ?? "fr-FR"
|
|
const sort = unref(options.sort) ?? null
|
|
const populate = unref(options.populate) ?? null
|
|
const filters = unref(options.filters) ?? null
|
|
|
|
const query = new URLSearchParams()
|
|
query.set("locale", locale)
|
|
if (sort) {
|
|
query.set("sort[0]", sort)
|
|
}
|
|
if (populate && typeof populate === "object") {
|
|
appendPopulate(query, populate)
|
|
}
|
|
if (filters && typeof filters === "object") {
|
|
appendFilters(query, filters)
|
|
}
|
|
|
|
return query.toString()
|
|
})
|
|
|
|
const { data, pending, error, refresh } = useFetch(
|
|
() => `${endpoint}?${queryString.value}`,
|
|
{
|
|
server: true,
|
|
key: () => `${endpoint}:${queryString.value}`,
|
|
watch: [queryString],
|
|
}
|
|
)
|
|
|
|
const items = computed(() => {
|
|
const raw = data.value?.data
|
|
let list = []
|
|
if (Array.isArray(raw)) {
|
|
list = raw.map(normalizeStrapiItem)
|
|
} else if (raw && typeof raw === "object") {
|
|
list = [normalizeStrapiItem(raw)]
|
|
}
|
|
|
|
const limit = unref(options.limit)
|
|
if (typeof limit === "number") {
|
|
list = list.slice(0, Math.max(0, limit))
|
|
}
|
|
|
|
return list
|
|
})
|
|
|
|
return {
|
|
items,
|
|
pending,
|
|
error,
|
|
refresh,
|
|
}
|
|
}
|
|
|
|
function appendPopulate(query, populate, prefix = "populate") {
|
|
Object.entries(populate).forEach(([key, value]) => {
|
|
if (value === true) {
|
|
query.set(`${prefix}[${key}]`, "true")
|
|
return
|
|
}
|
|
if (value && typeof value === "object") {
|
|
const entries = Object.entries(value)
|
|
const allTrue = entries.length > 0 && entries.every(([, v]) => v === true)
|
|
if (allTrue) {
|
|
const list = entries.map(([k]) => k).join(",")
|
|
query.set(`${prefix}[${key}][populate]`, list)
|
|
return
|
|
}
|
|
appendPopulate(query, value, `${prefix}[${key}][populate]`)
|
|
}
|
|
})
|
|
}
|
|
|
|
function appendFilters(query, filters, prefix = "filters") {
|
|
Object.entries(filters).forEach(([key, value]) => {
|
|
if (value === null || value === undefined) return
|
|
if (typeof value !== "object") {
|
|
query.set(`${prefix}[${key}]`, String(value))
|
|
return
|
|
}
|
|
Object.entries(value).forEach(([k, v]) => {
|
|
if (v === null || v === undefined) return
|
|
if (typeof v !== "object") {
|
|
query.set(`${prefix}[${key}][${k}]`, String(v))
|
|
return
|
|
}
|
|
appendFilters(query, v, `${prefix}[${key}][${k}]`)
|
|
})
|
|
})
|
|
}
|
|
|
|
function normalizeStrapiItem(item) {
|
|
const a = item.attributes || item || {}
|
|
|
|
return {
|
|
id: item.id,
|
|
...a,
|
|
}
|
|
}
|