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.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 NapiExecute = std::function<void(void)>; 33 using NapiComplete = 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 NapiExecute execute = nullptr; 54 NapiComplete complete = nullptr; 55 56 static constexpr size_t ARGC_MAX = 3; 57 58 friend class NapiWork; 59 }; 60 61 class NapiWork { 62 public: 63 static napi_value AsyncEnqueue(napi_env env, ContextBase *ctxt, const std::string &name, 64 NapiExecute execute = NapiExecute(), NapiComplete complete = NapiComplete()); 65 static napi_value SyncEnqueue(napi_env env, ContextBase *ctxt, const std::string &name, 66 NapiExecute execute = NapiExecute(), NapiComplete complete = NapiComplete()); 67 68 private: 69 enum { 70 /* AsyncCallback / Promise output result index */ 71 RESULT_ERROR = 0, 72 RESULT_DATA = 1, 73 RESULT_ALL = 2 74 }; 75 static void GenerateOutput(ContextBase *ctxt); 76 static napi_value GenerateOutputSync(napi_env env, ContextBase *ctxt); 77 }; 78 } // namespace Time 79 } // namespace MiscServices 80 } // namespace OHOS 81 82 #endif // NAPI_ASYNC_WORK_H