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 = 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 = 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;