refactor: extract lookup helper, use idiomatic pipelines, remove unused imports
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import gleam/dict.{type Dict}
|
||||
import gleam/erlang/process
|
||||
import gleam/option.{type Option, None, Some}
|
||||
import gleam/option.{type Option}
|
||||
import gleam/otp/actor
|
||||
|
||||
const max_requests_per_minute = 10
|
||||
@@ -17,40 +17,44 @@ pub type StorageMsg {
|
||||
ResetRateLimits
|
||||
}
|
||||
|
||||
fn lookup_paste(state: StorageState, key: String) -> Option(String) {
|
||||
state.pastes
|
||||
|> dict.get(key)
|
||||
|> option.from_result
|
||||
}
|
||||
|
||||
pub fn handle_message(state: StorageState, msg: StorageMsg) {
|
||||
case msg {
|
||||
CreatePaste(key, content, reply) -> {
|
||||
let new_state =
|
||||
StorageState(dict.insert(state.pastes, key, content), state.rate_limits)
|
||||
let new_pastes =
|
||||
state.pastes
|
||||
|> dict.insert(key, content)
|
||||
process.send(reply, True)
|
||||
actor.continue(new_state)
|
||||
actor.continue(StorageState(new_pastes, state.rate_limits))
|
||||
}
|
||||
PeekPaste(key, reply) -> {
|
||||
let content = case dict.get(state.pastes, key) {
|
||||
Ok(value) -> Some(value)
|
||||
Error(_) -> None
|
||||
}
|
||||
process.send(reply, content)
|
||||
process.send(reply, lookup_paste(state, key))
|
||||
actor.continue(state)
|
||||
}
|
||||
GetPaste(key, reply) -> {
|
||||
let content = case dict.get(state.pastes, key) {
|
||||
Ok(value) -> Some(value)
|
||||
Error(_) -> None
|
||||
}
|
||||
let new_pastes = dict.delete(state.pastes, key)
|
||||
let new_state = StorageState(new_pastes, state.rate_limits)
|
||||
let content = lookup_paste(state, key)
|
||||
let new_pastes =
|
||||
state.pastes
|
||||
|> dict.delete(key)
|
||||
process.send(reply, content)
|
||||
actor.continue(new_state)
|
||||
actor.continue(StorageState(new_pastes, state.rate_limits))
|
||||
}
|
||||
CheckRateLimit(ip, reply) -> {
|
||||
let current_count =
|
||||
dict.get(state.rate_limits, ip)
|
||||
let count =
|
||||
state.rate_limits
|
||||
|> dict.get(ip)
|
||||
|> option.from_result
|
||||
|> option.unwrap(0)
|
||||
let allowed = current_count < max_requests_per_minute
|
||||
let allowed = count < max_requests_per_minute
|
||||
let new_limits = case allowed {
|
||||
True -> dict.insert(state.rate_limits, ip, current_count + 1)
|
||||
True ->
|
||||
state.rate_limits
|
||||
|> dict.insert(ip, count + 1)
|
||||
False -> state.rate_limits
|
||||
}
|
||||
process.send(reply, allowed)
|
||||
|
||||
Reference in New Issue
Block a user