Skip to content

Commit

Permalink
Create /events/reservations/stream SSE endpoint
Browse files Browse the repository at this point in the history
This endpoint creates a stream with keep-alive headers that continuously streams the number of active reservations.
  • Loading branch information
jeffplays2005 committed Sep 15, 2024
1 parent bd655d0 commit 3f3771c
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 1 deletion.
11 changes: 11 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.

30 changes: 30 additions & 0 deletions server/src/middleware/__generated__/routes.ts

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

12 changes: 12 additions & 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.

36 changes: 35 additions & 1 deletion server/src/service-layer/controllers/EventController.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import EventService from "data-layer/services/EventService"
import { EventSignupBody } from "service-layer/request-models/EventRequests"
import { EventSignupResponse } from "service-layer/response-models/EventResponse"
import { Body, Controller, Post, Route, SuccessResponse } from "tsoa"
import {
Get,
Body,
Controller,
Post,
Route,
Request,
SuccessResponse
} from "tsoa"
import express from "express"

@Route("events")
export class EventController extends Controller {
Expand Down Expand Up @@ -58,4 +67,29 @@ export class EventController extends Controller {
return { error: "Failed to sign up for event." }
}
}

@Get("/reservations/stream")
public async streamSignupCounts(
@Request() req: express.Request
): Promise<void> {
// Set the required headers for SSE
req.res.setHeader("Cache-Control", "no-cache")
req.res.setHeader("Content-Type", "text/event-stream")
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 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)

// If the connection drops, stop sending events
req.res?.on("close", () => {
clearInterval(interValID) // Clear the loop
req.res?.end()
})
}
}

0 comments on commit 3f3771c

Please sign in to comment.