Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/graphql / src / bootstrapper / setup / requestMiddleware.ts
Size: Mime:
import { Request as RequestChain } from 'uxui-modules/oneRequest'
// import { isTrue } from 'uxui-modules/exotic'
import { setConfig, config } from 'uxui-modules/oneRequest/config'
import {
  middlewareForLocalStorage,
  staticFixtureMiddleware,
} from 'uxui-modules/oneRequest/middleware'
import {
  GET,
  POST,
  FETCHREQUEST,
  partnerId,
  campaignId,
  shouldIncudeCampaignId,
  storeId,
  appid,
  locale,
} from '../../bootstrapper/api/config'
import { getURL, endpoints, callDetails } from '../../deps/transformRequestProxy'

// Todo isTruish is not available in uxui-module
const isTruish = x => x === true || x === 'true' || /^["|']?true["|']?$/.test(x)

const storeKey = isTruish(process.env.SHOULD_USE_LOWERCASE_STORE_ID) ? 'storeid' : 'storeId'

const constantAndDefault = {
  partnerId,
  [storeKey]: storeId,
  appid,
  locale,
}

if (isTruish(shouldIncudeCampaignId)) {
  constantAndDefault.campaignId = campaignId
}

setConfig({
  GET,
  POST,
  FETCHREQUEST,
  // should not need this..
  // partnerId,
  // campaignId,
  [storeKey]: storeId,
  appid,
  locale,
  //
  constantParams: constantAndDefault,
  defaultParams: constantAndDefault,
})

config.set('constantParams', constantAndDefault)

// this is how it's done in express
// endpoints.map(fromRouteToProxy)
// const route = endpoints[index]
// const proxyConfig = getProxyUrl(route, callDetails[route])

function proxyMiddleware(requestChain, eventData = {}) {
  if (eventData.type !== 'toRequest') return

  const method = requestChain.get('method') || FETCHREQUEST
  async function interceptRequestWithProxy(url, params) {
    // @todo doesn't cover subroutes like submitorder/return
    const afterApi = url.split('api/').pop()
    const finalUrl = url.split('/').shift()

    console.log('[uxui-apis] proxymiddleware: ', finalUrl)
    const [error, response] = await method(url, params)

    if (error) {
      throw error
    } else {
      // const { authCookies, onCookie } = createCookieHacker()
      // response.cookies =
      return [error, response]
    }
  }
  requestChain.setMethod(interceptRequestWithProxy)
}

// @todo @fixme seemingly middleware will muck with request method
// RequestChain.middleware.set('proxy', proxyMiddleware)

// if (IS_FIXTURES_ENABLED) {
//   // RequestChain.middleware.set('staticData', staticFixtureMiddleware)
// }
// if (DISABLE_CACHE) {
//   // console.log('Should Be Getting Cached')
//   RequestChain.middleware.set('persistance', middlewareForLocalStorage)
// } else {
//   // console.log('Should Not Be Getting Cached!!!')
// }