[Feature request] Automatically stringify JSON
KaKi87 opened this issue · comments
Thanks
@mpetrunic If there's interest, I can make a PR for this.
Maybe you can first propose approach here (without breaking changes)? :)
Simple : reply.sse({ data: JSON.stringify({ 'foo': 'bar' }) })
keeps working but can be simplified with reply.sse({ data: { 'foo': 'bar' } })
, which currently has no use case since it sends [Object object]
.
Thanks
Ah I see, stringify data if it's an object. Yeah, I'm happy to accept PR with the changes.
Oh wow, I completely missed this issue. I'll have a look around tomorrow and get to it if nobody else started the PR.
In some cases, JSON.stringify
is not very good, and we need other libraries to improve stringify performance.
SSE common scenarios involve high-frequency requests. We need to reduce consumption.
Yeah, I was just making an example, in practice I guess the library that Fastify currently uses for serializing JSON should be used here.
just use JSON.stringify, we can edit this file.
https://github.com/mpetrunic/fastify-sse-v2/blob/master/src/sse.ts
export function isObject(value: any) {
return typeof value === 'object' && value !== null;
}
...
if (chunk.data) {
if (isObject(chunk.data)) {
payload += `data: ${JSON.stringify(chunk.data)}\n`;
} else {
payload += `data: ${chunk.data}\n`;
}
}