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 #ifndef PRE_JS_NAPI_ASYNC_CALL_H 16 #define PRE_JS_NAPI_ASYNC_CALL_H 17 18 #include <functional> 19 #include <memory> 20 21 #include "js_common_utils.h" 22 #include "napi/native_api.h" 23 #include "napi/native_common.h" 24 #include "napi/native_node_api.h" 25 #include "napi_preferences_error.h" 26 27 namespace OHOS { 28 namespace PreferencesJsKit { 29 30 using InputAction = std::function<void(napi_env, size_t, napi_value *, napi_value)>; 31 using OutputAction = std::function<void(napi_env, napi_value &)>; 32 using ExecuteAction = std::function<int()>; 33 extern bool g_async; 34 extern bool g_sync; 35 #define ASYNC &g_async 36 #define SYNC &g_sync 37 38 class BaseContext { 39 public: 40 void SetAction(napi_env env, napi_callback_info info, InputAction input, ExecuteAction exec, OutputAction output); 41 void SetError(std::shared_ptr<JSError> error); 42 virtual ~BaseContext(); 43 44 napi_env env_ = nullptr; 45 bool isAsync_ = true; 46 bool sendable_ = false; 47 void *boundObj = nullptr; 48 int execCode_ = ERR; 49 std::shared_ptr<JSError> error; 50 51 napi_ref self_ = nullptr; 52 napi_ref callback_ = nullptr; 53 napi_deferred defer_ = nullptr; 54 napi_async_work work_ = nullptr; 55 56 OutputAction output_ = nullptr; 57 ExecuteAction exec_ = nullptr; 58 napi_value result_ = nullptr; 59 std::shared_ptr<BaseContext> keep_; 60 }; 61 62 class AsyncCall final { 63 public: 64 static napi_value Call(napi_env env, std::shared_ptr<BaseContext> context, const std::string &name); 65 66 private: 67 enum { ARG_ERROR, ARG_DATA, ARG_BUTT }; 68 static void OnExecute(napi_env env, void *data); 69 static void OnComplete(napi_env env, void *data); 70 static void OnReturn(napi_env env, napi_status status, void *data); 71 static void OnComplete(napi_env env, napi_status status, void *data); 72 static void SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr<JSError> error); 73 static napi_value Async(napi_env env, std::shared_ptr<BaseContext> context, const std::string &name); 74 static napi_value Sync(napi_env env, std::shared_ptr<BaseContext> context); 75 }; 76 } // namespace PreferencesJsKit 77 } // namespace OHOS 78 #endif 79