From c2638539e593de66ea368175a3c5b489ebe5cc7f Mon Sep 17 00:00:00 2001 From: Lucien Greathouse Date: Mon, 7 May 2018 13:53:35 -0700 Subject: [PATCH 1/2] Introduce new middleware API --- lib/Store.lua | 11 ++++++++--- lib/loggerMiddleware.lua | 6 +++--- lib/thunkMiddleware.lua | 6 +++--- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/lib/Store.lua b/lib/Store.lua index 8719533..db793c3 100644 --- a/lib/Store.lua +++ b/lib/Store.lua @@ -48,12 +48,17 @@ function Store.new(reducer, initialState, middlewares) table.insert(self._connections, connection) if middlewares then - local dispatch = Store.dispatch + local dispatch = function(...) + return self:dispatch(...) + end + for _, middleware in ipairs(middlewares) do - dispatch = middleware(dispatch) + dispatch = middleware(dispatch, self) end - self.dispatch = dispatch + self.dispatch = function(self, ...) + return dispatch(...) + end end return self diff --git a/lib/loggerMiddleware.lua b/lib/loggerMiddleware.lua index d3342a0..9bc922b 100644 --- a/lib/loggerMiddleware.lua +++ b/lib/loggerMiddleware.lua @@ -39,9 +39,9 @@ local loggerMiddleware = { outputFunction = print, } -function loggerMiddleware.middleware(next) - return function(store, action) - local result = next(store, action) +function loggerMiddleware.middleware(nextDispatch, store) + return function(action) + local result = nextDispatch(action) loggerMiddleware.outputFunction(("Action dispatched: %s\nState changed to: %s"):format( prettyPrint(action), diff --git a/lib/thunkMiddleware.lua b/lib/thunkMiddleware.lua index b4735e4..08c676b 100644 --- a/lib/thunkMiddleware.lua +++ b/lib/thunkMiddleware.lua @@ -4,12 +4,12 @@ This middleware consumes the function; middleware further down the chain will not receive it. ]] -local function thunkMiddleware(next) - return function(store, action) +local function thunkMiddleware(nextDispatch, store) + return function(action) if typeof(action) == "function" then return action(store) else - return next(store, action) + return nextDispatch(action) end end end From 36c653fbdf0fec4d88908b51ba08b49e5c6b37b2 Mon Sep 17 00:00:00 2001 From: Lucien Greathouse Date: Mon, 7 May 2018 14:16:08 -0700 Subject: [PATCH 2/2] Fix up the infinite recursion stuff --- lib/Store.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/Store.lua b/lib/Store.lua index db793c3..c688540 100644 --- a/lib/Store.lua +++ b/lib/Store.lua @@ -48,8 +48,9 @@ function Store.new(reducer, initialState, middlewares) table.insert(self._connections, connection) if middlewares then + local unboundDispatch = self.dispatch local dispatch = function(...) - return self:dispatch(...) + return unboundDispatch(self, ...) end for _, middleware in ipairs(middlewares) do