UNPKG

1.99 kBMarkdownView Raw
1# Request Layer
2
3This is the request layer used here at One Day Only to handle request tracking between clients and server, as well as optimistic updates.
4
5## The general idea:
6
7We 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
8asynchronous 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
9stores each request in state along with its current status (`pending`, `complete`, `failed`).
10
11## How to use
12
13We need to target 4 areas of the system:
14
15+ 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.
16+ Action creators - to wrap an action with the required meta data.
17+ Reducers - to handle state mutations and provide optimistic updates.
18+ Socket Server - to interpret the clientAction and properly format a responseAction.
19
20```javascript
21/* Middleware */
22import { requestMiddleware } from '@odo/request-layer'
23import io from 'socket.io-client'
24
25const socket = io("http:// ...")
26const store = createStore(
27 applyMiddleware(requestMiddleware(socket))
28)
29```
30
31```javascript
32/* Action Creators */
33import { serverAction } from '@odo/request-layer'
34
35export const someAction = (payload: Object, getRequestId: Function) => serverAction({
36 type: String,
37 payload,
38 meta: {
39 optimistic: Boolean,
40 requestName: String
41 }
42}, getRequestId)
43```
44
45The 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
46redux-optimist reducer
47```javascript
48/* Reducer */
49import { reducerEnhancer } from '@odo/request-layer'
50
51const roodReducer = combineReducers({ ... })
52export default reducerEnhancer(roodReducer)
53```
\No newline at end of file