manifest/nuxt/composables/api.js

43 lines
868 B
JavaScript

import jsonapi from 'jsonapi-serializer'
function idmap(arr, idattr = 'id') {
if (!arr) { return {} }
return arr.reduce((vse, i) => {
const id = i[idattr]
vse[id] = i
return vse
}, {})
}
export const useApi = () => {
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)
}
const jsonApiUrl = jezik => {
if (!jezik) {
jezik = 'sl'
}
return `${baseUrl}/${jezik}${jsonapiPath}`
}
return {
baseUrl: baseUrl,
jsonApiUrl,
headers,
deserialize
}
}