造一个 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 的核心代码了。

当然这个库里对一些特殊字符处理的代码没有过多提及,因为纠结这些过于细节的代码意义并不大。而且上面已经做了一些特殊字符处理了,已经涵盖大部分使用情况了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容

  • 1、整理记录一下js-cookie这个库的使用 一个简单,轻巧的JavaScript API,用于处理Cookie...
    长情G阅读 2,889评论 0 15
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 21,766评论 1 92
  • 前言 web到目前为止走过了1.0、2.0、移动互联网、本地应用化几个阶段,这使得js变得炙手可热,许多原来在se...
    白昔月阅读 1,718评论 3 6
  • 原文链接:https://segmentfault.com/a/1190000004556040[https://...
    R_X阅读 396评论 0 1
  • JavaScript从入门到放弃 1如何写好JS? 各司其职。即css就负责样式的部分,HTML就负责结构的部分,...
    冬晴分身阅读 109评论 0 0