lib/amd/src/localstorage.js

  1. // This file is part of Moodle - http://moodle.org/
  2. //
  3. // Moodle is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // Moodle is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  15. /**
  16. * Simple API for set/get to localstorage, with cacherev expiration.
  17. *
  18. * @module core/localstorage
  19. * @class localstorage
  20. * @copyright 2015 Damyon Wiese <damyon@moodle.com>
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. * @since 2.9
  23. */
  24. define(['core/config', 'core/storagewrapper'], function(config, StorageWrapper) {
  25. // Private functions and variables.
  26. /** @var {Object} StorageWrapper - Wraps browsers localStorage object */
  27. var storage = new StorageWrapper(window.localStorage);
  28. return /** @alias module:core/localstorage */ {
  29. /**
  30. * Get a value from local storage. Remember - all values must be strings.
  31. *
  32. * @method get
  33. * @param {string} key The cache key to check.
  34. * @return {boolean|string} False if the value is not in the cache, or some other error - a string otherwise.
  35. */
  36. get: function(key) {
  37. return storage.get(key);
  38. },
  39. /**
  40. * Set a value to local storage. Remember - all values must be strings.
  41. *
  42. * @method set
  43. * @param {string} key The cache key to set.
  44. * @param {string} value The value to set.
  45. * @return {boolean} False if the value can't be saved in the cache, or some other error - true otherwise.
  46. */
  47. set: function(key, value) {
  48. return storage.set(key, value);
  49. },
  50. /**
  51. * Clean local storage
  52. *
  53. * @method clean
  54. */
  55. clean: function() {
  56. return storage.clean();
  57. }
  58. };
  59. });