manifest/nuxt/composables/api.js

36 lines
810 B
JavaScript
Raw Normal View History

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
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 {
2023-06-15 20:45:38 +02:00
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
}, {})
}