Created
May 15, 2023 06:37
-
-
Save rbaul/d32a5619343bcc98f15e6086f9f4eb02 to your computer and use it in GitHub Desktop.
RateLimit Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.rbaul.rate_limit; | |
import lombok.AllArgsConstructor; | |
import lombok.Builder; | |
import lombok.Getter; | |
import lombok.NoArgsConstructor; | |
import lombok.Setter; | |
import org.springframework.util.CollectionUtils; | |
import java.util.HashMap; | |
import java.util.Map; | |
@Getter | |
@Setter | |
@AllArgsConstructor | |
@NoArgsConstructor | |
@Builder | |
public class RateLimitModel { | |
private String key; | |
private boolean regex; | |
private Map<String, RateLimitModel> nested = new HashMap<>(); | |
public void addChildren(String part, String key) { | |
if (nested == null) { | |
nested = new HashMap<>(); | |
} | |
nested.put(part, RateLimitModel.builder() | |
.key(key) | |
.regex(isRegex(part)).build()); | |
} | |
private boolean isRegex(String part) { | |
return part.startsWith("{") && part.endsWith("}"); | |
} | |
public boolean isNestedExist(String part) { | |
return !CollectionUtils.isEmpty(nested) && nested.containsKey(part); | |
} | |
public static String getKey(RateLimitModel parent, String[] url, int index, String lastKey) { | |
if (parent == null) { | |
return lastKey; | |
} | |
String key = parent.getKey() == null ? lastKey : parent.getKey(); | |
if (index == url.length || CollectionUtils.isEmpty(parent.getNested())) { | |
return key; | |
} | |
RateLimitModel next = parent.getNested().get(url[index]); | |
if (next == null) { | |
next = parent.getNested().values().stream() | |
.filter(RateLimitModel::isRegex) | |
.findAny().orElse(null); | |
} | |
return getKey(next, url, index + 1, key); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private final RateLimitModel root = new RateLimitModel(); | |
String path = "GET /url/demo" | |
String[] splitBySlashes = path.split("/"); | |
RateLimitModel current = root; | |
for (int i = 1; i < splitBySlashes.length; i++) { | |
if (!current.isNestedExist(splitBySlashes[i])) { | |
current.addChildren(splitBySlashes[i], null); | |
} | |
current = current.getNested().get(splitBySlashes[i]); | |
} | |
current.setKey(rateLimitApiProperties.getKey()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment