manifest/nuxt/composables/api.js

43 lines
868 B
JavaScript
Raw Normal View History

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
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)
}
2024-04-01 19:59:09 +02:00
const jsonApiUrl = jezik => {
if (!jezik) {
jezik = 'sl'
}
return `${baseUrl}/${jezik}${jsonapiPath}`
}
return {
2023-06-15 20:45:38 +02:00
baseUrl: baseUrl,
2024-04-01 19:59:09 +02:00
jsonApiUrl,
headers,
deserialize
}
}