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