1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
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 #include "storage_impl.h"
17 
18 namespace OHOS::Ace {
GetPreference(const std::string& fileName)19 std::shared_ptr<NativePreferences::Preferences> StorageImpl::GetPreference(const std::string& fileName)
20 {
21     auto it = preferences_.find(fileName);
22     if (it != preferences_.end()) {
23         return it->second;
24     }
25     auto pref = NativePreferences::PreferencesHelper::GetPreferences(fileName, errCode_);
26     preferences_.insert(std::make_pair(fileName, pref));
27     return pref;
28 }
29 
SetString(const std::string& key, const std::string& value)30 void StorageImpl::SetString(const std::string& key, const std::string& value)
31 {
32     std::shared_ptr<NativePreferences::Preferences> pref = GetPreference(fileName_);
33     CHECK_NULL_VOID(pref);
34     TAG_LOGD(AceLogTag::ACE_STATE_MGMT, "Set preference with key %{public}s, value %{public}s",
35         key.c_str(), value.c_str());
36     pref->PutString(key, value);
37     pref->Flush();
38 }
39 
GetString(const std::string& key)40 std::string StorageImpl::GetString(const std::string& key)
41 {
42     std::shared_ptr<NativePreferences::Preferences> pref = GetPreference(fileName_);
43     CHECK_NULL_RETURN(pref, "");
44     LOGD("Get preference with key %{public}s", key.c_str());
45     return pref->GetString(key, "");
46 }
47 
Clear()48 void StorageImpl::Clear()
49 {
50     std::shared_ptr<NativePreferences::Preferences> pref = GetPreference(fileName_);
51     CHECK_NULL_VOID(pref);
52     pref->Clear();
53     LOGD("StorageImpl: Clear preferences");
54     NativePreferences::PreferencesHelper::DeletePreferences(fileName_);
55     preferences_.erase(fileName_);
56 }
57 
Delete(const std::string& key)58 void StorageImpl::Delete(const std::string& key)
59 {
60     std::shared_ptr<NativePreferences::Preferences> pref = GetPreference(fileName_);
61     CHECK_NULL_VOID(pref);
62     LOGD("StorageImpl: Delete preference with key %{public}s", key.c_str());
63     pref->Delete(key);
64     pref->FlushSync();
65 }
66 
GetStorage() const67 RefPtr<Storage> StorageProxyImpl::GetStorage() const
68 {
69     return AceType::MakeRefPtr<StorageImpl>();
70 }
71 } // namespace OHOS::Ace