Skip to content

Commit

Permalink
Update payload to follow SSE requirements, also now returns a JSON pa…
Browse files Browse the repository at this point in the history
…yload
  • Loading branch information
jeffplays2005 committed Sep 15, 2024
1 parent 8966a78 commit 771ed50
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
8 changes: 8 additions & 0 deletions client/src/models/__generated__/schema.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions server/src/middleware/__generated__/swagger.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 17 additions & 4 deletions server/src/service-layer/controllers/EventController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ export class EventController extends Controller {
}
}

/**
* Streams the current signup count for events.
* Note that when testing this on swagger, the connection will remain open.
*/
@Get("/reservations/stream")
public async streamSignupCounts(
@Request() req: express.Request
Expand All @@ -78,13 +82,22 @@ export class EventController extends Controller {
req.res.setHeader("Access-Control-Allow-Origin", "*")
req.res.setHeader("Connection", "keep-alive")
req.res.flushHeaders()

const eventService = new EventService()
// Create something that updates every second

const signupCount = await eventService.getActiveReservationsCount() // Fetch the current signup count
req.res.write(
`data: ${JSON.stringify({ reservation_count: signupCount })}\n\n`
)

// Create something that updates every 5 seconds
const interValID = setInterval(async () => {
const signupCount = await eventService.getActiveReservationsCount() // Fetch the current signup count
req.res?.write(`${signupCount}\n`) // res.write() instead of res.send()
}, 1000)
// NOTE: We use double new line because SSE requires this to indicate we're ready for the next event
// We also need the data: to indicate data payload
req.res.write(
`data: ${JSON.stringify({ reservation_count: signupCount })}\n\n`
) // res.write() instead of res.send()
}, 5000)

// If the connection drops, stop sending events
req.res?.on("close", () => {
Expand Down

0 comments on commit 771ed50

Please sign in to comment.