Replies: 2 comments
-
Right now, if json/ object is returned from the nitro API, there is mismatch on client-side for types. An option to specify custom serializer would be awesome! Just wondering we already have @nuxt/devalue module, wondering if the same can be used for this purpose? |
Beta Was this translation helpful? Give feedback.
0 replies
-
poc import { uneval } from 'devalue'
import type { EventHandler, EventHandlerRequest } from 'h3/dist/index'
export function defineUnevalEventHandler<TReq extends EventHandlerRequest, TRet>(fn: EventHandler<TReq, TRet>) {
return defineEventHandler(async (event) => {
try {
const returnValue = await fn(event)
event.node.res.end(uneval(returnValue))
}
catch (err: any) {
event.node.res.writeHead(500)
const returnValue = JSON.parse(JSON.stringify(err, Object.getOwnPropertyNames(err)))
const { message = undefined, ...rest } = returnValue
event.node.res.end(`throw new Error(${uneval(message)}, ${uneval(rest)})`)
}
}) as EventHandler<TReq, TRet>
}
import { defineUnevalEventHandler } from '../handler'
export default defineUnevalEventHandler((event) => {
return {
article: 'hello world!',
date: new Date(),
set: new Set(),
map: new Map([
['key', 'value'],
['key2', 'value2'],
]),
}
})
import { defineUnevalEventHandler } from '../handler'
export default defineUnevalEventHandler((event) => {
throw new Error('boom')
})
{article:"hello world!",date:new Date(1699258213021),set:new Set([]),map:new Map([["key","value"],["key2","value2"]])}
throw new Error("boom", {
stack: "Error: boom\n at \u003Canonymous> ...(rest of the stack)"
}) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
I am using nitro with Nuxt3.
as described in #804, we can only send json to the client.
with nuxt-trpc I am able provide my custom serializer like https://trpc.io/docs/server/data-transformers#different-transformers-for-upload-and-download shows, using
superjson
when client -> server anduneval
in server -> client.with this approach I am serializing the response to string, then serialize this string to json again with json-rpc overheads.
I am looking for a way to optimize this output, a custom serializer in h3/nitro would be a perfect fit.
is it possible to do something like I described?
Beta Was this translation helpful? Give feedback.
All reactions