import type {
IItem,
IItemPrimitive
} from '@snakeware/snakeware.api.site.typescript'
import { Item } from '@snakeware/snakeware.api.site.typescript'
export const useCms = () => {
const { getPage } = useSwCloudApi()
const { $swCloud } = useNuxtApp()
const getControls = (item: IItem) => {
if (!item.template) return
return Array.from(item.template.controls)
.map((control) =>
$swCloud.item.getControlByAlias(item, control.alias ?? '')
)
.reduce(
(obj, secondItem) => ({
...obj,
[secondItem?.alias ?? '']: secondItem
}),
{}
)
}
const getControlData = (arr: Iterable<IItemPrimitive>) => {
return Array.from(arr).map((item) => {
const control = {
id: item.id,
...getControls(Item.create(item))
} as unknown as IItem
return control
})
}
const getItems = async (category: string, section: string) => {
const categoryResponse = await getPage(category)
const selectedSection = Array.from(
categoryResponse.data?.category?.sections
).find((s) => s.name === section)
if (selectedSection) {
return Array.from(selectedSection.items).map((item) =>
getControls(Item.create(item))
)
}
return []
}
return { getItems, getControls, getControlData }
}