Skip to content

Instantly share code, notes, and snippets.

@danielkellyio
Created October 30, 2024 14:53
Show Gist options
  • Save danielkellyio/0908021672fe0bb3bf085503a24bd415 to your computer and use it in GitHub Desktop.
Save danielkellyio/0908021672fe0bb3bf085503a24bd415 to your computer and use it in GitHub Desktop.
serialize nuxt api endpoint data with devalue
// server/api/currentDate
import { stringify } from "devalue"
export default defineEventHandler(async (event) => {
const data = {
createAt: new Date(),
}
if (getHeader(event, 'Content-Type') === 'application/devalue') {
const dataToJSON = {
...data,
toJSON() {
return this;
}
}
return stringify(data) as unknown as typeof dataToJSON;
}
return data;
})
// app.vue
const { data } = await useFetch('/api/currentDate', {
headers:{
'Content-Type': "application/devalue"
},
transform(data) {
return devalue.parse(data as unknown as string) as typeof data;
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment