-
-
Notifications
You must be signed in to change notification settings - Fork 9
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
Event-based emit support? #49
Comments
Hello @TimKieu , A similar question has been asked in #34 and in #16 The last example uses an older api of the library, though it should still give you an idea how to do it. The general idea is that you need to somehow identify a user, using an actual account or just an anonymous session id, it doesn't matter which way you do it. All that matters is that you have some string that identifies a unique client. Then you create some global state that maps the user's id to an emitter function, the one you get when you call Something like this. /** @type {Map<string,(eventName:string,data:string)=>import('sveltekit-sse').Unsafe<void,Error>>} */
const someGlobalMap = new Map()
export function POST({ request }) {
return produce(
function start({ emit }) {
const sessionId = request.headers.get('session-id') ?? ''
if (!sessionId) {
return function stop() {
console.error('Client session id not found.')
}
}
// Save the emit function.
// This will also indicate to you that the client is "online".
someGlobalMap.set(sessionId, emit)
},
{
stop() {
// Client goes "offline", so remove the emit map.
const sessionId = request.headers.get('session-id') ?? ''
if (!sessionId) {
return
}
someGlobalMap.delete(sessionId)
},
},
)
} This piece of code doesn't take into account that the same client may open you application from more than 1 browser tab, you'll need to add your own logic to implement that. There are many ways to do that, which is beyond the scope of this library.
Also you probably want to move Let me know if this addresses your question. |
@razshare thanks much for your advice. |
Yes, obviously your map would have to be backed by some database, a broker, or something like that in cases of a distributed system, or maybe you don't even need specifically a map, some other data structure could fit better. In any case, the idea remains the same: save your emitter so that you can retrieve it later. |
@TimKieu I've added a FAQ section with a few more details and a possible solution using Postgre, regarding this distributed systems matter and event forwarding. |
@razshare Great! Thank you much indeed! |
Current example uses polling-interval emit events.
if we have a stable connection, can we do emit fired by a given event?
For example, an order is updated from a client page, it updates server DB (REST/trpc/FormSubmit), then trigger SSE emit when update DB sucessfully or REST/trpc/FormSubmit workflow completed.
The text was updated successfully, but these errors were encountered: