1 /* 2 * Copyright (c) 2024 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 HIDEBUG_ASYNCTASK_H_ 17 #define HIDEBUG_ASYNCTASK_H_ 18 19 #include "napi/native_api.h" 20 21 #include <functional> 22 #include <string> 23 #include <type_traits> 24 25 namespace OHOS { 26 namespace HiviewDFX { 27 28 napi_value CreateErrorMessage(napi_env env, const std::string& msg); 29 30 napi_value CreateErrorMessage(napi_env env, const std::string& errCode, const std::string& msg); 31 32 napi_value CreateUndefined(napi_env env); 33 34 bool MatchValueType(napi_env env, napi_value value, napi_valuetype targetType); 35 36 bool GetNapiBoolValue(napi_env env, napi_value value, bool& ret); 37 38 bool GetNapiStringValue(napi_env env, napi_value value, std::string& ret, size_t maxSize); 39 40 bool GetTheOnlyStringParam(napi_env env, napi_callback_info info, std::string &fileName); 41 42 std::string GetFileNameParam(napi_env env, napi_callback_info info); 43 class AsyncTask { 44 public: AsyncTask(const std::string & resourceName)45 explicit AsyncTask(const std::string& resourceName): resourceName_(resourceName) {}; 46 virtual ~AsyncTask() = default; 47 48 template<typename T, typename = typename std::enable_if<std::is_base_of<AsyncTask, T>::value>::type> 49 static napi_value GetPromise(napi_env env, std::function<void(T*)> setReqParam = [](T*) {}) 50 { 51 napi_value promise = nullptr; 52 T* asyncTask = new (std::nothrow) T(); 53 if (asyncTask == nullptr) { 54 return nullptr; 55 } 56 setReqParam(asyncTask); 57 if (!asyncTask->CreatePromise(env, promise)) { 58 delete asyncTask; 59 return nullptr; 60 } 61 return promise; 62 }; 63 64 protected: 65 napi_async_work worker_ = nullptr; 66 napi_deferred deferred_ = nullptr; 67 std::string resourceName_; 68 virtual void Work(napi_env env) = 0; 69 virtual void Done(napi_env env, napi_status status) = 0; 70 71 private: 72 bool CreatePromise(napi_env env, napi_value& promise); 73 static void ExecuteCallBack(napi_env env, void* data); 74 static void CompletedCallBack(napi_env env, napi_status status, void* data); 75 }; 76 } 77 } 78 79 #endif //HIDEBUG_ASYNCTASK_H_ 80