2023-03-08 23:13:33 +01:00
|
|
|
import jsonapi from 'jsonapi-serializer'
|
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 apiBaseUrl = `${baseUrl}${jsonapiPath}`
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2023-06-15 20:45:38 +02:00
|
|
|
baseUrl: baseUrl,
|
|
|
|
jsonApiUrl: apiBaseUrl,
|
2023-03-08 23:13:33 +01:00
|
|
|
headers,
|
|
|
|
deserialize
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const idmap = (arr, idattr = 'id') => {
|
|
|
|
if (!arr) { return {} }
|
|
|
|
|
|
|
|
return arr.reduce((vse, i) => {
|
|
|
|
const id = i[idattr]
|
|
|
|
vse[id] = i
|
|
|
|
return vse
|
|
|
|
}, {})
|
|
|
|
}
|