Skip to content

Commit

Permalink
Introduce new middleware API (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
LPGhatguy authored May 21, 2018
1 parent d1161cd commit abe2847
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 22 deletions.
14 changes: 11 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
# Rodux Changelog

## Current master
* No changes
* Added `combineReducers` utility, mirroring Redux's ([#9](https://github.com/Roblox/rodux/pull/9))
* Added `createReducer` utility, similar to `redux-create-reducer` ([#10](https://github.com/Roblox/rodux/pull/10))
* `type` is now required as a field on all actions
* Introduced middleware ([#13](https://github.com/Roblox/rodux/pull/13))
* Thunks are no longer enabled by default, use `Rodux.thunkMiddleware` to add them back.
* Added `Rodux.loggerMiddleware` as a simple debugger
* The middleware API changed in [#29](https://github.com/Roblox/rodux/pull/29) in a backwards-incompatible way!
* Middleware now run left-to-right instead of right-to-left!
* Errors thrown in `changed` event now have correct stack traces ([#27](https://github.com/Roblox/rodux/pull/27))

## 1.0.0 (TODO: Date)
* Initial release
## Public Release (December 13, 2017)
* Initial release!
23 changes: 17 additions & 6 deletions docs/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,30 +153,41 @@ local reducer = createReducer(initialState, {
```

## Middleware
Rodux provides an API that allows changing the way that actions are dispatched called *middleware*. To attach middlewares to a store, pass a list of middleware as the third argument to `Store.new`.
Rodux provides an API that allows changing the way that actions are dispatched called *middleware*. To attach middleware to a store, pass a list of middleware as the third argument to `Store.new`.

!!! warn
The middleware API changed in [#29](https://github.com/Roblox/rodux/pull/29) -- middleware written against the old API will not work!

A single middleware is just a function with the following signature:

```
(next) -> (store, action) -> result
(nextDispatch, store) -> (action) -> result
```

That is, middleware is a function that accepts the next middleware to apply and returns a new function. That function takes the `Store` and the current action and can dispatch more actions, log to output, or do network requests!
A middleware is a function that accepts the next dispatch function in the *middleware chain*, as well as the store the middleware is being used with, and returns a new function. That function is called whenever an action is dispatched and can dispatch more actions, log to output, or perform any side effects!

A simple version of Rodux's `loggerMiddleware` is as easy as:

```lua
local function simpleLogger(next)
return function(store, action)
local function simpleLogger(nextDispatch, store)
return function(action)
print("Dispatched action of type", action.type)

return next(store, action)
return nextDispatch(action)
end
end
```

Rodux also ships with several middleware that address common use-cases.

To apply middleware, pass a list of middleware as the third argument to `Store.new`:

```lua
local store = Store.new(reducer, initialState, { simpleLogger })
```

Middleware runs from left to right when an action is dispatched. That means that if a middleware does not call `nextDispatch` when handling an action, any middleware after it will not run.

### Rodux.loggerMiddleware
A middleware that logs actions and the new state that results from them.

Expand Down
15 changes: 11 additions & 4 deletions lib/Store.lua
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,19 @@ function Store.new(reducer, initialState, middlewares)
table.insert(self._connections, connection)

if middlewares then
local dispatch = Store.dispatch
for _, middleware in ipairs(middlewares) do
dispatch = middleware(dispatch)
local unboundDispatch = self.dispatch
local dispatch = function(...)
return unboundDispatch(self, ...)
end

self.dispatch = dispatch
for i = #middlewares, 1, -1 do
local middleware = middlewares[i]
dispatch = middleware(dispatch, self)
end

self.dispatch = function(self, ...)
return dispatch(...)
end
end

return self
Expand Down
69 changes: 66 additions & 3 deletions lib/Store.spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -36,30 +36,93 @@ return function()
end)

it("should modify the dispatch method when middlewares are passed", function()
local middlewareInstantiateCount = 0
local middlewareInvokeCount = 0
local passedDispatch
local passedStore
local passedAction

local function reducer(state, action)
if action.type == "test" then
return "test state"
end

return state
end

local function testMiddleware(next)
return function(store, action)
local function testMiddleware(nextDispatch, store)
middlewareInstantiateCount = middlewareInstantiateCount + 1
passedDispatch = nextDispatch
passedStore = store

return function(action)
middlewareInvokeCount = middlewareInvokeCount + 1
next(store, action)
passedAction = action

nextDispatch(action)
end
end

local store = Store.new(reducer, "initial state", { testMiddleware })

expect(middlewareInstantiateCount).to.equal(1)
expect(middlewareInvokeCount).to.equal(0)
expect(passedDispatch).to.be.a("function")
expect(passedStore).to.equal(store)

store:dispatch({
type = "test",
})

expect(middlewareInstantiateCount).to.equal(1)
expect(middlewareInvokeCount).to.equal(1)
expect(passedAction.type).to.equal("test")

store:flush()

expect(store:getState()).to.equal("test state")

store:destruct()
end)

it("should execute middleware left-to-right", function()
local events = {}

local function reducer(state)
return state
end

local function middlewareA(nextDispatch, store)
table.insert(events, "instantiate a")
return function(action)
table.insert(events, "execute a")
return nextDispatch(action)
end
end

local function middlewareB(nextDispatch, store)
table.insert(events, "instantiate b")
return function(action)
table.insert(events, "execute b")
return nextDispatch(action)
end
end

local store = Store.new(reducer, 5, { middlewareA, middlewareB })

expect(#events).to.equal(2)
expect(events[1]).to.equal("instantiate b")
expect(events[2]).to.equal("instantiate a")

store:dispatch({
type = "test",
})

expect(#events).to.equal(4)
expect(events[3]).to.equal("execute a")
expect(events[4]).to.equal("execute b")
end)

it("should send an initial action with a 'type' field", function()
local lastAction
local callCount = 0
Expand Down
6 changes: 3 additions & 3 deletions lib/loggerMiddleware.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
6 changes: 3 additions & 3 deletions lib/thunkMiddleware.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit abe2847

Please sign in to comment.