request-layer

1.0.0 • Public • Published

Request Layer

Async action tracking

  • WHAT AND WHY (comment on how this was build for redux, alternate versions can be built for mobx or other state management patterns)
  • USAGE
  • USAGE WITH TRACING
  • USAGE WITH REQUEST TOOLS
  • OPTIMISTIC UPDATES
  • API

This is the request layer used here at One Day Only to handle request tracking between clients and server, as well as optimistic updates.

WHY:

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>
        )
    }
})

API

The API is described using flow-types for properties and parameters

clientMiddleware: (eventEmitter) => ReduxMiddleware

Creates a redux middleware for use on the client. Should be given an event emitter for subscribing to and emitting actions. This could be something like a a socket.io, or a WebSocket client.

type EventEmitter = {
	emit: (event: string, action: ReduxAction) => void,
	on: (event: string, cb: (action: ReduxAction) => void) => void
}

const store = createStore(
	rootReducer,
	applyMiddleware(
		clientMiddleware({emit: socket.emit, on: socket.on})
	)
)
requestAction: ([requestName, ] actionCreator) => (...params) => ServerAction

Wraps a redux actionCreator with some request information. The clientMiddleware will only manage actions that have been wrapped with requestAction. This produces a modified ServerAction.

type ServerAction = {
	type: string,
	payload?: any,
   	
	__request: {
		id: string, // uuid-v4 string
		name: string | null,
		status: string,
		timestamp: number,
		initial: boolean,
		
		resolve?: (action: ServerAction) => void,
		reject?: (action: ServerAction) => void
	}
}

const doSomething = requestAction("do.something", (payload) => ({
	type: "DO_SOMETHING",
	payload
}))
bindAndTrace: (actionCreators, dispatch) => boundActionCreators

Drop-in replacement for redux's bindActionCreators. This utility works in the same way as bindActionCreators, however in addition to binding each action creator with dispatch it adds a trace to the action in the form of a Promise. This promise resolves or rejects when the EventEmitter provided to the clientMiddleware responds with a matching action.

type ActionCreator = () => Action

type ActionCreators = {
	[actionCreatorName: string]: ActionCreator
} | ActionCreator

const actionCreators = {
	doSomething: doSomething
}
const boundActions = bindAndTrace(actionCreators, store.dispatch)

boundActions.doSomething()
	.then(action => {
		// Emitter responded with a COMPLETE_REQUEST action
	})
	.catch(action, => {
		// Emitter responded with a FAIL_REQUEST action
	})
requestReducer: (state, action) => state | newState

A reducer to add to the store. Stores requests and their statuses in state.

const rootReducer = combineReducers({
	// ... other application reducers
	
	requests: requestReducer
})

Readme

Keywords

none

Package Sidebar

Install

npm i request-layer

Weekly Downloads

4

Version

1.0.0

License

MIT

Last publish

Collaborators

  • julienvincent