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 DATASHARE_JSUTILS_H 17 #define DATASHARE_JSUTILS_H 18 19 #include <iostream> 20 #include <map> 21 #include <string> 22 #include <vector> 23 24 #include "napi/native_api.h" 25 #include "napi/native_common.h" 26 #include "napi/native_node_api.h" 27 28 #define NAPI_ASSERT_ERRCODE(env, assertion, error) \ 29 do { \ 30 if (!(assertion)) { \ 31 napi_throw_error((env), std::to_string((error)->GetCode()).c_str(), (error)->GetMessage().c_str()); \ 32 return; \ 33 } \ 34 } while (0) 35 36 namespace OHOS { 37 namespace DataShare { 38 class DataShareJSUtils final { 39 public: 40 static constexpr int32_t DEFAULT_BUF_SIZE = 1024; 41 static constexpr int32_t ASYNC_RST_SIZE = 2; 42 static constexpr int32_t SYNC_RESULT_ELEMNT_NUM = 2; 43 44 static std::string Convert2String(napi_env env, napi_value jsStr, size_t max = DEFAULT_BUF_SIZE); 45 static std::vector<std::string> Convert2StrVector(napi_env env, napi_value value, size_t strMax); 46 static std::vector<uint8_t> Convert2U8Vector(napi_env env, napi_value jsValue); 47 static std::string ConvertAny2String(napi_env env, const napi_value jsValue); 48 static std::string UnwrapStringFromJS(napi_env env, napi_value param, const std::string &defaultValue = ""); 49 50 static napi_value Convert2JSValue(napi_env env, const std::vector<std::string> &value); 51 static napi_value Convert2JSValue(napi_env env, const std::string &value); 52 static napi_value Convert2JSValue(napi_env env, const std::vector<uint8_t> &value); 53 static napi_value Convert2JSValue(napi_env env, int32_t value); 54 static napi_value Convert2JSValue(napi_env env, int64_t value); 55 static napi_value Convert2JSValue(napi_env env, double value); 56 static napi_value Convert2JSValue(napi_env env, bool value); 57 static napi_value Convert2JSValue(napi_env env, const std::map<std::string, int>& value); 58 static std::vector<uint8_t> ConvertU8Vector(napi_env env, napi_value jsValue); 59 static bool Equals(napi_env env, napi_value value, napi_ref copy); 60 }; 61 } // namespace DataShare 62 } // namespace OHOS 63 64 #endif // DATASHARE_JSUTILS_H