!830 Add JSON logic code under the public basic library util.

Merge pull request !830 from 王景悟/master
This commit is contained in:
openharmony_ci 2024-02-23 07:02:27 +00:00 committed by Gitee
commit 028e0d33ad
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
5 changed files with 388 additions and 1 deletions

View File

@ -73,7 +73,8 @@
"//commonlibrary/ets_utils/js_sys_module/dfx:dfx_packages",
"//commonlibrary/ets_utils/js_sys_module/timer:timer_packages",
"//commonlibrary/ets_utils/js_util_module/util:util_packages",
"//commonlibrary/ets_utils/js_util_module/container:container_packages"
"//commonlibrary/ets_utils/js_util_module/container:container_packages",
"//commonlibrary/ets_utils/js_util_module/json:json_packages"
],
"inner_kits": [
{

View File

@ -0,0 +1,135 @@
# Copyright (c) 2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni")
import("//build/ohos.gni")
import("//commonlibrary/ets_utils/ets_utils_config.gni")
import("//foundation/arkui/ace_engine/ace_config.gni")
import("//foundation/arkui/ace_engine/build/ace_gen_obj.gni")
# compile .ts to .js.
action("build_ts_js") {
script = "$util_module/build_ts_js.py"
outFile_Path = target_out_dir + "/" + current_cpu
args = [
"--dst-file",
rebase_path(target_out_dir + "/json_js.js"),
"--module-path",
rebase_path("/commonlibrary/ets_utils/js_util_module/json"),
"--out-file",
rebase_path(outFile_Path + "/json_js.js"),
"--out-filePath",
rebase_path(outFile_Path),
"--relative-path",
rebase_path("//", root_build_dir),
]
outputs = [ target_out_dir + "/json_js.js" ]
}
# compile .js to .abc.
es2abc_gen_abc("gen_json_abc") {
extra_visibility = [ ":*" ]
src_js = rebase_path(target_out_dir + "/json_js.js")
dst_file = rebase_path(target_out_dir + "/json.abc")
in_puts = [ target_out_dir + "/json_js.js" ]
out_puts = [ target_out_dir + "/json.abc" ]
extra_args = [ "--module" ]
extra_dependencies = [ ":build_ts_js" ]
}
abc_output_path = get_label_info(":json_abc", "target_out_dir")
gen_obj("json_js") {
input = "$target_out_dir/json_js.js"
if (use_mac || use_mingw_win || use_ios || use_linux) {
json_js_obj_path = abc_output_path + "/json.c"
} else {
json_js_obj_path = abc_output_path + "/json.o"
}
output = json_js_obj_path
snapshot_dep = [ ":build_ts_js" ]
}
gen_obj("json_abc") {
input = "$target_out_dir/json.abc"
if (use_mac || use_mingw_win || use_ios || use_linux) {
json_js_obj_path = abc_output_path + "/json_abc.c"
} else {
json_js_obj_path = abc_output_path + "/json_abc.o"
}
output = json_js_obj_path
snapshot_dep = [ ":gen_json_abc" ]
}
json_sources = [ "native_module_json.cpp" ]
ohos_shared_library("json") {
deps = [ ":json_static" ]
subsystem_name = "commonlibrary"
part_name = "ets_utils"
relative_install_dir = "module/util"
}
ohos_source_set("json_static") {
include_dirs = [
"include",
"//third_party/icu/icu4c/source/common",
"//third_party/node/src",
]
configs = [
"$icu_root:icu_config",
"$napi_root:ace_napi_config",
]
sources = json_sources
deps = [
":gen_obj_src_json_abc",
":gen_obj_src_json_js",
]
if (is_arkui_x) {
include_dirs += [
"$plugins_root/hilog/include",
"$plugins_root/interfaces",
]
if (target_os == "android") {
defines = [ "ANDROID_PLATFORM" ]
} else if (target_os == "ios") {
defines = [ "IOS_PLATFORM" ]
}
deps += [
"$plugins_root/libs/icu:icu_${target_os}",
"$plugins_root/libs/napi:napi_${target_os}",
"$plugins_root/libs/securec:sec_${target_os}",
]
} else {
deps += [
"//third_party/bounds_checking_function:libsec_shared",
"//third_party/icu/icu4c:shared_icuuc",
]
external_deps = [
"hilog:libhilog",
"napi:ace_napi",
]
deps += [ "//third_party/icu/icu4c:shared_icuuc" ]
}
subsystem_name = "commonlibrary"
part_name = "ets_utils"
}
group("json_packages") {
public_deps = [ ":json" ]
}

View File

@ -0,0 +1,66 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "utils/log.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
extern const char _binary_json_js_js_start[];
extern const char _binary_json_js_js_end[];
extern const char _binary_json_abc_start[];
extern const char _binary_json_abc_end[];
static napi_value JsonInit(napi_env env, napi_value exports)
{
return exports;
}
extern "C"
__attribute__((visibility("default"))) void NAPI_util_json_GetJSCode(const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_json_js_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_json_js_js_end - _binary_json_js_js_start;
}
}
extern "C"
__attribute__((visibility("default"))) void NAPI_util_json_GetABCCode(const char** buf, int* buflen)
{
if (buf != nullptr) {
*buf = _binary_json_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_json_abc_end - _binary_json_abc_start;
}
}
static napi_module_with_js jsonModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = JsonInit,
.nm_modname = "json",
.nm_priv = ((void*)0),
.nm_get_abc_code = NAPI_util_json_GetABCCode,
.nm_get_js_code = NAPI_util_json_GetJSCode,
};
extern "C" __attribute__ ((constructor)) void JsonRegisterModule()
{
napi_module_with_js_register(&jsonModule);
}

View File

@ -0,0 +1,169 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const typeErrorCode = 401;
class BusinessError extends Error {
code: number;
constructor(msg: string) {
super(msg);
this.name = 'BusinessError';
this.code = typeErrorCode;
}
}
type TransformsFunc = (this: Object, key: string, value: Object) => Object | undefined | null;
type ReplacerType = (number | string)[] | null | TransformsFunc;
function parse(text: string, reviver?: TransformsFunc): Object | null {
if (typeof text !== 'string') {
let error = new BusinessError(`Parameter error.The type of ${text} must be string`);
throw error;
}
if (reviver) {
if (typeof reviver !== 'function') {
let error = new BusinessError(`Parameter error.${reviver} must be a method, but it is ${reviver}`);
throw error;
}
}
try {
return JSON.parse(text, reviver);
} catch (e) {
let error = new BusinessError(`e.message: `+ (e as Error).message + `e.name: ` + (e as Error).name);
throw error;
}
}
function stringfyFun(value: Object, replacer?: (this: Object, key: string, value: Object) => Object,
space?: string | number): string {
if (arguments.length === 1) {
return JSON.stringify(value);
} else {
return JSON.stringify(value, replacer, space);
}
}
function stringfyArr(value: Object, replacer?: (number | string)[] | null, space?: string | number): string {
if (arguments.length === 1) {
return JSON.stringify(value);
} else {
return JSON.stringify(value, replacer, space);
}
}
function isParameterType(self: unknown): boolean {
return (Array.isArray(self) && self.every((item) => typeof item === 'number' || typeof item === 'string')
|| self === null || typeof self === 'function');
}
function isSpaceType(self: unknown): boolean {
return (typeof self == 'string' || typeof self == 'number');
}
function isCirculateReference(value: Object, seenObjects: Set<Object> = new Set()): boolean {
if (value == null || !(value instanceof Object)) {
return false;
}
if (seenObjects.has(value)) {
return true;
}
seenObjects.add(value);
for (let key in value) {
if (isCirculateReference(value[key], seenObjects)) {
return true;
}
}
return false;
}
function stringify(value: Object, replacer?: ReplacerType, space?: string | number): string {
if (typeof (value as Object) === 'undefined' || !(value instanceof Object)) {
let error = new BusinessError(`Parameter error. The type of ${value} must be Object`);
throw error;
}
if (value === null) {
let error = new BusinessError(`Parameter error. The type of ${value} is null`);
throw error;
}
if (typeof value === 'bigint') {
let error = new BusinessError(`Parameter error. The type of ${value} is Bigint`);
throw error;
}
if (isCirculateReference(value)) {
let error = new BusinessError(`Parameter error. The object circular Reference`);
throw error;
}
if (replacer) {
if (!isParameterType(replacer)) {
let error = new BusinessError(`Parameter error. ${replacer} must be a method or array, but it is ${replacer}`);
throw error;
}
if (space) {
if (!isSpaceType(space)) {
let error = new BusinessError(`Parameter error. ${space} must be a string or number, but it is ${space}`);
throw error;
}
}
}
try {
if (arguments.length === 1) {
return stringfyArr(value);
} else {
if (typeof replacer === 'function') {
return stringfyFun(value, replacer, space);
} else {
return stringfyArr(value, replacer, space);
}
}
} catch (e) {
let error = new BusinessError((e as Error).message + `e.name: ` + (e as Error).name);
throw error;
}
}
function has(value: object, key: string): boolean {
if (typeof value !== 'object') {
let error = new BusinessError(`Parameter error. The type of ${value} must be object`);
throw error;
}
if (!(typeof key === 'string' && key.length)) {
let error = new BusinessError(`Parameter error. The type of ${key} must be string and not empty`);
throw error;
}
return value.hasOwnProperty(key);
}
function remove(value: object, key: string): void {
if (typeof value !== 'object') {
let error = new BusinessError(`Parameter error. The type of ${value} must be object`);
throw error;
}
if (!(typeof key === 'string' && key.length)) {
let error = new BusinessError(`Parameter error. The type of ${key} must be string and not empty`);
throw error;
}
if (value.hasOwnProperty(key)) {
delete value[key];
}
}
export default {
parse: parse,
stringify: stringify,
has: has,
remove: remove,
};

View File

@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2017",
"module": "es6",
"rootDir": "./src",
//"outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "./out", /* Specify an output folder for all emitted files. */
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"noImplicitThis": false,
"suppressImplicitAnyIndexErrors": true,
"strictNullChecks": false,
}
}