razshare / sveltekit-sse

Server Sent Events with SvelteKit
https://www.npmjs.com/package/sveltekit-sse
MIT License
301 stars 9 forks source link

Passing generics to SourceSelect #57

Closed jonashoen closed 3 weeks ago

jonashoen commented 1 month ago

First of all thanks for creating this library! Its the first time I'm having fun working with SSE.

I tried to use the json function but noticed that the typing is kinda odd to me.

When creating a listener with source you can pass in a generic which then isn't passed down to the select function: https://github.com/razshare/sveltekit-sse/blob/df70401357727037e57e672cc1a9b62bb706674d/src/lib/types.external.js#L169

Because of this the type of the readable store returned by the json function is always any.

But in my opinion it would also be more useful to specify the generic when calling select instead of source because different events can emit different kinds of data.

What are your thoughts on that? Am I missing something?

Thanks!

razshare commented 4 weeks ago

Hello @jonashoen , thank you for the issue!

Yes, I agree with you, source is not a good place to specify a generic.

But I also don't think source::select is a good place, because that returns a Readable<string> by default.

The source::select::json and source::select::transform functions should each specify the generic type.

I've just released a new version with these changes v0.13.8

In short, you can now do this

<!-- +page.svelte -->
<script lang="ts">
  import { source } from 'sveltekit-sse'

  type User = {
    username: string
  }

  const user = 
    source('/my-event')
      .select('user')
        .json<User>()
</script>

{#if $user}
  <h3>{$user.username}</h3>
{/if}

Let me know if this solves your issue.

jonashoen commented 3 weeks ago

Hey @razshare, yeah this is great!

Thanks for the change :)