JSFiddle - React, Tailwind, and code Playground

by scriptwerx

JavaScript

/**
 * Persistent Data using localStorage with expiry
 *
 * @description
 * Service to allow the storage of data within the browser localStorage
 * Local storage is also cached to improve performance of retrieving values.
 * Optional data expiry date is supported.
 * This is not designed to store large amounts of data.
 *
 */
(function() {

  'use strict';

  return angular.module('Scriptwerx.core', [])

  .service('storage', ['$window', function($window) {

      var prefix = 'swx_',
          webStorage = $window.localStorage,
          oneDay = 24 * 60 * 60 * 1000,
          cache = {};

      /**
       * Add data to storage
       * @param {String} key
       * @param {*} value
       * [@param {Number} expires] (expiry in days)
       */
      this.add = function(key, value) {

        var dataToStore = { data: value };

        if (arguments.length > 2 && angular.isNumber(arguments[2])) {
          dataToStore.expires = new Date().getTime() + (arguments[2] * oneDay);
        }

        // Save to local storage and session cache
        webStorage.setItem(prefix + key, JSON.stringify(dataToStore));
        cache[key] = dataToStore;

        return value;
      };

      /**
       * Get data from storage
       * @param {String} key
       * @returns {*}
       */
      this.get = function(key) {

        var item;

        // Return value from session cache if possible.
        if (key in cache) {
          item = cache[key];
        }
        else {
          // Get value from local storage
          item = webStorage.getItem(prefix + key);

          // If exists add to cache now
          if (item) {
            item = JSON.parse(item);
            cache[key] = item;
          }
          else {
            // Undefined value
            return void 0;
          }
        }

        // Check if stored item has expired
        if (item.expires && item.expires < new Date().getTime()) {
          this.remove(key);
          return void 0;
        }

      ...