mirror of
https://gitea.invidious.io/iv-org/shard-kemal.git
synced 2024-08-15 00:53:36 +00:00
Merge pull request #85 from jmoriau/fix-filter-middleware
Fix filter middleware
This commit is contained in:
commit
52538afb10
1 changed files with 28 additions and 3 deletions
|
@ -17,6 +17,11 @@ module Kemal::Middleware
|
|||
process_filter(context, :after)
|
||||
end
|
||||
|
||||
def filter_for_path_type_defined?(path, type)
|
||||
lookup = @tree.find radix_path(type, path)
|
||||
lookup.found? && lookup.payload.is_a? Block
|
||||
end
|
||||
|
||||
private def process_filter(context, type)
|
||||
lookup = @tree.find radix_path(type, context.request.path)
|
||||
if lookup.found? && lookup.payload.is_a? Block
|
||||
|
@ -28,6 +33,19 @@ module Kemal::Middleware
|
|||
private def radix_path(type : Symbol, path)
|
||||
"/#{type}#{path}"
|
||||
end
|
||||
|
||||
class BeforeFilterAlreadyDefinedException < Exception
|
||||
def initialize(path)
|
||||
super "A before-filter is already defined for path: '#{path}'."
|
||||
end
|
||||
end
|
||||
|
||||
class AfterFilterAlreadyDefinedException < Exception
|
||||
def initialize(path)
|
||||
super "An after-filter is already defined for path: '#{path}'."
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
class Block
|
||||
|
@ -35,18 +53,25 @@ module Kemal::Middleware
|
|||
def initialize(&@block : HTTP::Server::Context -> _)
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
def add_filters
|
||||
Kemal.config.add_handler Kemal::Middleware::Filter.new
|
||||
unless filter = Kemal.config.handlers.any? { |handler| handler.is_a? Kemal::Middleware::Filter }
|
||||
filter = Kemal::Middleware::Filter.new
|
||||
Kemal.config.add_handler filter
|
||||
end
|
||||
filter
|
||||
end
|
||||
|
||||
def before(path = "*", options = {} of Symbol => String, &block : HTTP::Server::Context -> _)
|
||||
filter = Kemal.config.handlers.first as Kemal::Middleware::Filter
|
||||
filter = (Kemal.config.handlers.find { |handler| handler.is_a? Kemal::Middleware::Filter } || add_filters) as Kemal::Middleware::Filter
|
||||
raise Kemal::Middleware::Filter::BeforeFilterAlreadyDefinedException.new(path) if filter.filter_for_path_type_defined?(path, :before)
|
||||
filter.add :before, path, options, &block
|
||||
end
|
||||
|
||||
def after(path = "*", options = {} of Symbol => String, &block : HTTP::Server::Context -> _)
|
||||
filter = Kemal.config.handlers.first as Kemal::Middleware::Filter
|
||||
filter = (Kemal.config.handlers.find { |handler| handler.is_a? Kemal::Middleware::Filter } || add_filters) as Kemal::Middleware::Filter
|
||||
raise Kemal::Middleware::Filter::AfterFilterAlreadyDefinedException.new(path) if filter.filter_for_path_type_defined?(path, :after)
|
||||
filter.add :after, path, options, &block
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue