DEV Community

Parv Dave
Parv Dave

Posted on

Creating Custom Cookies

  1. create store for storing entries
  2. use Object.defineProperty to define 'myCookie' property with setters and getters and configurable set to true so you can redefine property
  3. getter - provide data from cookie
  4. if maxAge is not undefined, check if difference between time now and created at is bigger than maxAge, if yes, remove that entry from store and go to next entries otherwise construct a string and push to results array return joining with ;

  5. setter - accepts value

  • input looks like this: bfe=dev; max-age=1 so split by ; and first one is keyValue pair and second one is optional max-age, also also you can trim white spaces then you can split keyValuePair by "=" .
  • if there is no key or value we can return otherwise we can construct entry consisting of value and createAt time.
  • if we have optional option we need to take care of it we can split it by "=".
  • if their is option key with key 'max-age', make that string a number insert that maxAge on entry object to value of maxAge*1000 to get miliseconds set key and entry to store Map remember to set configuarable: true to be able to redefine property
function install() {
  // Map<string, {value: string, maxAge?: number, createdAt: number}>
  const store = new Map()
  // use getter and setter
  Object.defineProperty(document, 'myCookie', {
    get() {
      const result = []
      for (let [key, entry] of store.entries()) {
        if (entry.maxAge !== undefined) {
          if (Date.now() - entry.createdAt >= entry.maxAge) {
            // expire
            store.delete(key)
            continue
          }
        }

        result.push(`${key}=${entry.value}`)
      }
      return result.join('; ')
    },

    set(valueStr) {
     const [keyValuePair, option] = valueStr.replace(/ /g, '').split(';')
     const [key, value] = keyValuePair.split('=')

      if (!key || !value) return

      const entry = {
        value,
        createdAt: Date.now()
      }

      if(option) {
          const [optionKey, optionValue] = option.split('=')
            if (optionKey === 'max-age') {
            const maxAge = Number(optionValue)
            entry.maxAge = maxAge * 1000
         }
      }

      store.set(key, entry)
    },

   configurable: true
  })
}

// disable myCookie
function uninstall() {
  delete document.myCookie
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)