CoNarrative / framework-x

A reasonable programming framework.
https://framework-x.io
MIT License
19 stars 2 forks source link

Extract fetch-fx package from RealWorld example & publish #17

Closed alex-dixon closed 5 years ago

alex-dixon commented 5 years ago
  1. Separate package @framework-x/fetch-fx pulled from RealWorld example
  2. import into RealWorld example
import * as R from 'ramda'

const keys = ['body', 'bodyUsed', 'ok', 'status', 'statusText', 'headers', 'redirected', 'url', 'type']
const fetchFx = R.curry(({dispatch}, [urlOrReq, successEventOrEventVector, failureEventOrEventVector]) => {
  let isVector = { success: true, failure: true }
  let successEventName = successEventOrEventVector
  let failureEventName = failureEventOrEventVector
  if (typeof successEventOrEventVector === 'string') {
    isVector.success = false
  } else {
    successEventName = successEventOrEventVector[0]
  }
  if (typeof failureEventOrEventVector === 'string') {
    isVector.failure = false
  } else {
    failureEventName = failureEventOrEventVector[0]
  }

  let awesomeness = urlOrReq
  if (typeof urlOrReq !== 'string') {
    awesomeness = new Request(urlOrReq.url, R.dissoc('url', urlOrReq))
  }
  (async () => {
    const res = await fetch(awesomeness)
      .catch(e => dispatch(failureEventName,
        isVector.failure
        ? { res: e, args: failureEventOrEventVector[1] }
        : e))
    const data = R.pick(keys, res)
    const json = await res.json().catch(e => console.error('error .json()ing', e))
    if (res.ok) {
      dispatch(successEventName, isVector.success ? {
        res: R.assoc('json', json, data),
        args: successEventOrEventVector[1]
      } : R.assoc('json', json, data))
    } else {
      dispatch(failureEventName,
        isVector.failure
        ? { res: R.assoc('json', json, data), args: failureEventOrEventVector[1] }
        : R.assoc('json', json, data),)
    }
  })()
})

Needs access to dispatch via context (fx api with context 1st arg) or argument to a create fn.

const createFx = ({dispatch}) => fetchFx({dispatch})

// application
regFx('fetch', fetchFx.createFx({dispatch}))
alex-dixon commented 5 years ago

https://www.npmjs.com/package/@framework-x/fetch-fx