2023-03-08 23:13:33 +01:00
|
|
|
import jsonapi from 'jsonapi-serializer'
|
2023-02-22 21:19:55 +01:00
|
|
|
|
2024-04-01 19:59:09 +02:00
|
|
|
function idmap(arr, idattr = 'id') {
|
|
|
|
if (!arr) { return {} }
|
|
|
|
|
|
|
|
return arr.reduce((vse, i) => {
|
|
|
|
const id = i[idattr]
|
|
|
|
vse[id] = i
|
|
|
|
return vse
|
|
|
|
}, {})
|
|
|
|
}
|
|
|
|
|
2023-02-22 21:19:55 +01:00
|
|
|
export const useApi = () => {
|
2023-09-30 20:14:02 +02:00
|
|
|
const { baseUrl, jsonapiPath } = useRuntimeConfig().public
|
2023-03-08 23:13:33 +01:00
|
|
|
|
|
|
|
const headers = {
|
|
|
|
'Content-Type': 'application/vnd.api+json'
|
|
|
|
}
|
|
|
|
const deserializer = new jsonapi.Deserializer({ keyForAttribute: 'camelCase' })
|
2023-05-03 21:31:01 +02:00
|
|
|
|
|
|
|
const deserialize = async (data, mapfun = null, idAttr = null) => {
|
2023-03-08 23:13:33 +01:00
|
|
|
const ds = await deserializer.deserialize(data)
|
2023-05-03 21:31:01 +02:00
|
|
|
|
|
|
|
if (!mapfun) mapfun = a => a
|
|
|
|
return idmap(ds.map(mapfun), idAttr)
|
2023-03-08 23:13:33 +01:00
|
|
|
}
|
|
|
|
|
2024-04-01 19:59:09 +02:00
|
|
|
const jsonApiUrl = jezik => {
|
|
|
|
if (!jezik) {
|
|
|
|
jezik = 'sl'
|
|
|
|
}
|
|
|
|
|
|
|
|
return `${baseUrl}/${jezik}${jsonapiPath}`
|
|
|
|
}
|
|
|
|
|
2023-03-08 23:13:33 +01:00
|
|
|
return {
|
2023-06-15 20:45:38 +02:00
|
|
|
baseUrl: baseUrl,
|
2024-04-01 19:59:09 +02:00
|
|
|
jsonApiUrl,
|
2023-03-08 23:13:33 +01:00
|
|
|
headers,
|
|
|
|
deserialize
|
|
|
|
}
|
|
|
|
}
|