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