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 INTELL_VOICE_NAPI_QUEUE_H
17 #define INTELL_VOICE_NAPI_QUEUE_H
18 
19 #include <functional>
20 #include "napi/native_api.h"
21 #include "napi/native_node_api.h"
22 
23 namespace OHOS {
24 namespace IntellVoiceNapi {
25 constexpr size_t ARGC_MAX = 4;
26 
27 class AsyncContext;
28 using CbInfoParser = std::function<bool(size_t argc, napi_value *argv)>;
29 using AsyncExecute = napi_async_execute_callback;
30 using AsyncComplete = std::function<void(napi_env, AsyncContext *, napi_value &)>;
31 
32 class AsyncContext {
33 public:
34     explicit AsyncContext(napi_env env);
35     ~AsyncContext();
36     bool GetCbInfo(napi_env env, napi_callback_info info, size_t callBackIndex, CbInfoParser parser);
37 
38     napi_env env_ = nullptr;
39     void *instanceNapi_ = nullptr;
40 
41     int32_t result_ = -1;
42     AsyncComplete complete_ = nullptr;
43 
44     napi_async_work work_ = nullptr;
45     napi_deferred deferred_ = nullptr;
46     napi_ref callbackRef_ = nullptr;
47     std::shared_ptr<AsyncContext> contextSp_ = nullptr;
48 };
49 
50 class NapiAsync {
51 public:
52     static napi_value AsyncWork(napi_env env, std::shared_ptr<AsyncContext> context, const std::string &name,
53         AsyncExecute execute);
54     static napi_value AsyncWork(napi_env env, std::shared_ptr<AsyncContext> context, const std::string &name,
55         AsyncExecute execute, napi_async_complete_callback complete);
56     static void CommonCallbackRoutine(napi_env env, AsyncContext *context, const napi_value &data);
57 
58 private:
59     static void AsyncCompleteCallback(napi_env env, napi_status status, void *data);
60     static void HandlePromise(napi_env env, AsyncContext *context, const napi_value &data);
61     static void HandleAsyncCallback(napi_env env, AsyncContext *context, const napi_value &data);
62 };
63 }  // namespace IntellVoiceNapi
64 }  // namespace OHOS
65 
66 #endif
67