[fabric/core] Add JSON utility functions for parsing and stringifying with core types

This commit is contained in:
Pablo Baleztena 2024-10-23 23:45:08 -03:00
parent de49970c0c
commit 36b5286a09
7 changed files with 50 additions and 17 deletions

View File

@ -3,5 +3,8 @@
"version": "0.1.0",
"exports": {
".": "./index.ts"
},
"imports": {
"decimal": "jsr:@quentinadam/decimal@^0.1.6"
}
}

View File

@ -1,3 +1,4 @@
import Decimal from "decimal";
export * from "./array/index.ts";
export * from "./error/index.ts";
export * from "./record/index.ts";
@ -7,3 +8,4 @@ export * from "./time/index.ts";
export * from "./types/index.ts";
export * from "./utils/index.ts";
export * from "./variant/index.ts";
export { Decimal };

View File

@ -1 +1,2 @@
export * from "./ensure.ts";
export * from "./json-utils.ts";

View File

@ -0,0 +1,43 @@
import { isRecord, PosixDate } from "@fabric/core";
import Decimal from "decimal";
export namespace JSONUtils {
export function reviver(key: string, value: unknown) {
if (isRecord(value)) {
if (value._type === "bigint" && typeof value.value == "string") {
return BigInt(value.value);
}
if (value._type === "decimal" && typeof value.value == "string") {
return Decimal.from(value.value);
}
if (PosixDate.isPosixDateJSON(value)) {
return PosixDate.fromJson(value);
}
}
return value;
}
export function parse<T>(json: string): T {
return JSON.parse(json, reviver);
}
export function stringify<T>(value: T): string {
return JSON.stringify(value, (key, value) => {
if (typeof value === "bigint") {
return {
_type: "bigint",
value: value.toString(),
};
}
if (value instanceof Decimal) {
return {
_type: "decimal",
value: value.toString(),
};
}
return value;
});
}
}

View File

@ -6,7 +6,6 @@
},
"imports": {
"@fabric/core": "jsr:@fabric/core",
"@fabric/validations": "jsr:@fabric/validations",
"decimal": "jsr:@quentinadam/decimal@^0.1.6"
"@fabric/validations": "jsr:@fabric/validations"
}
}

View File

@ -1,2 +1 @@
export * from "./json-utils.ts";
export * from "./sort-by-dependencies.ts";

View File

@ -1,14 +0,0 @@
import { PosixDate } from "@fabric/core";
export namespace JSONUtils {
export function reviver(key: string, value: unknown) {
if (PosixDate.isPosixDateJSON(value)) {
return PosixDate.fromJson(value);
}
return value;
}
export function parse<T>(json: string): T {
return JSON.parse(json, reviver);
}
}