9bf3d94ceda1d2a3fb7b522fa0328069626addc0
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Resources / Private / TypeScript / Storage / Client.ts
1 /*
2 * This file is part of the TYPO3 CMS project.
3 *
4 * It is free software; you can redistribute it and/or modify it under
5 * the terms of the GNU General Public License, either version 2
6 * of the License, or any later version.
7 *
8 * For the full copyright and license information, please read the
9 * LICENSE.txt file that was distributed with this source code.
10 *
11 * The TYPO3 project - inspiring people to share!
12 */
13
14 /**
15 * Module: TYPO3/CMS/Backend/Storage/Client
16 * Wrapper for localStorage
17 * @exports TYPO3/CMS/Backend/Storage/Client
18 */
19 class Client {
20 private keyPrefix: string = 't3-';
21
22 /**
23 * Simple localStorage wrapper, to get value from localStorage
24 * @param {string} key
25 * @returns {string}
26 */
27 public get = (key: string): string => {
28 return localStorage.getItem(this.keyPrefix + key);
29 }
30
31 /**
32 * Simple localStorage wrapper, to set value from localStorage
33 *
34 * @param {string} key
35 * @param {string} value
36 * @returns {string}
37 */
38 public set = (key: string, value: string): void => {
39 localStorage.setItem(this.keyPrefix + key, value);
40 }
41
42 /**
43 * Simple localStorage wrapper, to unset value from localStorage
44 *
45 * @param {string} key
46 */
47 public unset = (key: string): void => {
48 localStorage.removeItem(this.keyPrefix + key);
49 }
50
51 /**
52 * Removes values from localStorage by a specific prefix of the key
53 *
54 * @param {string} prefix
55 */
56 public unsetByPrefix = (prefix: string): void => {
57 prefix = this.keyPrefix + prefix;
58
59 const keysToDelete: Array<string> = [];
60 for (let i = 0; i < localStorage.length; ++i) {
61 if (localStorage.key(i).substring(0, prefix.length) === prefix) {
62 // Remove the global key prefix, as it gets prepended in unset again
63 const key = localStorage.key(i).substr(this.keyPrefix.length);
64
65 // We can't delete the key here as this interferes with the size of the localStorage
66 keysToDelete.push(key);
67 }
68 }
69
70 for (let key of keysToDelete) {
71 this.unset(key);
72 }
73 }
74
75 /**
76 * Simple localStorage wrapper, to clear localStorage
77 */
78 public clear = (): void => {
79 localStorage.clear();
80 }
81
82 /**
83 * Checks if a key was set before, useful to not do all the undefined checks all the time
84 *
85 * @param {string} key
86 * @returns {boolean}
87 */
88 public isset = (key: string): boolean => {
89 const value = this.get(key);
90 return (typeof value !== 'undefined' && value !== null);
91 }
92 }
93
94 export = new Client();