From f531fc487c25340f055adf2b08935ed7d7caf94c Mon Sep 17 00:00:00 2001 From: Santiago Lo Coco Date: Tue, 5 Nov 2024 19:06:06 +0100 Subject: [PATCH] Refactor code --- src/api.py | 46 +++++++++++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/src/api.py b/src/api.py index 9624ac2..68ed601 100644 --- a/src/api.py +++ b/src/api.py @@ -24,21 +24,9 @@ def create_endpoint(): data = request.get_json() new_url = data.get("url") - if new_url is None or not is_valid_url(new_url): - return jsonify({"status": "error", "message": "Invalid or missing URL"}), 400 - - existing_endpoint = get_endpoint_by_url(new_url) - if existing_endpoint: - return ( - jsonify( - { - "status": "error", - "message": "Endpoint already exists", - "id": existing_endpoint["id"], - } - ), - 409, - ) + endpoint_exists = check_endpoint_exists(data, new_url) + if endpoint_exists: + return endpoint_exists endpoint_id = add_endpoint_to_db(new_url) return jsonify({"id": endpoint_id, "url": new_url}), 201 @@ -58,14 +46,15 @@ def update_endpoint(endpoint_id): data = request.get_json() new_url = data.get("url") - if not new_url or not is_valid_url(new_url): - return jsonify({"status": "error", "message": "Invalid or missing URL"}), 400 + endpoint_exists = check_endpoint_exists(data, new_url) + if endpoint_exists: + return endpoint_exists updated = update_endpoint_in_db(endpoint_id, new_url) if updated: return "", 204 else: - return jsonify({"status": "error", "message": "Endpoint not found"}), 404 + return jsonify({"message": "Endpoint not found"}), 404 @api.route("/api/endpoints/", methods=["DELETE"]) @@ -74,9 +63,28 @@ def delete_endpoint(endpoint_id): if deleted: return "", 204 else: - return jsonify({"status": "error", "message": "Endpoint not found"}), 404 + return jsonify({"message": "Endpoint not found"}), 404 @api.route("/api/health", methods=["GET"]) def health(): return jsonify({"status": "ok"}) + + +def check_endpoint_exists(data, new_url): + new_url = data.get("url") + + if not new_url or not is_valid_url(new_url): + return jsonify({"message": "Invalid or missing URL"}), 400 + + existing_endpoint = get_endpoint_by_url(new_url) + if existing_endpoint: + return ( + jsonify( + { + "message": "Endpoint already exists", + "id": existing_endpoint["id"], + } + ), + 409, + )