npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

request-layer

v1.0.0

Published

A complete client => socket request solution

Downloads

35

Readme

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