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 #include "frameworks/bridge/declarative_frontend/jsview/js_local_storage.h"
16
17 #include "frameworks/bridge/declarative_frontend/engine/bindings.h"
18 #include "frameworks/core/common/container.h"
19
20 namespace OHOS::Ace::Framework {
21
22 thread_local std::unordered_map<int32_t, JSRef<JSObject>> JSLocalStorage::storages_;
23
JSLocalStorage()24 JSLocalStorage::JSLocalStorage()
25 {
26 LOGD("JSLocalStorage ctor");
27 }
28
JSBind(BindingTarget globalObj)29 void JSLocalStorage::JSBind(BindingTarget globalObj)
30 {
31 JSClass<JSLocalStorage>::Declare("NativeLocalStorage");
32 JSClass<JSLocalStorage>::StaticMethod("GetShared", JSLocalStorage::GetShared);
33 JSClass<JSLocalStorage>::Bind<>(globalObj);
34 }
35
AddStorage(int32_t key,const JSRef<JSObject> & value)36 void JSLocalStorage::AddStorage(int32_t key, const JSRef<JSObject>& value)
37 {
38 if (storages_.find(key) != storages_.end()) {
39 LOGW("A local storage already exists for key %d", key);
40 return;
41 }
42
43 storages_.emplace(key, value);
44 }
45
RemoveStorage(int32_t key)46 void JSLocalStorage::RemoveStorage(int32_t key)
47 {
48 auto it = storages_.find(key);
49 if (it != storages_.end()) {
50 storages_.erase(it);
51 } else {
52 LOGW("A local storage with key %{public}d does not exist!", key);
53 }
54 }
55
GetShared(const JSCallbackInfo & info)56 void JSLocalStorage::GetShared(const JSCallbackInfo& info)
57 {
58 int32_t currentInstance = Container::CurrentId();
59 LOGD("Current ID is %{public}d", currentInstance);
60 auto it = storages_.find(currentInstance);
61 if (it == storages_.end()) {
62 LOGW("LocalStorage with ID %{public}d not found!", currentInstance);
63 return;
64 }
65 LOGI("JSLocalStorage::GetShared find ID:%{public}d", currentInstance);
66 info.SetReturnValue(it->second);
67 }
68
69 } // namespace OHOS::Ace::Framework