From 90f543ad22d233eb3ae8f26ff8fc8e3235ff1bce Mon Sep 17 00:00:00 2001 From: IvaDey Date: Mon, 22 Jul 2024 22:31:54 +0300 Subject: [PATCH] docs: add example of server-side events in controllers.md --- docs/docs/controllers.md | 41 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/docs/docs/controllers.md b/docs/docs/controllers.md index 17cf7a9e971..e145e75fdb1 100644 --- a/docs/docs/controllers.md +++ b/docs/docs/controllers.md @@ -488,6 +488,47 @@ This example will produce a response with status code 400 and "Not a number" mes See our guide on [HttpExceptions to throw customer HttpExceptions](/docs/throw-http-exceptions.md) ::: +## Server-side events + +::: warning +`compression` middleware should be disabled for correct SSE work +::: + +### Example + +```typescript +import { Controller } from '@tsed/di'; +import { Res } from '@tsed/common'; +import { Get } from '@tsed/schema'; + +@Controller('/sse') +export class Ctrl { + @Get('/events') + events(@Res() response: Res) { + let intervalId: ReturnType; + + response.on('close', () => { + console.log('connection closed'); + clearInterval(intervalId); + }); + response.on('end', () => { + console.log('connection ended'); + clearInterval(intervalId); + }); + + response.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', + }); + + intervalId = setInterval(() => { + response.write(`data: Current timestamp: ${Date.now()}\n\n`); + }, 1000); + } +} +``` + ## Inject Request and Response You can use a decorator to inject the Request in order to retrieve information from the request that you cannot get