1 /* 2 * Copyright (C) 2025 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 NAPI_API_VALUE_H 17 #define NAPI_API_VALUE_H 18 19 #ifdef __OHOS_PLATFORM__ 20 #include "napi/native_api.h" 21 #else 22 #include <node_api.h> 23 #endif 24 25 #include <base/containers/string.h> 26 #include <base/containers/type_traits.h> 27 28 #include "utils.h" 29 30 namespace NapiApi { 31 32 template<typename type> 33 class Value { 34 napi_env env_ { nullptr }; 35 napi_value value_ { nullptr }; 36 napi_valuetype jstype = napi_undefined; 37 38 public: 39 using Type = type; 40 Value() = default; Value(napi_env env,Type v)41 Value(napi_env env, Type v) 42 { 43 Init(env, v); 44 } 45 46 void Init(napi_env env, Type v); 47 Value(napi_env env,napi_value v)48 Value(napi_env env, napi_value v) : env_(env) 49 { 50 if ((env == nullptr) || (v == nullptr)) { 51 return; 52 } 53 // validate type 54 napi_status status = napi_invalid_arg; 55 status = napi_typeof(env_, v, &jstype); 56 if (status != napi_ok) { 57 // okay then failed. 58 return; 59 } 60 bool isArray = false; 61 napi_is_array(env_, v, &isArray); 62 63 if (NapiApi::ValidateType<type>(jstype, isArray)) { 64 value_ = v; 65 } else { 66 jstype = napi_undefined; 67 } 68 } 69 IsValid()70 bool IsValid() const 71 { 72 return (env_ && value_); 73 } 74 IsNull()75 bool IsNull() const 76 { 77 return (napi_null == jstype); 78 } 79 IsDefined()80 bool IsDefined() const 81 { 82 return !IsUndefined(); 83 } 84 IsUndefined()85 bool IsUndefined() const 86 { 87 return (napi_undefined == jstype); 88 } 89 IsUndefinedOrNull()90 bool IsUndefinedOrNull() const 91 { 92 if (!IsValid()) { 93 return true; 94 } 95 return ((napi_null == jstype) || (napi_undefined == jstype)); 96 } 97 IsDefinedAndNotNull()98 bool IsDefinedAndNotNull() const 99 { 100 return ((napi_null != jstype) && (napi_undefined != jstype)); 101 } 102 type()103 operator type() 104 { 105 return valueOrDefault(); 106 } 107 GetEnv()108 napi_env GetEnv() const 109 { 110 return env_; 111 } 112 ToNapiValue()113 napi_value ToNapiValue() const 114 { 115 return value_; 116 } 117 118 type valueOrDefault(const type defaultValue = {}); 119 }; 120 121 } // namespace NapiApi 122 123 #endif 124