Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature request] Automatically stringify JSON #80

Open
KaKi87 opened this issue Mar 9, 2024 · 10 comments
Open

[Feature request] Automatically stringify JSON #80

KaKi87 opened this issue Mar 9, 2024 · 10 comments

Comments

@KaKi87
Copy link

KaKi87 commented Mar 9, 2024

Thanks

@millette
Copy link

@mpetrunic If there's interest, I can make a PR for this.

@mpetrunic
Copy link
Owner

Maybe you can first propose approach here (without breaking changes)? :)

@KaKi87
Copy link
Author

KaKi87 commented Jun 17, 2024

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

@mpetrunic
Copy link
Owner

Ah I see, stringify data if it's an object. Yeah, I'm happy to accept PR with the changes.

@millette
Copy link

millette commented Jul 1, 2024

Oh wow, I completely missed this issue. I'll have a look around tomorrow and get to it if nobody else started the PR.

@daimalou
Copy link
Contributor

In some cases, JSON.stringify is not very good, and we need other libraries to improve stringify performance.

@daimalou
Copy link
Contributor

SSE common scenarios involve high-frequency requests. We need to reduce consumption.

@KaKi87
Copy link
Author

KaKi87 commented Sep 24, 2024

Yeah, I was just making an example, in practice I guess the library that Fastify currently uses for serializing JSON should be used here.

@daimalou
Copy link
Contributor

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`;
    }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants