Created
October 30, 2024 14:53
-
-
Save danielkellyio/0908021672fe0bb3bf085503a24bd415 to your computer and use it in GitHub Desktop.
serialize nuxt api endpoint data with devalue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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