eduardosilvapereira
6/14/2018 - 12:15 PM

storageApi.js

(() => {
    const _hasLocalStorage = () => {
      return ('localStorage' in window) && window.localStorage !== null
    }

    const _localStorage_setItem = (storageDataId, storageData) => {
      window.localStorage.setItem(storageDataId, storageData)
      return true
    }

    const _localStorage_getItem = storageDataId => {
      const storageData = window.localStorage.getItem(storageDataId)
      return !storageData ? null : storageData
    }

    const _cookie_setItem = (cookieId, cookieData) => {
      const date = new Date();
      const exdays = 365;
      date.setTime(date.getTime() + (exdays*24*60*60*1000));
      const expires = "expires="+ date.toUTCString();
      document.cookie = cookieId + "=" + cookieData + ";" + expires + ";path=/";
    }

    const _cookie_getItem = cookieId => {
      const name = cookieId + "=";
      const decodedCookie = decodeURIComponent(document.cookie);
      const ca = decodedCookie.split(';');

      for(var i = 0; i <ca.length; i++) {
          var c = ca[i];
          while (c.charAt(0) == ' ') {
              c = c.substring(1);
          }
          if (c.indexOf(name) == 0) {
              return c.substring(name.length, c.length);
          }
      }

      return null;
    }

    const getItem = storageDataId => {
      return _hasLocalStorage ? _localStorage_getItem(storageDataId) : _cookie_getItem(storageDataId)
    }

    const setItem = (storageDataId, storageData) => {
      return _hasLocalStorage ? _localStorage_setItem(storageDataId, storageData) : _cookie_setItem(storageDataId, storageData)
    }

    window.storageApi = {
        getItem,
        setItem
    }

    console.log('window.storageApi')
    return window.storageApi
})()