36 lines
810 B
JavaScript
36 lines
810 B
JavaScript
import jsonapi from 'jsonapi-serializer'
|
|
|
|
export const useApi = () => {
|
|
const { baseUrl, jsonapiPath } = useRuntimeConfig().public
|
|
|
|
const apiBaseUrl = `${baseUrl}${jsonapiPath}`
|
|
const headers = {
|
|
'Content-Type': 'application/vnd.api+json'
|
|
}
|
|
const deserializer = new jsonapi.Deserializer({ keyForAttribute: 'camelCase' })
|
|
|
|
const deserialize = async (data, mapfun = null, idAttr = null) => {
|
|
const ds = await deserializer.deserialize(data)
|
|
|
|
if (!mapfun) mapfun = a => a
|
|
return idmap(ds.map(mapfun), idAttr)
|
|
}
|
|
|
|
return {
|
|
baseUrl: baseUrl,
|
|
jsonApiUrl: apiBaseUrl,
|
|
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
|
|
}, {})
|
|
}
|