From fab29242508923c42f01513fae52ee52c92fef88 Mon Sep 17 00:00:00 2001 From: SinTan1729 Date: Tue, 8 Nov 2022 18:23:41 -0600 Subject: [PATCH] Avoid adding duplicate shortUrl --- src/main/java/tk/draganczuk/url/Routes.java | 7 +++++-- src/main/resources/public/js/main.js | 19 +++++++++++++++---- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/main/java/tk/draganczuk/url/Routes.java b/src/main/java/tk/draganczuk/url/Routes.java index 91a780b..f67de52 100644 --- a/src/main/java/tk/draganczuk/url/Routes.java +++ b/src/main/java/tk/draganczuk/url/Routes.java @@ -30,12 +30,15 @@ public class Routes { } String shortUrl = split[1]; shortUrl = shortUrl.toLowerCase(); + + var shortUrlPresent = urlRepository + .findForShortUrl(shortUrl); - if (Utils.validate(shortUrl)) { + if (shortUrlPresent.isEmpty() && Utils.validate(shortUrl)) { return urlRepository.addUrl(longUrl, shortUrl); } else { res.status(HttpStatus.BAD_REQUEST_400); - return "shortUrl not valid ([a-z0-9-_]+)"; + return "shortUrl not valid or already in use"; } } diff --git a/src/main/resources/public/js/main.js b/src/main/resources/public/js/main.js index c9a8190..312fd55 100644 --- a/src/main/resources/public/js/main.js +++ b/src/main/resources/public/js/main.js @@ -72,11 +72,22 @@ const submitForm = () => { method: "POST", body: `${longUrl.value};${shortUrl.value}` }) - .then(_ => { - longUrl.value = ""; - shortUrl.value = ""; + .then((res) => { + if (!res.ok) { + controls = document.querySelector(".pure-controls"); + errBox = document.createElement("p"); + errBox.setAttribute("id", "errBox"); + errBox.setAttribute("style", "color:red"); + errBox.innerHTML = "Short URL not valid or already in use"; + controls.appendChild(errBox); + } + else { + document.getElementById("errBox")?.remove(); + longUrl.value = ""; + shortUrl.value = ""; - refreshData(); + refreshData(); + } }); };