summaryrefslogtreecommitdiff
path: root/backend/src/controllers/getRobots.ts
blob: 80b430fd68fd02b39e49585bdabc16647d26b119 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { Request, Response } from "express";
import { QueryResult } from "pg";
import db from "../database/postgres.js";
import redisClient from "../database/redis.js";
import { ErrorResponse } from "../types/error.js";
import { Robot, RobotsResponse } from "../types/robot.js";

const CACHE_TTL = 10;
const ROBOTS_CACHE_KEY = "allMyRobots";

async function getRobots(_req: Request, res: Response) {
    try {
        // Check if Redis has cached data to send to frontend
        const cachedData = await redisClient.get(ROBOTS_CACHE_KEY);

        if (cachedData) {
            console.log("Data served from Redis cache.");
            const robots: Robot[] = JSON.parse(cachedData);

            const simulationRunning = robots?.every(
                (robot) => robot.status === "moving"
            );

            const response: RobotsResponse = {
                source: "cache",
                robots,
                simulationRunning,
            };

            return res.status(200).json(response);
        }

        // Else query database, then save in Redis cache and send to frontend
        const robotsQuery: QueryResult<Robot> = await db.query(
            "SELECT * FROM robots ORDER BY id;"
        );
        const robots = robotsQuery.rows;

        const simulationRunning = robots?.every(
            (robot) => robot.status === "moving"
        );
        
        await redisClient.set(ROBOTS_CACHE_KEY, JSON.stringify(robots), {
            EX: CACHE_TTL,
        });

        console.log("Cache miss: data queried from PostgreSQL.");
        const response: RobotsResponse = {
            source: "database",
            robots,
            simulationRunning,
        };

        return res.status(200).json(response);
    } catch (error) {
        console.error("Failed to load the robots: ", error);
        const errorResponse: ErrorResponse = {
            message: "Internal server error while loading the robots.",
            error,
        };

        return res.status(500).json(errorResponse);
    }
}

export default getRobots;