Delete a Model (DELETE /api/models/:id)
Relevant source files
The following files were used as context for generating this wiki page:The DELETE /api/models/:id endpoint provides a mechanism to permanently remove a model record from the database. This is a destructive operation and is protected to ensure only authorized users can perform it. Access is restricted to users with an 'admin' role, which is determined at login based on their email address format.
This functionality is exposed to the end-user through a "Delete" button in the model details modal on the web interface. When an admin user clicks this button, a request is sent to the server, which validates the user's session and, if authorized, proceeds to delete the specified model from the MongoDB collection.
Endpoint Definition
The endpoint is defined within the Express application and uses the DELETE HTTP method to signify a resource deletion request.
- Method:
DELETE - Path:
/api/models/:id - Handler Location:
server.js
Sources: server.js:93-98
Path Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | The MongoDB _id of the model to delete. |
Sources: server.js:93
Authorization
Access to this endpoint is controlled by the isAdmin middleware. This function checks if a user session exists and if the user's role is set to 'admin'. If the user is not an admin, the server responds with a 403 Forbidden status and an error message, preventing the deletion operation.
Sources: server.js:37-40, server.js:93
The isAdmin middleware logic is defined as follows:
const isAdmin = (req, res, next) => {
if (req.session.user && req.session.user.role === 'admin') next();
else res.status(403).json({ message: 'Admin required' });
};
Sources: server.js:37-40
The user role is assigned during the login process based on the email address. An email ending in @admin.com grants the 'admin' role.
Sources: server.js:28-32
Request Flow
The process of deleting a model involves the client-side interface, the server-side API, and the database. The following sequence diagram illustrates the end-to-end flow for a successful deletion by an admin user.
This diagram shows the interaction between the user, the frontend, the backend API, and the database to delete a model.
Sources: public/index.html:48, public/index.html:159, server.js:93-98
Backend Implementation
The backend logic for the delete endpoint is handled within the main server.js file. It uses a try...catch block for error handling.
Sources: server.js:93-98
Core Logic
Upon receiving a request, and after the isAdmin middleware grants access, the handler executes the Model.findByIdAndDelete() Mongoose method. This method finds a document by its _id (passed as req.params.id) and removes it from the collection.
app.delete("/api/models/:id", isAdmin, async (req, res) => {
try {
await Model.findByIdAndDelete(req.params.id);
res.json({ message: 'Deleted' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
Sources: server.js:93-98
Responses
The endpoint provides distinct responses for success, authorization failure, and server errors.
| Status Code | Condition | Response Body |
|---|---|---|
200 OK | The model was successfully deleted. | { "message": "Deleted" } |
403 Forbidden | The user is not authenticated as an admin. | { "message": "Admin required" } |
500 Internal Server Error | A database or other server-side error occurred. | { "error": "<error_message>" } |
Sources: server.js:39, server.js:95-97
Frontend Integration
The frontend, defined in public/index.html, includes a "Delete" button within a modal view. This button is only visible to users with the 'admin' role.
Sources: public/index.html:48, public/index.html:78-82
deleteModel() Function
When the "Delete" button is clicked, the deleteModel() JavaScript function is invoked. This function is not explicitly defined in the provided index.html file, but its onclick handler is present. Based on the pattern of other functions, it would send a fetch request to the DELETE /api/models/:id endpoint using the currentId variable, which is set when the modal is opened. After a successful response, it would likely call fetchModels() to refresh the UI.
The button is wired up as follows:
<button onclick="deleteModel()" id="deleteBtn" class="px-4 py-2 bg-red-600 text-white rounded hidden">Delete</button>
Sources: public/index.html:48
The visibility of this button is controlled by the login() function, which removes the hidden class for admin users.
function login() {
// ...
if (data.role === 'admin') {
// ...
document.getElementById('deleteBtn').classList.remove('hidden');
}
// ...
}
Sources: public/index.html:78-82
Related Python Implementation
The repository also contains a Python script, model_database.py, which defines a class for managing a JSON-based model database. It includes a remove_model method that provides similar functionality by deleting a model entry from a dictionary and saving the result to a JSON file. This demonstrates an alternative, file-based implementation of the same core feature.
def remove_model(self, name):
"""Remove a model by name."""
if name in self.models:
del self.models[name]
self.save_data()
print(f"🗑️ Removed model: {name}")
else:
print(f"❌ Model '{name}' not found.")
Sources: model_database.py:38-45