aboutsummaryrefslogtreecommitdiffstats
path: root/src/js/storage.js
blob: 27fdad9fa094523d83c3b9e6038f293863ef4eed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// ==========================================================================
// Plyr storage
// ==========================================================================

import is from './utils/is';
import { extend } from './utils/objects';

class Storage {
    constructor(player) {
        this.enabled = player.config.storage.enabled;
        this.key = player.config.storage.key;
    }

    // Check for actual support (see if we can use it)
    static get supported() {
        try {
            if (!('localStorage' in window)) {
                return false;
            }

            const test = '___test';

            // Try to use it (it might be disabled, e.g. user is in private mode)
            // see: https://github.com/sampotts/plyr/issues/131
            window.localStorage.setItem(test, test);
            window.localStorage.removeItem(test);

            return true;
        } catch (e) {
            return false;
        }
    }

    get(key) {
        if (!Storage.supported || !this.enabled) {
            return null;
        }

        const store = window.localStorage.getItem(this.key);

        if (is.empty(store)) {
            return null;
        }

        const json = JSON.parse(store);

        return is.string(key) && key.length ? json[key] : json;
    }

    set(object) {
        // Bail if we don't have localStorage support or it's disabled
        if (!Storage.supported || !this.enabled) {
            return;
        }

        // Can only store objectst
        if (!is.object(object)) {
            return;
        }

        // Get current storage
        let storage = this.get();

        // Default to empty object
        if (is.empty(storage)) {
            storage = {};
        }

        // Update the working copy of the values
        extend(storage, object);

        // Update storage
        window.localStorage.setItem(this.key, JSON.stringify(storage));
    }
}

export default Storage;