1 /*
2  * Copyright (C) 2023 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 #ifndef NAPI_ASYNC_CALLBACK_H
17 #define NAPI_ASYNC_CALLBACK_H
18 
19 #include <map>
20 #include <memory>
21 #include <mutex>
22 #include "napi/native_api.h"
23 #include "napi_async_work.h"
24 
25 namespace OHOS {
26 namespace Bluetooth {
27 class NapiCallback;
28 class NapiPromise;
29 class NapiNativeObject;
30 
31 struct NapiAsyncCallback {
32     enum class Type {
33         CALLBACK = 1,
34         PROMISE,
35     };
36 
37     void CallFunction(int errCode, const std::shared_ptr<NapiNativeObject> &object);
38     napi_value GetRet(void);
39 
40     Type type;
41     napi_env env;
42     std::shared_ptr<NapiCallback> callback = nullptr;
43     std::shared_ptr<NapiPromise> promise = nullptr;
44 };
45 
46 class NapiCallback {
47 public:
48     // napi_value 'callback' shall be type of napi_founction, check it use NapiIsFunction().
49     NapiCallback(napi_env env, napi_value callback);
50     ~NapiCallback();
51 
52     void CallFunction(const std::shared_ptr<NapiNativeObject> &object);
53     void CallFunction(int errCode, const std::shared_ptr<NapiNativeObject> &object);
54     napi_env GetNapiEnv(void);
55     bool Equal(napi_value &callback) const;
56 private:
57     NapiCallback(const NapiCallback &) = delete;
58     NapiCallback &operator=(const NapiCallback &) = delete;
59     NapiCallback(NapiCallback &&) = delete;
60     NapiCallback &operator=(NapiCallback &&) noexcept = delete;
61 
62     napi_env env_;
63     napi_ref callbackRef_;
64 };
65 
66 class NapiPromise {
67 public:
68     explicit NapiPromise(napi_env env);
69     ~NapiPromise() = default;
70 
71     void ResolveOrReject(int errCode, const std::shared_ptr<NapiNativeObject> &object);
72     void Resolve(napi_value resolution);
73     void Reject(napi_value rejection);
74     napi_value GetPromise(void) const;
75 private:
76     napi_env env_;
77     napi_value promise_;
78     napi_deferred deferred_;
79     bool isResolvedOrRejected_ = false;
80 };
81 
82 class NapiHandleScope {
83 public:
84     explicit NapiHandleScope(napi_env env);
85     ~NapiHandleScope();
86 
87 private:
88     napi_env env_;
89     napi_handle_scope scope_;
90 };
91 
92 }  // namespace Bluetooth
93 }  // namespace OHOS
94 #endif  // NAPI_ASYNC_CALLBACK_H