feat: add update route for robot

This commit is contained in:
RohitR311
2024-11-17 02:30:20 +05:30
parent baf8ce9ecb
commit e92bef2925

View File

@@ -57,6 +57,95 @@ router.get('/recordings/:id', requireSignIn, async (req, res) => {
}
})
/**
* PUT endpoint to update the name and limit of a robot.
*/
router.put('/recordings/:id', requireSignIn, async (req: AuthenticatedRequest, res) => {
try {
const { id } = req.params;
const { name, limit } = req.body;
// Validate input
if (!name && limit === undefined) {
return res.status(400).json({ error: 'Either "name" or "limit" must be provided.' });
}
// Fetch the robot by ID
const robot = await Robot.findOne({ where: { 'recording_meta.id': id } });
if (!robot) {
return res.status(404).json({ error: 'Robot not found.' });
}
// Update fields if provided
if (name) {
robot.set('recording_meta', { ...robot.recording_meta, name });
}
// Update the limit
if (limit !== undefined) {
const workflow = [...robot.recording.workflow]; // Create a copy of the workflow
// Ensure the workflow structure is valid before updating
if (
workflow.length > 0 &&
workflow[0]?.what?.[0]
) {
// Create a new workflow object with the updated limit
const updatedWorkflow = workflow.map((step, index) => {
if (index === 0) { // Assuming you want to update the first step
return {
...step,
what: step.what.map((action, actionIndex) => {
if (actionIndex === 0) { // Assuming the first action needs updating
return {
...action,
args: (action.args ?? []).map((arg, argIndex) => {
if (argIndex === 0) { // Assuming the first argument needs updating
return { ...arg, limit };
}
return arg;
}),
};
}
return action;
}),
};
}
return step;
});
// Replace the workflow in the recording object
robot.set('recording', { ...robot.recording, workflow: updatedWorkflow });
} else {
return res.status(400).json({ error: 'Invalid workflow structure for updating limit.' });
}
}
await robot.save();
const updatedRobot = await Robot.findOne({ where: { 'recording_meta.id': id } });
console.log('After save:', updatedRobot);
// Log the update
logger.log('info', `Robot with ID ${id} was updated successfully.`);
return res.status(200).json({ message: 'Robot updated successfully', robot });
} catch (error) {
// Safely handle the error type
if (error instanceof Error) {
logger.log('error', `Error updating robot with ID ${req.params.id}: ${error.message}`);
return res.status(500).json({ error: error.message });
} else {
logger.log('error', `Unknown error updating robot with ID ${req.params.id}`);
return res.status(500).json({ error: 'An unknown error occurred.' });
}
}
});
/**
* DELETE endpoint for deleting a recording from the storage.
*/