Last active
May 26, 2023 19:55
-
-
Save markgarrigan/d117014a3b9d64e82b48791ca22a94a5 to your computer and use it in GitHub Desktop.
Netlify Edge Function for SSE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function sse({ path, body }) { | |
let timerId; | |
const response = new ReadableStream({ | |
start(controller) { | |
timerId = setInterval(() => { | |
const msg = new TextEncoder().encode( | |
`data: hello at ${new Date().toUTCString()}\r\n\r\n`, | |
); | |
controller.enqueue(msg); | |
}, 1000); | |
}, | |
cancel() { | |
if (typeof timerId === "number") { | |
clearInterval(timerId); | |
} | |
}, | |
}); | |
return new Response(response, { | |
headers: { | |
"Content-Type": "text/event-stream", | |
}, | |
}); | |
} | |
export const config = () => { | |
return { | |
path: "/sse" | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<sse> | |
<h1>SSE</h1> | |
<ul> | |
<li each={ (message, i) in state.messages }> | |
{ message } | |
</li> | |
</ul> | |
<script> | |
export default { | |
state: { | |
messages: [] | |
}, | |
addMessage(message) { | |
this.state.messages.push(message); | |
this.update({ | |
messages: this.state.messages | |
}); | |
}, | |
onMounted(props, state) { | |
const sse = new EventSource('/sse'); | |
sse.onerror = (event) => { | |
console.error({ | |
event | |
}); | |
}; | |
sse.addEventListener("message", (event) => { | |
console.log(event.data); | |
this.addMessage(event.data); | |
}) | |
}, | |
onUpdated(props, state) { | |
console.log(state.messages); | |
} | |
} | |
</script> | |
</sse> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment