1 /*
2 * Copyright (c) 2024 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 #include "json_manager.h"
16 #include "tools/log.h"
17
18 namespace Commonlibrary::Concurrent {
19 const std::string JSON_NAME = "JSON";
20 const std::string ASON_NAME = "ASON";
21 const std::string PARSE_NAME = "parse";
22 const std::string PARSE_SENDABLE_NAME = "parseSendable";
23 const std::string STRINGIFY_SENDABLE_NAME = "stringifySendable";
24 const std::string STRINGIFY_NAME = "stringify";
25
GeJsonFunction(napi_env env,napi_value global,const std::string & jsonName,napi_value & jsonFunction)26 bool JsonManager::GeJsonFunction(napi_env env, napi_value global, const std::string &jsonName, napi_value &jsonFunction)
27 {
28 napi_value jsonKey;
29 NAPI_CALL_BASE(env, napi_create_string_utf8(env, jsonName.c_str(), jsonName.size(), &jsonKey), false);
30 NAPI_CALL_BASE(env, napi_get_property(env, global, jsonKey, &jsonFunction), false);
31 bool validFunction = false;
32 NAPI_CALL_BASE(env, napi_is_callable(env, jsonFunction, &validFunction), false);
33 if (!validFunction) {
34 HILOG_ERROR("Get ASON function for %{public}s failed.", jsonName.c_str());
35 }
36 return validFunction;
37 }
38
Init(napi_env env,napi_value exports)39 napi_value JsonManager::Init(napi_env env, napi_value exports)
40 {
41 napi_value global;
42 napi_value ason;
43 napi_value parseSendable;
44 napi_value stringify;
45 napi_value jsonKey;
46 napi_value jsonValue;
47 NAPI_CALL(env, napi_create_object(env, &ason));
48 NAPI_CALL(env, napi_get_global(env, &global));
49 NAPI_CALL(env, napi_create_string_utf8(env, JSON_NAME.c_str(), JSON_NAME.size(), &jsonKey));
50 NAPI_CALL(env, napi_get_property(env, global, jsonKey, &jsonValue));
51 if (!(GeJsonFunction(env, jsonValue, PARSE_SENDABLE_NAME, parseSendable) &&
52 GeJsonFunction(env, jsonValue, STRINGIFY_SENDABLE_NAME, stringify))) {
53 return exports;
54 }
55 napi_property_descriptor desc[] = {
56 DECLARE_NAPI_PROPERTY(PARSE_NAME.c_str(), parseSendable),
57 DECLARE_NAPI_PROPERTY(STRINGIFY_NAME.c_str(), stringify),
58 };
59 NAPI_CALL(env, napi_define_properties(env, ason, sizeof(desc) / sizeof(desc[0]), desc));
60 NAPI_CALL(env, napi_set_named_property(env, exports, ASON_NAME.c_str(), ason));
61 return exports;
62 }
63 }
64
65