From 891107c442c8b707acaf959b83b2141505fcf61d Mon Sep 17 00:00:00 2001 From: Kharec Date: Sun, 1 Mar 2026 10:07:16 +0100 Subject: [PATCH] refactor: extract lookup helper, use idiomatic pipelines, remove unused imports --- src/storage.gleam | 44 ++++++++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/src/storage.gleam b/src/storage.gleam index 813eee4..1b0774b 100644 --- a/src/storage.gleam +++ b/src/storage.gleam @@ -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)