this repo has no description
4
fork

Configure Feed

Select the types of activity you want to include in your feed.

🧷 Add a build function that does not panic

+26 -16
+26 -16
src/glimit.gleam
··· 37 37 38 38 import gleam/erlang/process.{type Subject} 39 39 import gleam/option.{type Option, None, Some} 40 + import gleam/result 40 41 import glimit/actor 41 42 42 - /// The rate limiter's public interface. 43 + /// A rate limiter. 43 44 /// 44 45 pub type RateLimiter(a, b, id) { 45 46 RateLimiter( ··· 124 125 /// function or handler function is missing. 125 126 /// 126 127 pub fn build(config: RateLimiterBuilder(a, b, id)) -> RateLimiter(a, b, id) { 127 - RateLimiter( 128 - subject: case 129 - actor.new(config.per_second, config.per_minute, config.per_hour) 130 - { 131 - Ok(subject) -> subject 132 - Error(_) -> panic as "Failed to start rate limiter actor" 133 - }, 134 - identifier: case config.identifier { 135 - Some(identifier) -> identifier 136 - None -> panic as "Identifier function is required" 137 - }, 138 - handler: case config.handler { 139 - Some(handler) -> handler 140 - None -> panic as "Handler function is required" 141 - }, 128 + case try_build(config) { 129 + Ok(limiter) -> limiter 130 + Error(message) -> panic as message 131 + } 132 + } 133 + 134 + /// Build the rate limiter, but return an error instead of panicking. 135 + /// 136 + pub fn try_build( 137 + config: RateLimiterBuilder(a, b, id), 138 + ) -> Result(RateLimiter(a, b, id), String) { 139 + use subject <- result.try( 140 + actor.new(config.per_second, config.per_minute, config.per_hour) 141 + |> result.map_error(fn(_) { "Failed to start rate limiter actor" }), 142 142 ) 143 + use identifier <- result.try(case config.identifier { 144 + Some(identifier) -> Ok(identifier) 145 + None -> Error("Identifier function is required") 146 + }) 147 + use handler <- result.try(case config.handler { 148 + Some(handler) -> Ok(handler) 149 + None -> Error("Handler function is required") 150 + }) 151 + 152 + Ok(RateLimiter(subject: subject, handler: handler, identifier: identifier)) 143 153 } 144 154 145 155 /// Apply the rate limiter to a request handler or function.