1/* 2 * Copyright (c) 2021-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#include "napi_utils.h" 17#include "battery_log.h" 18 19namespace OHOS { 20namespace PowerMgr { 21namespace { 22constexpr uint32_t MAX_SIZE = 255; 23} 24napi_value NapiUtils::GetCallbackInfo(napi_env& env, napi_callback_info& info, size_t& argc, napi_value argv[]) 25{ 26 napi_value thisVar = nullptr; 27 void* data = nullptr; 28 if (napi_ok != napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)) { 29 BATTERY_HILOGW(FEATURE_BATT_INFO, "Failed to get the input parameter"); 30 } 31 return thisVar; 32} 33 34std::string NapiUtils::GetStringFromNapi(napi_env& env, napi_value& napiStr) 35{ 36 char str[MAX_SIZE] = {0}; 37 size_t strLen; 38 if (napi_ok != napi_get_value_string_utf8(env, napiStr, str, MAX_SIZE - 1, &strLen)) { 39 BATTERY_HILOGW(FEATURE_BATT_INFO, "napi_get_value_string_utf8 failed"); 40 return ""; 41 } 42 return std::string(str); 43} 44 45napi_ref NapiUtils::CreateReference(napi_env& env, napi_value& value) 46{ 47 napi_ref refVal = nullptr; 48 if (napi_ok != napi_create_reference(env, value, 1, &refVal)) { 49 BATTERY_HILOGW(FEATURE_BATT_INFO, "Failed to create a value reference"); 50 return refVal; 51 } 52 return refVal; 53} 54 55void NapiUtils::ReleaseReference(napi_env& env, napi_ref& ref) 56{ 57 if (ref != nullptr) { 58 napi_delete_reference(env, ref); 59 ref = nullptr; 60 } 61} 62 63bool NapiUtils::CheckValueType(napi_env& env, napi_value& value, napi_valuetype checkType) 64{ 65 napi_valuetype valueType = napi_undefined; 66 napi_typeof(env, value, &valueType); 67 if (valueType != checkType) { 68 BATTERY_HILOGW(FEATURE_BATT_INFO, "Parameter type error"); 69 return false; 70 } 71 return true; 72} 73} // namespace PowerMgr 74} // namespace OHOS 75