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 #include "function.h"
17
18 #include "env.h"
19 #include "object.h"
20
21 namespace NapiApi {
22
Function(napi_env env,napi_value v)23 Function::Function(napi_env env, napi_value v) : env_(env), func_(v)
24 {
25 if (env_) {
26 napi_typeof(env_, v, &jstype);
27 }
28 if (jstype != napi_function) {
29 // value was not a function
30 env_ = {};
31 func_ = nullptr;
32 }
33 }
34
operator napi_value() const35 Function::operator napi_value() const
36 {
37 return func_;
38 }
39
Env() const40 NapiApi::Env Function::Env() const
41 {
42 return env_;
43 }
44
GetEnv() const45 napi_env Function::GetEnv() const
46 {
47 return env_;
48 }
49
Invoke(const NapiApi::Object & thisJS,size_t argc,napi_value * argv) const50 napi_value Function::Invoke(const NapiApi::Object& thisJS, size_t argc, napi_value* argv) const
51 {
52 if (!env_) {
53 return nullptr;
54 }
55 auto res = env_.GetUndefined();
56 if (func_) {
57 napi_call_function(env_, thisJS.ToNapiValue(), func_, argc, argv, &res);
58 }
59 return res;
60 }
61
IsDefined()62 bool Function::IsDefined()
63 {
64 return (napi_undefined != jstype);
65 }
66
IsNull()67 bool Function::IsNull()
68 {
69 return (napi_null == jstype);
70 }
71
72 } // namespace NapiApi
73