summaryrefslogtreecommitdiff
path: root/backend/src/controllers/createRobot.ts
diff options
context:
space:
mode:
Diffstat (limited to 'backend/src/controllers/createRobot.ts')
-rw-r--r--backend/src/controllers/createRobot.ts61
1 files changed, 61 insertions, 0 deletions
diff --git a/backend/src/controllers/createRobot.ts b/backend/src/controllers/createRobot.ts
new file mode 100644
index 0000000..fa483af
--- /dev/null
+++ b/backend/src/controllers/createRobot.ts
@@ -0,0 +1,61 @@
+import { Request, Response } from "express";
+import { QueryResult } from "pg";
+import db from "../database/postgres.js";
+import redisClient from "../database/redis.js";
+import { CreateRequest } from "../types/request.js";
+import { Robot } from "../types/robot.js";
+
+const ROBOTS_CACHE_KEY = "allMyRobots";
+
+async function createRobot(req: Request, res: Response) {
+ const io = 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.");
+
+ return res.status(201).json({
+ message: "Robot successfully created.",
+ robot: newRobot,
+ });
+ } catch (error) {
+ console.error("Error creating the robot: ", error);
+ return res.status(500).json({
+ message: "Internal server error during robot creation.",
+ error,
+ });
+ }
+}
+
+export default createRobot;
+