1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sw=2 sts=2 et cindent: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef MOZILLA_KEY_VALUE_STORAGE_H
8 #define MOZILLA_KEY_VALUE_STORAGE_H
9 
10 #include "mozilla/MozPromise.h"
11 #include "nsIKeyValue.h"
12 
13 namespace mozilla {
14 
15 /* A wrapper class around kv store service, which allows storing a pair of key
16  * value permanently. The class must be used from the parent process, where
17  * there is no sandbox because it requires access to the directory that the
18  * database is located. */
19 class KeyValueStorage final {
20  public:
21   NS_INLINE_DECL_THREADSAFE_REFCOUNTING(KeyValueStorage)
22 
23   /* Store permanently the value in the Key. */
24   RefPtr<GenericPromise> Put(const nsACString& aName, const nsACString& aKey,
25                              int32_t aValue);
26   /* Get the value stored in the aKey. If the aKey does not exist the promise is
27    * resolved with the value -1. */
28   typedef MozPromise<int32_t, nsresult, true> GetPromise;
29   RefPtr<GetPromise> Get(const nsACString& aName, const nsACString& aKey);
30 
31   /* Clear all the key/value pairs from the aName database. */
32   RefPtr<GenericPromise> Clear(const nsACString& aName);
33 
34  private:
35   /* Create, if doesn't exist, and initialize the database with a given name. */
36   RefPtr<GenericPromise> Init();
37   RefPtr<GenericPromise> Put(const nsACString& aKey, int32_t aValue);
38   RefPtr<GetPromise> Get(const nsACString& aKey);
39   RefPtr<GenericPromise> Clear();
40   ~KeyValueStorage() = default;
41 
42   RefPtr<nsIKeyValueDatabase> mDatabase;
43   nsCString mDatabaseName;
44 };
45 
46 }  // namespace mozilla
47 
48 #endif  // MOZILLA_KEY_VALUE_STORAGE_H
49