manifest/nuxt/composables/api.js

33 lines
785 B
JavaScript

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