是否单一出口原则

  1. const headerKeys = ['sdp-app-id', 'sdp-biz-type', 'sdp-org-id', 'Accept-Language']
  2. const alias = {
  3. 'sdp-app-id': ['appId', '__app_id'],
  4. 'Accept-Language': ['language', 'lang', 'locale', '__lang']
  5. }
  6. const headers = {}
  7. // 初始化 从 url localStorage window.SDP_APP_DATA cookie 浏览器 中取值
  8. const searchParams = parse(window.location.search)
  9. const hashParams = parse(window.location.hash.replace(/^#[^?]+/, ''))
  10. const db = JSON.parse(localStorage.getItem('SDP_APP_DATA') || '{}')
  11. const global = window.SDP_APP_DATA || {}
  12. const dataSources = [searchParams, hashParams, db, global]
  13. dataSources.forEach((data) => {
  14. headerKeys.forEach((key) => {
  15. if (!headers[key]) {
  16. if (data[key]) {
  17. headers[key] = data[key]
  18. } else {
  19. const aliasKeys = alias[key] || []
  20. aliasKeys.some((aliasKey) => {
  21. const value = data[aliasKey]
  22. if (value) {
  23. headers[key] = value
  24. return true
  25. }
  26. return false
  27. })
  28. }
  29. }
  30. })
  31. })
  1. headerKeys.forEach((key) => {
  2. if (headers[key]) return
  3. dataSources.forEach((data) => {
  4. if (data[key]) return headers[key] = data[key]
  5. if (!alias[key]) return
  6. alias[key].forEach((aliasKey) => {
  7. const value = data[aliasKey]
  8. if (value) {
  9. headers[key] = value
  10. }
  11. })
  12. })
  13. })

image.png