From 98e6489f73c12233dbdd7dc818dea47ea87744eb Mon Sep 17 00:00:00 2001 From: Shubham Varshney Date: Tue, 6 Feb 2024 13:45:49 +0530 Subject: [PATCH] af --- .../dao/repositories/ShortUrlRepository.java | 2 +- .../web/v1/controllers/TinyURLController.java | 16 ++++++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/main/java/code/shubham/core/tinyurl/dao/repositories/ShortUrlRepository.java b/src/main/java/code/shubham/core/tinyurl/dao/repositories/ShortUrlRepository.java index 562ef9b..af91e8a 100644 --- a/src/main/java/code/shubham/core/tinyurl/dao/repositories/ShortUrlRepository.java +++ b/src/main/java/code/shubham/core/tinyurl/dao/repositories/ShortUrlRepository.java @@ -11,7 +11,7 @@ public interface ShortUrlRepository extends JpaRepository { @Query(nativeQuery = true, - value = "SELECT url FROM short_urls WHERE key_name = ? AND (account_id IS NULL OR account_id = ?)") + value = "SELECT url FROM short_urls WHERE key_name = ? AND (account_id IS NULL OR account_id = ?) AND expiry_at > now()") Optional findURL(String shortUrl, Long accountId); } diff --git a/src/main/java/code/shubham/core/tinyurl/web/v1/controllers/TinyURLController.java b/src/main/java/code/shubham/core/tinyurl/web/v1/controllers/TinyURLController.java index 4b1a24e..a440656 100644 --- a/src/main/java/code/shubham/core/tinyurl/web/v1/controllers/TinyURLController.java +++ b/src/main/java/code/shubham/core/tinyurl/web/v1/controllers/TinyURLController.java @@ -19,7 +19,9 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import java.util.Date; import java.util.HashMap; +import java.util.Optional; @Slf4j @RestController @@ -30,12 +32,22 @@ public class TinyURLController { private final TinyURLService service; @GetMapping - public ResponseEntity get(@RequestParam("url") final String url) { + public ResponseEntity get(@RequestParam("url") final String url, + @RequestParam(value = "alias", required = false) final String alias, + @RequestParam(value = "ttlInSeconds", required = false) final Long ttlInSeconds) { if (StringUtils.isEmpty(url)) throw new InvalidRequestException("url", "url must not be null or empty"); - final ShortURL shortURL = ShortURL.builder().url(url).accountId(AccountIDContextHolder.get()).build(); + final ShortURL shortURL = ShortURL.builder() + .url(url) + .accountId(AccountIDContextHolder.get()) + .keyName(alias) + .expiryAt(Optional.ofNullable(ttlInSeconds) + .map(ttl -> new Date(System.currentTimeMillis() + (ttl * 1000))) + .orElse(null)) + .build(); + final String tinyURL = this.service.create(shortURL); return ResponseUtils.getDataResponseEntity(HttpStatus.CREATED.value(), new HashMap<>() { {