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