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/react-server / src / middleware / fsMiddleware.ts
Size: Mime:
/**
 * @file this whole file is already done?
 */
import { resolveToRoot } from '@skava/bs'
import { Request, Response } from 'express'
import { fromReqResToDebug } from '../deps'

const expireSettings = {
  maxAge: process.env.BROWSER_MAX_CACHE_AGE,
  index: false,
}

function fromExtToContentType(ext: string) {
  switch (true) {
    case ext.includes('html'):
      return 'text/html'
    case ext.includes('json') || ext.includes('.map'):
      return 'application/json'
    default:
    case ext.includes('js'):
      return 'text/javascript'
  }
}

interface FileSendOptions {
  headers: {
    'Content-Type': 'text/html' | 'application/json' | 'text/javascript'
    [key: string]: any
  }
  [key: string]: any
}
function toResolvedFileMeta(
  resolvedPathname: string
): [string, FileSendOptions] {
  return [
    resolvedPathname,
    {
      headers: {
        'Content-Type': fromExtToContentType(resolvedPathname),
      },
    },
  ]
}

/**
 * @todo resolve to root same as express static
 * @see https://medium.com/@rajaraodv/webpack-hot-module-replacement-hmr-e756a726a07
 * @see http://code.fitness/post/2016/02/webpack-public-path-and-hot-reload.html
 */
// @lint - console logs take more statements
// eslint-disable-next-line
function fsMiddleware(req: Request, res: Response, next: Function) {
  const pathname = req.pathname || req.originalUrl

  if (process.env.NODE_ENV === 'production') {
    console.log('ignoring route, on deployment')
    next()
    return
  }

  if (pathname === undefined) {
    console.log('[react-server] unknown request', fromReqResToDebug(req))
    next()
  } else if (pathname.includes('client') && pathname.includes('js')) {
    const pathnameFixed = pathname.replace('client', 'client/')
    const resolvedPathname = resolveToRoot('dist/dist/bundled' + pathnameFixed)
    console.log('[react-server] client request ', resolvedPathname)
    res.sendFile(...toResolvedFileMeta(resolvedPathname))
  } else if (pathname.includes('hmr') && pathname.includes('js')) {
    const resolvedPathname = resolveToRoot('dist/dist/bundled' + pathname)
    console.log('[react-server] HMR_MIDDLEWARE ', resolvedPathname)
    res.sendFile(...toResolvedFileMeta(resolvedPathname))
  } else {
    console.log('[react-server] unknown request ', fromReqResToDebug(req))
    next()
  }
}

export { fsMiddleware }