1 /*
2 * Copyright (c) 2021 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 "n_class.h"
17
18 namespace OHOS {
19 namespace HiviewDFX {
20 using namespace std;
GetInstance()21 NClass &NClass::GetInstance()
22 {
23 static NClass nClass;
24 return nClass;
25 }
26
DefineClass(napi_env env, string className, napi_callback constructor, vector<napi_property_descriptor> &&properties)27 tuple<bool, napi_value> NClass::DefineClass(napi_env env, string className, napi_callback constructor,
28 vector<napi_property_descriptor> &&properties)
29 {
30 napi_value classVal = nullptr;
31 napi_status stat = napi_define_class(env, className.c_str(), className.length(), constructor,
32 nullptr, properties.size(), properties.data(), &classVal);
33 return { stat == napi_ok, classVal };
34 }
35
InstantiateClass(napi_env env, string className, vector<napi_value> args)36 napi_value NClass::InstantiateClass(napi_env env, string className, vector<napi_value> args)
37 {
38 NClass &nClass = NClass::GetInstance();
39 #if not (defined(__WINDOWS__) || defined(__MAC__) || defined(__LINUX__))
40 lock_guard(nClass.exClassMapLock);
41 #endif
42 auto it = nClass.exClassMap.find(className);
43 if (it == nClass.exClassMap.end()) {
44 return nullptr;
45 }
46 napi_value cons = nullptr;
47 napi_status status = napi_get_reference_value(env, it->second, &cons);
48 if (status != napi_ok) {
49 return nullptr;
50 }
51 napi_value instance = nullptr;
52 status = napi_new_instance(env, cons, args.size(), args.data(), &instance);
53 if (status != napi_ok) {
54 return nullptr;
55 }
56 return instance;
57 }
58 } // namespace HiviewDFX
59 } // namespace OHOS