Request Layer
This is the request layer used here at One Day Only to handle request tracking between clients and server, as well as optimistic updates.
The general idea:
We do not directly make api requests from our clients but rather we pass actions via a socket server, which will later respond with the data we need. This is great, but due to its very
asynchronous nature, its hard to keep track of requests. What this layer does is wrap each action with some meta information including a requestId
and a requestName
and then
stores each request in state along with its current status (pending
, complete
, failed
).
How to use
We need to target 4 areas of the system:
- Redux middleware - to intercept wrapped actions. sure we could make thunk actions, but its easier to understand whats going on when the action system is sync.
- Action creators - to wrap an action with the required meta data.
- Reducers - to handle state mutations and provide optimistic updates.
- Socket Server - to interpret the clientAction and properly format a responseAction.
/* Middleware */
import { requestMiddleware } from 'request-layer'
import io from 'socket.io-client'
const socket = io("http:// ...")
const store = createStore(
applyMiddleware(requestMiddleware(socket))
)
/* Action Creators */
import { serverAction } from 'request-layer'
export const someAction = (payload: Object, getRequestId: Function) => serverAction({
type: String,
payload,
meta: {
optimistic: Boolean,
requestName: String,
...additionalParams
}
}, getRequestId)
In addition to other properties, a _use_request_layer: true
property is set on the action. You can use this property in a middleware to hook into request-layer
server actions. Note: additionalParams
will get passed along with the status updates and can be used for custom reducers listening to status updates.
The reducer provided is actually a reducer enhancer meaning it will wrap your reducers and quietly change state. The reducerEnhancer will also enhance your store with a redux-optimist reducer
/* Reducer */
import { reducerEnhancer } from 'request-layer'
const roodReducer = combineReducers({ ... })
export default reducerEnhancer(roodReducer)
/* Socket Server */
import { serverMiddleware } from 'request-layer'
type Action = {
type: string,
payload: ?any,
meta: ?Object
}
type HandlerParams = {
action: ServerAction,
resolve: (res: ResponseAction) => RequestAction,
reject: (e: any) => RequestAction,
socket: Object
}
const actionHandler = (params: HandlerParams) => {}
serverMiddleware(actionHandler, socket)
Additionally, request-layer provides a react HOC
that passes a collection of tools into a components props. These tools can be used to get the status of requests and handle
complete/failed requests.
import React, { Component } from 'react'
import { requestTools, serverAction } from 'request-layer'
import { connect } from 'react-redux'
import _ from 'lodash'
const enhance = _.flowRight(
connect(state => ({requests: state.requests})),
requestTools
)
export default
enhance(class App extends Component {
addItem = item => {
store.dispatch(serverAction({
type: "ADD_ITEMS",
payload: item,
meta: {
requestName: "items.add"
}
}, id => {
this.props.trace(id)
.then(result => {
// result equals action.payload.result on the returning action
// request is complete
})
.catch(e => {
// request failed with error: e
})
}))
}
render() {
return this.props.pending("items.fetch",
<Loader />,
<div>
<Button disabled={this.props.pending("items.add")} onClick={this.addItem({name: "new item"})}>Add Item</Button>
{this.props.failed("items.add", "failed to add item")}
{this.props.complete("items.add", "successfully added item")}
</div>
)
}
})