1 /*
2 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development 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 "javascriptapi.h"
17
18 static const char *TAG = "[javascriptapi_property]";
19
testNapiSetNamedProperty(napi_env env,napi_callback_info info)20 napi_value testNapiSetNamedProperty(napi_env env, napi_callback_info info)
21 {
22 // pages/javascript/jsproperties/napisetnamedproperty
23 size_t argc = PARAM3;
24 napi_value argv[PARAM3];
25 napi_status status;
26 napi_value obj;
27 napi_value propName;
28 napi_value propValue;
29 const napi_extended_error_info *extended_error_info;
30 status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL); // 解析传入的参数
31 if (status != napi_ok) {
32 getErrMsg(status, env, extended_error_info, "get cb info", TAG);
33 return NULL;
34 }
35 if (argc < PARAM3) { // 检查参数数量
36 napi_throw_error(env, NULL, "Expected 2 arguments");
37 return NULL;
38 }
39 obj = argv[PARAM0];
40 propName = argv[PARAM1];
41 propValue = argv[PARAM2];
42 // 判断参数有效性
43 bool resValid = validateObjectProperty(env, obj, propName, TAG);
44 if (resValid == false) {
45 return NULL;
46 }
47 // 将第二个参数从napi_value转换为C字符串
48 size_t str_size = 0;
49 status = napi_get_value_string_utf8(env, propName, NULL, 0, &str_size);
50 if (status != napi_ok) {
51 getErrMsg(status, env, extended_error_info, "get value string", TAG);
52 return NULL;
53 }
54 char *propertyName = new char[str_size + 1];
55 status = napi_get_value_string_utf8(env, propName, propertyName, str_size + 1, &str_size);
56 if (status != napi_ok) {
57 getErrMsg(status, env, extended_error_info, "get value string", TAG);
58 delete[] propertyName;
59 return NULL;
60 }
61 // 设置对象的属性
62 status = napi_set_named_property(env, obj, propertyName, propValue);
63 if (status != napi_ok) {
64 getErrMsg(status, env, extended_error_info, "set named property", TAG);
65 delete[] propertyName;
66 return NULL;
67 }
68 delete[] propertyName;
69 return obj; // 返回新设置对象
70 }
71