summaryrefslogtreecommitdiff
path: root/backend/src/controllers/createRobot.ts
blob: dbc1959957a5c3859fd7a644f1ff7409aec1a7bd (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
67
import { Request, Response } from "express";
import { QueryResult } from "pg";
import { Server } from "socket.io";
import db from "../database/postgres.js";
import redisClient from "../database/redis.js";
import { ErrorResponse } from "../types/error.js";
import { CreateRequest } from "../types/request.js";
import { CreateRobotResponse, Robot } from "../types/robot.js";

const ROBOTS_CACHE_KEY = "allMyRobots";

async function createRobot(req: Request, res: Response) {
    const io: Server = req.app.get("io");

    const { name } = req.body as CreateRequest;

    if (!name || !name.trim()) {
        return res.status(400).json({
            message: "Robot name is required.",
        });
    }

    try {
        const createNewRobotQuery: QueryResult<Robot> = await db.query(
            `
        INSERT INTO robots
            (name, status, lat, lon, robot_positions) 
            VALUES ($1, $2, $3, $4, $5) 
        RETURNING
            id, name, status, lat, lon, robot_positions, created_at, updated_at;`,
            [name.trim(), "idle", 51.340863, 12.375919, JSON.stringify([])]
        );

        const newRobot = createNewRobotQuery.rows[0];

        // Delete old Redis cache, get all robots again and broadcast update to the frontend
        await redisClient.del(ROBOTS_CACHE_KEY);
        console.log("Redis cache deleted after robot creation.");

        const allRobotsQuery: QueryResult<Robot> = await db.query(
            "SELECT * FROM robots ORDER BY id;"
        );

        const allRobots = allRobotsQuery.rows;

        io.emit("robots_update", allRobots);
        console.log("WebSocket update with newly created robot.");

        const createRobotResponse: CreateRobotResponse = {
            message: "Robot successfully created.",
            robot: newRobot,
        };

        return res.status(201).json(createRobotResponse);
    } catch (error) {
        console.error("Error creating the robot: ", error);

        const errorResponse: ErrorResponse = {
            message: "Internal server error during robot creation.",
            error,
        };
        return res.status(500).json(errorResponse);
    }
}

export default createRobot;