造一個 js-cookie 輪子

項目源碼:https://github.com/Haixiang6123/my-js-cookie

預覽鏈接:http://yanhaixiang.com/my-js-cookie/

參考輪子:https://www.npmjs.com/package/js-cookie

Cookie 相信大家都不陌生,但是很多時候我們都是這樣:“啊,我這個地方要用 Cookie 了,怎麼辦?沒事,裝一個 npm 包嘛”,或者去 MDN 去抄一兩個函數。沒什麼機會手寫一個 js-cookie 的庫,今天就帶大家一起來寫一個 js-cookie 的小庫。

從零開始

首先,我們要摒棄所有所謂的“設計模式”,做一個最 Low 的版本:只有 get(key)set(key, value)del(key) 3 個 API。

通過對 MDN、菜鳥教程、掘金博客的大量閱讀,很快就寫出了最簡單的 API。

get

document.cookie 長這樣:a=1&b=2。將 document.cookie 字符串轉化成 Object,在轉化過程中判斷是否存在對應的 key,如果有就返回對應的 value 即可。

function get(key: string): string | null {
  const cookiePairs = document.cookie ? document.cookie.split('; ') : []

  const cookieStore: Record<string, string> = {}

  cookiePairs.some(pair => {
    const [curtKey, ...curtValues] = pair.split('=')

    cookieStore[curtKey] = curtValues.join('=') // 有可能 value 存在 '='

    return curtKey === key // 如果相等時,就會 break
  })

  return key ? cookieStore[key] : null
}

注意:cookie 的值有可能裏會有 '=' 號,所以split('=') 後的,還要再 join('=') 一下變回原來的值。比如:a=123=456,join 後的 value 還是 123=456而不是 123

set

單純 set 或 add 一個 cookie 更簡單,只需要

document.cookie = `${key}=${value}`

但其實,一個 cookie 不只有 key 和 value,還有 expires 過期時間以及 path 路徑。一個完整的 set 應該長這樣。

document.cookie = `${key}=${value}; expires=${expires}; path=${path}`

當然,我們不希望 set 函數的入參變得很冗餘,所以這裏的入參設計爲:key, value, attributes 3 個。其中,attributes 是個對象,裏面爲 cookie 的屬性:expires, path。

interface Attributes {
  path: string; // Cookie 對應路徑
  expires?: string | number | Date // Cookie 的過期時間,第N天過期
}

爲了提高擴展性,我們再造一個 defaultAttributes 作爲默認參數傳入。

const TWENTY_FOUR_HOURS = 864e5
const defaultAttributes: Attributes = {path: '/'}

function set(key: string, value: string, attributes = defaultAttributes): string | null {
  attributes = {...defaultAttributes, ...attributes}

  if (attributes.expires) {
    // 將過期天數轉爲 UTC string
    if (typeof attributes.expires === 'number') {
      attributes.expires = new Date(Date.now() + attributes.expires * TWENTY_FOUR_HOURS)
      attributes.expires = attributes.expires.toUTCString()
    }
  }

  // 獲取 Cookie 其它屬性的字符串形式,如 "; expires=1; path=/"
  const attrStr = Object.entries(attributes).reduce((prevStr, attrPair) => {
    const [attrKey, attrValue] = attrPair

    if (!attrValue) return prevStr

    prevStr += `; ${attrKey}`

    // attrValue 有可能爲 truthy,所以要排除 true 值的情況
    if (attrValue === true) return prevStr

    // 排除 attrValue 存在 ";" 號的情況
    prevStr += `=${attrValue.split('; ')[0]}`

    return prevStr
  }, '')

  return document.cookie = `${key}=${value}${attrStr}`
}

上面的操作也非常簡單。首先對 expires 做了轉成 UTC 時間戳的處理,然後把 attributes 拍扁成一個 string,最後追加到 ${key}=${value} 後面。

這裏可能有人會對這段神祕代號 864e5 感興趣。這是 24 小時的毫秒值,具體可見 Stackoverflow

del

刪除一個 cookie 一件再簡單不過的事了。上面不是已經實現了 set 了麼,我們把 expires 設置爲 -1 天就好了。

/**
 * 刪除某個 Cookie
 */
function del(key: string, attributes = defaultAttributes) {
  // 將 expires 減 1 天,Cookie 自動失敗
  set(key, '', {...attributes, expires: -1})
}

編碼與解碼

雖然沒人要求 cookie 要做編碼與解碼,但是爲了更 cookie 不受一些特殊字符的干擾,我們還要需要對 cookie 的值做編碼與解碼的工作。

這裏普及一下:對於 cookie 的行爲是有規範,從 RFC 2109RFC 2965 再到 RFC6265。有興趣的可以看一看。好的,我知道你沒有興趣了。

咳咳,回到代碼。這一步需要在 set 裏做編碼,在 get 裏做解碼。一般來說,習慣用 encodeURIComponent 和 decodeURIComponent 做編碼和解碼的工作。

function get(key: string): string | null {
  ...

  cookiePairs.some(pair => {
    const [curtKey, ...curtValue] = pair.split('=')

    try {
      // 解碼
      const decodeedValue = decodeURIComponent(curtValue.join('='))  // 有可能 value 存在 '='
      cookieStore[curtKey] = decodeedValue
    } catch (e) {}

    return curtKey === key // 如果相等時,就會 break
  })

  return key ? cookieStore[key] : null
}

function set(key: string, value: string, attributes = defaultAttributes): string | null {
  ...
  
  // 編碼
  value = encodeURIComponent(value)

  ...

  return document.cookie = `${key}=${value}${attrStr}`
}

so easy ~ 不過,上面的 encodeURIComponentdecodeURIComponent 有點像硬編碼一樣寫在了代碼裏了,不妨抽象出來用 defaultConverter 來封裝編碼和解碼兩個操作。

export interface Converter {
  encode: (text: string) => string // 編碼
  decode: (text: string) => string // 解碼
}

// 默認 Cookie 值的轉換器
export const defaultConverter: Converter = {
  encode(text: string) {
    return text.replace(ASCII_HEX_REGEXP, encodeURIComponent)
  },
  decode(text: string) {
    return text.replace(ASCII_HEX_REGEXP, decodeURIComponent)
  },
}

set 和 get 函數將會更抽象了。

function get(key: string): string | null {
  ...
      // 解碼
      const decodeedValue = defaultConverter.decode(curtValue.join('='))  // 有可能 value 存在 '='
  ...
}

function set(key: string, value: string, attributes = defaultAttributes): string | null {
  ...
  // 編碼
  value = defaultConverter.encode(value)
  ...
}

配置中心

上面只是“我們覺得”習慣上會用 encodeURIComponentdecodeURIComponent 來編碼和解碼。別人可能會用別的編碼和解碼函數來完成,因此需要提供一個配置中心給開發者。一次配置,以後都會按照初始設置來 setget

像下面的例子,初始時設定 expires 爲 1 天,以後直接 set(xxx, yyy) 設置 Cookie 過期時間都是 1 天后。

// 初始配置
Cookies.atributes = { expires: 1 }
Cookies.converter = {
  encode(text: string) {
    return "hello"
  },
  decode(text: string) {
    return "world"
  },
}

Cookies.set('aaa', 111) // 過期時間爲 1 天,值 aaa="hello"
Cookies.set('bbb', 222) // 過期時間爲 1 天,值 bbb="hello"

Cookies.get('aaa') // "world"
Cookies.get('bbb') // "world"

要實現上面的效果,我們需要首先提供一個初始配置中心的入口,然後暴露配置中心。而且還需要將 attributes 和 converter 配置存下來。

let customAttributes: Attributes = defaultAttributes
let customConverter: Converter = defaultConverter

function get(key: string): string | null {
  ...
  const decodedValue = customConverter.decode(curtValue.join('='))  // 有可能 value 存在 '='
  ...
}

/**
 * 設置 Cookie key-val 對
 */
function set(key: string, value: string, attributes = defaultAttributes): string | null {
  attributes = {...customAttributes, ...attributes}
  
  ...

  value = customConverter.encode(value)
  ...
}

/**
 * 刪除某個 Cookie
 */
function del(key: string, attributes = defaultAttributes) {
  // 將 expires 減 1 天,Cookie 自動失敗
  set(key, '', {...attributes, expires: -1})
}

const Cookies = {
  get,
  set,
  del,
  attributes: customAttributes,
  converter: customConverter,
}

export default Cookies

上面導出了一個函數,每次使用 attributes 的時候都會先和 customAttributes 合併,每次編碼解碼的時候會使用 customCoverter

上面這麼實現在使用的時候會很麻煩,每次修改配置就要手動去做合併。

Cookies.attributes = {...Cookies.attributes, ...{ expires: 2 } }

那我們想:好吧,暴露兩個函數做合併唄。

...
function withAttributes(myAttributes: Attribute) {
  customAttributes = {...customAttributes, ...myAttributes}
}
function withAttributes(myConverter: Converter) {
  customConverter = {...customConverter, ...myConverter}
}

const Cookies = {
  get,
  set,
  del,
  withAttributes,
  withConverter
}

export default Cookies

還有沒有問題?有!把 customAttributescustomConverter 放到全局很容易造成污染。想象一下,這個項目很大,有人偷偷把 customAttributes 裏的 expires 改成 3 天,下個要開發的人可能完全不知情。所以,把這配置項改爲局部是十分有必要的。

直接給出實現:

function init(initConverter: Converter, initAttributes: Attributes) {
  function get(key: string): string | null {
    ...
    const decodeedValue = initConverter.decode(curtValue.join('='))
    ...
  }

  function set(key: string, value: string, attributes = customAttributes): string | null {
    ...
    attributes = {...initAttributes, ...attributes}
    value = initConverter.encode(value)
    ...
  }

  function del(key: string, attributes = customAttributes) {
    set(key, '', {...attributes, expires: -1})
  }

  function withConverter(customConverter: Converter) {
    return init({...this.converter, ...customConverter}, this.attributes)
  }

  function withAttributes(customAttributes: Attributes) {
    return init(this.converter, {...this.attributes, ...customAttributes})
  }

  return {
    get,
    set, 
    del, 
    attributes: initAttributes,
    converter: initConverter, 
    withAttributes,
    withConverter
  }
}

export default init(defaultConverter, defaultAttributes)

上面把配置項存放到了生成對象的 attributesconverter 裏了。調用 withConverterwithAttributes 的時候,再次調用 init 來創建 Cookies 對象。好處是 withXXX 後是一個全新的對象,不會造成全局污染。

const myCookies = Cookies.withAttributes({ expires: 2 }) // 新對象

attrCookies.set('aaa', 1) // 2 天后過期

Coookies.set('aaa', 1) // 沒有過期時間

把配置項“凍結”

上面的代碼還有個問題,attributesconverter 還是被暴露了出來,萬一哪個憨憨手抖改了,後面的接盤俠還是會傻眼。

這裏可以用 Object.create 來生成對象,並在第 2 個參數裏用 Object.freeze 把對象 atributesconverter“凍住”。

function init(initConverter: Converter, initAttributes: Attributes) {
  ...

  return Object.create(
    {get, set, del, withConverter, withAttributes},
    {
      converter: {value: Object.freeze(initConverter)}, // 被凍動了
      attributes: {value: Object.freeze(initAttributes)}, // 被凍動了
    }
  )
}

export default init(defaultConverter, defaultAttributes)

關於 Object.create 第 2 個參數的內容可以看 Object.defineProperties,它的意義是描述對象屬性,這裏的描述就是“凍動”了。比如:

Cookies.attributes = 1

console.log(Cookies.attributes) // 返回依然是 {path: '/'},不會變成 1

到此,一個 js-cookie 庫已經完美實現了!

總結

init 函數創建對象,對象裏有以下函數

  1. get 函數:將 document.cookie 字符串轉化爲 Object 形式,轉化過程中判斷是否在存 key,如果有就返回對應 value
  2. set 函數:把 attributes stringify,然後追加到 key=value 後, document.cookie = ${key}=${value}${attrStr}
  3. del 函數:調用 set,把 expires 設置爲 -1 天,cookie 直接過期被刪除
  4. withAttributes:更新 attributes 配置,並返回全新 Cookie 對象
  5. withConverter:更新 converter 配置,並返回全新 Cookie 對象

爲什麼要用函數生成對象這麼麻煩?因爲要解決全局污染的問題。需要把 attributesconverter 兩個配置存到函數參數裏,並且通過 withAttributeswithConverter 調用 init 返回新 Cookie 對象。

爲什麼要凍動 attributesconverter,還是因爲怕有憨憨把這兩玩意改了。

最後

上面的代碼其實就是 js-cookie 的核心代碼了。

當然這個庫裏對一些特殊字符處理的代碼沒有過多提及,因爲糾結這些過於細節的代碼意義並不大。而且上面已經做了一些特殊字符處理了,已經涵蓋大部分使用情況了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章