Files
url-shortener/src/main/java/tk/draganczuk/url/Routes.java
Przemek Dragańczuk 7f275bf6af Sqlite as storage backend (#1)
Some platforms has some problems with file locking, so I was forced to use an alternative. SQLite seems be the best option currently available


* Migrated to an sqlite database

* Removed unnecessary IOExceptions

* Removed an util class not needed anymore

* Updated README.md and docker-compose.yml to reflect new storage mechanism
2020-03-24 09:07:25 +01:00

60 lines
1.2 KiB
Java

package tk.draganczuk.url;
import org.eclipse.jetty.http.HttpStatus;
import spark.Request;
import spark.Response;
import java.io.IOException;
public class Routes {
private static UrlRepository urlRepository;
static {
urlRepository = new UrlRepository();
}
public static String getAll(Request req, Response res) {
return String.join("\n", urlRepository.getAll());
}
public static String addUrl(Request req, Response res) {
String longUrl = req.queryParams("long");
String shortUrl = req.queryParams("short");
if (shortUrl == null || shortUrl.isBlank()) {
shortUrl = Utils.randomString();
}
if (Utils.validate(shortUrl)) {
return urlRepository.addUrl(longUrl, shortUrl);
} else {
res.status(HttpStatus.BAD_REQUEST_400);
return "shortUrl not valid ([a-z0-9]+)";
}
}
public static String goToLongUrl(Request req, Response res) {
String shortUrl = req.params("shortUrl");
var longUrlOpt = urlRepository
.findForShortUrl(shortUrl);
if (longUrlOpt.isEmpty()) {
res.status(404);
return "";
}
res.redirect(longUrlOpt.get());
return "";
}
public static String delete(Request req, Response res) {
String shortUrl = req.params("shortUrl");
urlRepository.deleteEntry(shortUrl);
return "";
}
}