From 3aa22e11c0f78ec0b8b899f38c677378d8a732b7 Mon Sep 17 00:00:00 2001 From: Joris Moriau Date: Fri, 12 Feb 2016 10:35:12 +0100 Subject: [PATCH] - add_filters no longer needs to be called explicitly it will be lazily called if needed. - the Filter middleware no longer needs to be the first in the handlers array. - before and after methods will raise an exception if a filter for the requested path is already defined. --- src/kemal/middleware/filters.cr | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/kemal/middleware/filters.cr b/src/kemal/middleware/filters.cr index e51ca80..a0e0c2d 100644 --- a/src/kemal/middleware/filters.cr +++ b/src/kemal/middleware/filters.cr @@ -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