Debian Codegraph @

closure-library/closure/goog/storage/storage.js

raw
1 // Copyright 2011 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Provides a convenient API for data persistence using a selected
17 * data storage mechanism.
18 *
19 */
20
21 goog.provide('goog.storage.Storage');
22
23 goog.require('goog.json');
24 goog.require('goog.storage.ErrorCode');
25
26
27
28 /**
29 * The base implementation for all storage APIs.
30 *
31 * @param {!goog.storage.mechanism.Mechanism} mechanism The underlying
32 * storage mechanism.
33 * @constructor
34 * @struct
35 */
36 goog.storage.Storage = function(mechanism) {
37 /**
38 * The mechanism used to persist key-value pairs.
39 *
40 * @protected {goog.storage.mechanism.Mechanism}
41 */
42 this.mechanism = mechanism;
43 };
44
45
46 /**
47 * Sets an item in the data storage.
48 *
49 * @param {string} key The key to set.
50 * @param {*} value The value to serialize to a string and save.
51 */
52 goog.storage.Storage.prototype.set = function(key, value) {
53 if (!goog.isDef(value)) {
54 this.mechanism.remove(key);
55 return;
56 }
57 this.mechanism.set(key, goog.json.serialize(value));
58 };
59
60
61 /**
62 * Gets an item from the data storage.
63 *
64 * @param {string} key The key to get.
65 * @return {*} Deserialized value or undefined if not found.
66 */
67 goog.storage.Storage.prototype.get = function(key) {
68 var json;
69 try {
70 json = this.mechanism.get(key);
71 } catch (e) {
72 // If, for any reason, the value returned by a mechanism's get method is not
73 // a string, an exception is thrown. In this case, we must fail gracefully
74 // instead of propagating the exception to clients. See b/8095488 for
75 // details.
76 return undefined;
77 }
78 if (goog.isNull(json)) {
79 return undefined;
80 }
81
82 try {
83 return JSON.parse(json);
84 } catch (e) {
85 throw goog.storage.ErrorCode.INVALID_VALUE;
86 }
87 };
88
89
90 /**
91 * Removes an item from the data storage.
92 *
93 * @param {string} key The key to remove.
94 */
95 goog.storage.Storage.prototype.remove = function(key) {
96 this.mechanism.remove(key);
97 };