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 "log_print.h"
17 #include <memory>
18 #include "uv_queue.h"
19 #include "napi/native_common.h"
20 #include "napi/native_node_api.h"
21
22 namespace OHOS::PreferencesJsKit {
23 constexpr size_t MAX_CALLBACK_ARG_NUM = 6;
UvQueue(napi_env env)24 UvQueue::UvQueue(napi_env env)
25 : env_(env)
26 {
27 }
28
~UvQueue()29 UvQueue::~UvQueue()
30 {
31 LOG_DEBUG("no memory leak for queue-callback");
32 env_ = nullptr;
33 }
34
AsyncCall(NapiCallbackGetter getter,NapiArgsGenerator genArgs,bool sendable)35 void UvQueue::AsyncCall(NapiCallbackGetter getter, NapiArgsGenerator genArgs, bool sendable)
36 {
37 if (!getter) {
38 LOG_ERROR("callback is nullptr");
39 return;
40 }
41
42 auto env = GetEnv();
43 auto task = [env, getter, genArgs, sendable]() {
44 napi_handle_scope scope = nullptr;
45 napi_open_handle_scope(env, &scope);
46 if (scope == nullptr) {
47 return;
48 }
49 napi_value method = getter(env);
50 if (method == nullptr) {
51 LOG_WARN("the callback is invalid, maybe is cleared!");
52 napi_close_handle_scope(env, scope);
53 return;
54 }
55 int argc = 0;
56 napi_value argv[MAX_CALLBACK_ARG_NUM] = { nullptr };
57 if (genArgs) {
58 argc = MAX_CALLBACK_ARG_NUM;
59 genArgs(env, sendable, argc, argv);
60 }
61 napi_value global = nullptr;
62 napi_status status = napi_get_global(env, &global);
63 if (status != napi_ok) {
64 LOG_ERROR("get napi gloabl failed. status: %{public}d.", status);
65 napi_close_handle_scope(env, scope);
66 return;
67 }
68 napi_value result;
69 status = napi_call_function(env, global, method, argc, argv, &result);
70 if (status != napi_ok) {
71 LOG_ERROR("notify data change failed status: %{public}d.", status);
72 }
73 napi_close_handle_scope(env, scope);
74 };
75 if (napi_ok != napi_send_event(env_, task, napi_eprio_immediate)) {
76 LOG_ERROR("Failed to napi_send_event.");
77 }
78 }
79
GetEnv()80 napi_env UvQueue::GetEnv()
81 {
82 return env_;
83 }
84 } // namespace OHOS::DistributedKVStore
85