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_logger.h" 22 #include "js_utils.h" 23 #include "napi/native_api.h" 24 #include "napi/native_common.h" 25 #include "napi/native_node_api.h" 26 #include "napi_preferences_error.h" 27 28 namespace OHOS { 29 namespace PreferencesJsKit { 30 31 using InputAction = std::function<int(napi_env, size_t, napi_value *, napi_value)>; 32 using OutputAction = std::function<int(napi_env, napi_value &)>; 33 using ExecuteAction = std::function<int()>; 34 35 class BaseContext { 36 public: 37 void SetAction(napi_env env, napi_callback_info info, InputAction input, ExecuteAction exec, OutputAction output); 38 void SetError(std::shared_ptr<Error> error); 39 virtual ~BaseContext(); 40 41 napi_env env_ = nullptr; 42 void *boundObj = nullptr; 43 int execStatus = ERR; 44 std::shared_ptr<Error> error; 45 46 napi_ref self_ = nullptr; 47 napi_ref callback_ = nullptr; 48 napi_deferred defer_ = nullptr; 49 napi_async_work work_ = nullptr; 50 51 OutputAction output_ = nullptr; 52 ExecuteAction exec_ = nullptr; 53 std::shared_ptr<BaseContext> keep_; 54 }; 55 56 class AsyncCall final { 57 public: 58 static napi_value Call(napi_env env, std::shared_ptr<BaseContext> context); 59 60 private: 61 enum { ARG_ERROR, ARG_DATA, ARG_BUTT }; 62 static void OnExecute(napi_env env, void *data); 63 static void OnComplete(napi_env env, napi_status status, void *data); 64 static void SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr<Error> error); 65 }; 66 } // namespace PreferencesJsKit 67 } // namespace OHOS 68 #endif 69