Guest User

Untitled

a guest
Aug 14th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. import log from 'llog'
  2. import path from 'path'
  3. import fastifyStatic from 'fastify-static'
  4. import fastifyCompress from 'fastify-compress'
  5. import { service } from './service'
  6. import sdkData from './sdkData'
  7. import UA from 'browserslist-useragent'
  8.  
  9. const { src, legacySrc } = sdkData
  10.  
  11. service.register(fastifyCompress)
  12.  
  13. service.register(fastifyStatic, {
  14. root: path.resolve(process.cwd(), 'dist', 'sdks'),
  15. prefix: '/dist/sdks/'
  16. })
  17.  
  18. export const isModernBrowser = (userAgent) => {
  19. return UA.matchesUA(userAgent, {
  20. _allowHigherVersions: true,
  21. browsers: [
  22. "Chrome >= 66",
  23. "Safari >= 11.1",
  24. "iOS >= 11.3",
  25. "Firefox >= 60",
  26. "Edge >= 17"
  27. ]
  28. })
  29. }
  30.  
  31. export const redirectToClientJS = (request, reply) => {
  32. const userAgent = request.headers['user-agent']
  33. let srcForUserAgent = legacySrc
  34.  
  35. console.log({isModern: isModernBrowser(userAgent)})
  36.  
  37. if (isModernBrowser(userAgent)) {
  38. log.info('is modern browser')
  39. srcForUserAgent = src
  40. }
  41.  
  42.  
  43. log.info({msg: `request for JS lib received. Redirecting to ${srcForUserAgent}`, srcForUserAgent })
  44. reply.redirect(`${srcForUserAgent}`)
  45. }
  46.  
  47. service.get('/sdk.js', redirectToClientJS)
  48.  
  49. export const onListen = (err) => {
  50. if (err) {
  51. log.error(err)
  52. throw err
  53. }
  54. log.info(`service listening on ${service.server.address().port}`)
  55. }
  56.  
  57. // Run the service!
  58. service.listen(8000, '0.0.0.0', onListen)
Add Comment
Please, Sign In to add comment