• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef NAPI_ASYNC_WORK_H
17 #define NAPI_ASYNC_WORK_H
18 
19 #include <functional>
20 #include <memory>
21 #include <string>
22 
23 #include "napi/native_api.h"
24 #include "napi/native_common.h"
25 #include "napi/native_node_api.h"
26 #include "time_hilog_wreapper.h"
27 
28 namespace OHOS {
29 namespace MiscServices {
30 namespace Time {
31 using NapiCbInfoParser = std::function<void(size_t argc, napi_value *argv)>;
32 using NapiAsyncExecute = std::function<void(void)>;
33 using NapiAsyncComplete = std::function<void(napi_value &)>;
34 
35 struct ContextBase {
36     virtual ~ContextBase();
37     void GetCbInfo(napi_env env, napi_callback_info info, NapiCbInfoParser parse = NapiCbInfoParser(),
38         bool sync = false);
39 
40     napi_env env = nullptr;
41     napi_value output = nullptr;
42     napi_status status = napi_invalid_arg;
43     std::string errMessage = "";
44     int32_t errCode = 0;
45     napi_value self = nullptr;
46 
47 private:
48     napi_deferred deferred = nullptr;
49     napi_async_work work = nullptr;
50     napi_ref callbackRef = nullptr;
51     napi_ref selfRef = nullptr;
52 
53     NapiAsyncExecute execute = nullptr;
54     NapiAsyncComplete complete = nullptr;
55 
56     static constexpr size_t ARGC_MAX = 3;
57 
58     friend class NapiAsyncWork;
59 };
60 
61 class NapiAsyncWork {
62 public:
63     static napi_value Enqueue(napi_env env, ContextBase *ctxt, const std::string &name,
64         NapiAsyncExecute execute = NapiAsyncExecute(), NapiAsyncComplete complete = NapiAsyncComplete());
65 
66 private:
67     enum {
68         /* AsyncCallback / Promise output result index  */
69         RESULT_ERROR = 0,
70         RESULT_DATA = 1,
71         RESULT_ALL = 2
72     };
73     static void GenerateOutput(ContextBase *ctxt);
74 };
75 } // namespace Time
76 } // namespace MiscServices
77 } // namespace OHOS
78 
79 #endif // NAPI_ASYNC_WORK_H