index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const path = require('path')
  2. const defu = require('defu')
  3. const defaults = require('./defaults')
  4. module.exports = function createServePlaceholder (_options) {
  5. // Assign default options
  6. const options = defu(_options, defaults)
  7. return function servePlaceholderMiddleware (req, res, next) {
  8. // If response already sent, skip
  9. if (res.writableEnded) {
  10. return
  11. }
  12. // Get url from req object
  13. const url = req.url.split('?')[0]
  14. // Get ext of requst url
  15. const ext = path.extname(url)
  16. // Try to find a handler based on ext
  17. let handler = options.handlers[ext]
  18. // Skip middleware is handler is explictly set to false
  19. if (handler === false) {
  20. return next()
  21. }
  22. // In case of no handler guessed
  23. if (typeof handler === 'undefined') {
  24. if (options.skipUnknown) {
  25. // Skip this middleware
  26. return next()
  27. } else {
  28. // Use 'default' handler
  29. handler = 'default'
  30. }
  31. }
  32. // Set statusCode
  33. if (options.statusCode) {
  34. res.statusCode = options.statusCode
  35. }
  36. // Try to set appreciate mime type based on handler
  37. const mime = options.mimes[handler]
  38. if (mime) {
  39. res.setHeader('Content-Type', mime)
  40. }
  41. // Prevent caching
  42. if (options.noCache) {
  43. res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate') // HTTP 1.1
  44. res.setHeader('Pragma', 'no-cache') // HTTP 1.0
  45. res.setHeader('Expires', '0') // Proxies
  46. }
  47. // Try to find placeholder based on handler
  48. const placeholder = options.placeholders[handler]
  49. // Send placeholder and end response
  50. res.end(placeholder)
  51. }
  52. }