Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat changes pack #72

Merged
merged 4 commits into from
Dec 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- added MapPlainParseHelper
- added JsonHelper methods: mapJsonSerializableMapToJson(), mapPrimitiveMapToJson(), mapJsonSerializableArrayToJson()

### Fixed

- JsonSchemaFactory.Object() add missing 'additionalProperties' option

## [0.16.4] - 2024-11-30

### Added
Expand Down Expand Up @@ -206,8 +215,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- many changes.

[unreleased] https://github.com/hexancore/common/compare/0.16.4...HEAD
[0.16.4] https://github.com/hexancore/common/compare/0.16.3...0.16.4
[unreleased] https://github.com/hexancore/common/compare/0.16.4...HEAD
[0.16.4] https://github.com/hexancore/common/compare/0.16.3...0.16.4
[0.16.3] https://github.com/hexancore/common/compare/0.16.2...0.16.3
[0.16.2] https://github.com/hexancore/common/compare/0.16.1...0.16.2
[0.16.1] https://github.com/hexancore/common/compare/0.16.0...0.16.1
Expand Down
24 changes: 24 additions & 0 deletions src/Util/Json/JsonHelper.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { AppErrorCode, DefineErrorsUnion } from '../Error';
import { ERR, OK, R } from '../Result/Result';
import type { JsonObjectType } from "../types";
import type { JsonSerialize } from "./JsonSerialize";

export type JsonTraverserFn = (this: any, key: string, value: any) => any;

Expand All @@ -25,4 +27,26 @@ export class JsonHelper {
return ERR({ type: JsonErrors.stringify, code: AppErrorCode.BAD_REQUEST, error: e as any });
}
}

public static mapJsonSerializableArrayToJson<T extends JsonSerialize>(input: T[]): JsonObjectType<T>[] {
const out: JsonObjectType<T>[] = [];
input.forEach(v => {
out.push(v.toJSON());
});

return out;
}

public static mapJsonSerializableMapToJson<K, V extends JsonSerialize>(input: Map<K, V>): [K, JsonObjectType<V>][] {
const out: [K, JsonObjectType<V>][] = [];
input.forEach((v, k) => {
out.push([k, v.toJSON()]);
});

return out;
}

public static mapPrimitiveMapToJson<K, V>(input: Map<K, V>): [K, V][] {
return Array.from(input.entries());
}
}
6 changes: 3 additions & 3 deletions src/Util/Json/JsonSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export interface NumberJsonSchema extends JsonSchemaBase {
maximum?: number;
exclusiveMaximum?: number;

default?: number;
default?: number;
}

export interface BooleanJsonSchema extends JsonSchemaBase {
Expand All @@ -47,7 +47,7 @@ export interface ObjectJsonSchema extends JsonSchemaBase {
type: "object";
properties: Record<string, JsonSchema>;
required?: string[];
additionalProperties?: boolean
additionalProperties?: boolean;
}

export type JsonSchema =
Expand Down Expand Up @@ -85,7 +85,7 @@ export class JsonSchemaFactory {
};
}

public static Object(properties: Record<string, JsonSchema>, options: Pick<ObjectJsonSchema, "required"> = {}): ObjectJsonSchema {
public static Object(properties: Record<string, JsonSchema>, options: Pick<ObjectJsonSchema, "required" | "additionalProperties"> = {}): ObjectJsonSchema {
return {
type: "object",
properties,
Expand Down
109 changes: 109 additions & 0 deletions src/Util/Plain/MapPlainParseHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { type PlainParsableHObjectType } from "../Feature/HObjectTypeMeta";
import { ArrayPlainParseHelper } from "./ArrayPlainParseHelper";
import { InvalidArrayElementsPlainParseIssue, InvalidHObjectPlainParseIssue, InvalidMapEntriesPlainParseIssue, InvalidMapEntryPlainParseIssue, InvalidTypePlainParseIssue, OutOfRangePlainParseIssue, PlainParseIssue, TooBigPlainParseIssue, TooSmallPlainParseIssue } from "./PlainParseIssue";

Check warning on line 3 in src/Util/Plain/MapPlainParseHelper.ts

View workflow job for this annotation

GitHub Actions / check

'OutOfRangePlainParseIssue' is defined but never used

Check warning on line 3 in src/Util/Plain/MapPlainParseHelper.ts

View workflow job for this annotation

GitHub Actions / check

'TooBigPlainParseIssue' is defined but never used

Check warning on line 3 in src/Util/Plain/MapPlainParseHelper.ts

View workflow job for this annotation

GitHub Actions / check

'TooSmallPlainParseIssue' is defined but never used

export type ParseMapEntryKeyFn<T> = (v: unknown) => T | PlainParseIssue;
export type ParseMapEntryValueFn<T> = (v: unknown) => T | PlainParseIssue;

export class MapPlainParseHelper {

public static parsePrimitiveMap<K extends number | string, V>(
plain: unknown,
parseEntryKey: ParseMapEntryKeyFn<K>,
parseEntryValue: ParseMapEntryValueFn<V>,
path?: string,
issues?: PlainParseIssue[]
): PlainParseIssue | Map<K, V> {
if (!Array.isArray(plain)) {
const issue = new InvalidTypePlainParseIssue("map_entries", typeof plain, path);
issues?.push(issue);
return issue;
}

const entries = ArrayPlainParseHelper.parsePrimitiveArray(plain, (plainEntry) => {
if (!Array.isArray(plainEntry)) {
return new InvalidTypePlainParseIssue("map_entry", typeof plainEntry);
}

if (plainEntry.length !== 2) {
return new InvalidTypePlainParseIssue("map_entry", "array");
}

const key = parseEntryKey(plainEntry[0]);
const value = parseEntryValue(plainEntry[1]);

let keyIssue, valueIssue;
if (key instanceof PlainParseIssue) {
keyIssue = key;
}

if (value instanceof PlainParseIssue) {
valueIssue = value;
}

if (keyIssue || valueIssue) {
return new InvalidMapEntryPlainParseIssue(keyIssue, valueIssue);
}

return [key, value];
});

if (entries instanceof InvalidArrayElementsPlainParseIssue) {
const issue = new InvalidMapEntriesPlainParseIssue(entries.issues as any, path);
issues?.push(issue);
return issue;
}

return new Map(entries as any);
}

public static parseHObjectMap<K extends number | string, V extends object>(
plain: unknown,
parseEntryKey: ParseMapEntryKeyFn<K>,
objectClass: PlainParsableHObjectType<V, any>,
path?: string,
issues?: PlainParseIssue[]
): PlainParseIssue | Map<K, V> {
if (!Array.isArray(plain)) {
const issue = new InvalidTypePlainParseIssue("map_entries", typeof plain, path);
issues?.push(issue);
return issue;
}

const entries = ArrayPlainParseHelper.parsePrimitiveArray(plain, (plainEntry) => {
if (!Array.isArray(plainEntry)) {
return new InvalidTypePlainParseIssue("map_entry", typeof plainEntry);
}

if (plainEntry.length !== 2) {
return new InvalidTypePlainParseIssue("map_entry", "array");
}

const key = parseEntryKey(plainEntry[0]);
const valueParseResult = objectClass.parse(plainEntry[1]);

let keyIssue, valueIssue;
if (key instanceof PlainParseIssue) {
keyIssue = key;
}

if (valueParseResult.isError()) {
valueIssue = valueParseResult.e.data as InvalidHObjectPlainParseIssue;
}

if (keyIssue || valueIssue) {
return new InvalidMapEntryPlainParseIssue(keyIssue, valueIssue);
}

return [key, valueParseResult.v];
});

if (entries instanceof InvalidArrayElementsPlainParseIssue) {
const issue = new InvalidMapEntriesPlainParseIssue(entries.issues as any, path);
issues?.push(issue);
return issue;
}

return new Map(entries as any);
}
}
13 changes: 13 additions & 0 deletions src/Util/Plain/PlainParseHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,17 @@ export class PlainParseHelper {

return issue;
}

public static parseMap<T extends Record<string, unknown>>(plain: unknown, path?: string, issues?: PlainParseIssue[]): PlainParseIssue | T {
if (typeof plain === 'object' && plain !== null) {
return plain as T;
}

const issue = new InvalidTypePlainParseIssue('object', plain === null ? 'null' : typeof plain, path);
if (issues) {
issues.push(issue);
}

return issue;
}
}
48 changes: 46 additions & 2 deletions src/Util/Plain/PlainParseIssue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ export enum PlainParseIssueCode {
out_of_range = 'out_of_range',
invalid_enum_value = 'invalid_enum_value',
invalid_array_elements = 'invalid_array_elements',
invalid_map_entries = 'invalid_map_entries',
invalid_map_entry = 'invalid_map_entry',
invalid_hobject = 'invalid_hobject',
custom = 'custom',
}
Expand Down Expand Up @@ -62,7 +64,7 @@ export abstract class PlainParseIssue implements JsonSerialize {
}
}

export type PlainParsePrimitiveType = 'string' | 'number' | 'int' | 'uint' | 'bigint' | 'bigint_string' | "uint64_string" | 'boolean' | 'object' | 'array' | 'symbol' | 'undefined' | 'null' | 'function' | 'Date';
export type PlainParsePrimitiveType = 'string' | 'number' | 'int' | 'uint' | 'bigint' | 'bigint_string' | "uint64_string" | 'boolean' | 'object' | 'array' | 'map_entries' | 'map_entry' | 'symbol' | 'undefined' | 'null' | 'function' | 'Date';

export class InvalidTypePlainParseIssue extends PlainParseIssue {
public constructor(
Expand Down Expand Up @@ -96,7 +98,7 @@ export class InvalidStringPlainParseIssue extends PlainParseIssue {
}

public static uuid(path?: string): InvalidStringPlainParseIssue {
return new this('uuid', { }, "String must be UUID", path);
return new this('uuid', {}, "String must be UUID", path);
}

public static regex(regex: RegExp, path?: string): InvalidStringPlainParseIssue {
Expand Down Expand Up @@ -365,6 +367,48 @@ export class InvalidArrayElementsPlainParseIssue extends PlainParseIssue {
}
}

export class InvalidMapEntryPlainParseIssue extends PlainParseIssue {
public constructor(
public keyIssue?: PlainParseIssue,
public valueIssue?: PlainParseIssue,
path?: string
) {
super(PlainParseIssueCode.invalid_map_entry, 'Invalid map entry', path);
}

public toJSON(): JsonObjectType<InvalidMapEntryPlainParseIssue> {
return {
code: this.code,
message: this.message,
path: this.path,
i18n: this.i18n,

keyIssue: this.keyIssue?.toJSON(),
valueIssue: this.valueIssue?.toJSON(),
};
}
}

export class InvalidMapEntriesPlainParseIssue extends PlainParseIssue {
public constructor(
public issues: (InvalidMapEntryPlainParseIssue | InvalidTypePlainParseIssue)[],
path?: string
) {
super(PlainParseIssueCode.invalid_map_entries, 'Invalid map entries', path);
}

public toJSON(): JsonObjectType<InvalidMapEntriesPlainParseIssue> {
return {
code: this.code,
message: this.message,
path: this.path,
i18n: this.i18n,

issues: this.issues.map(v => v.toJSON() as any),
};
}
}

export class InvalidHObjectPlainParseIssue extends PlainParseIssue {
public constructor(
public typeMeta: HObjectTypeMeta & JsonExcluded,
Expand Down
8 changes: 6 additions & 2 deletions src/Util/Plain/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
export * from './PlainParseIssue';
export * from './types';

export * from './PlainParseHelper';

export * from './IntegerPlainParseHelper';
export * from './ArrayPlainParseHelper';
export * from './StringPlainParseHelper';
export * from './NumberPlainParseHelper';
export * from './NumberPlainParseHelper';

export * from './ArrayPlainParseHelper';
export * from './MapPlainParseHelper';
2 changes: 2 additions & 0 deletions test/helper/TestDto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import type { v } from "@/Util/Plain/types";
export class TestValueObject extends UInt { }

export class OtherTestDTO extends DTO {
public static HOBJ_META = HObjectTypeMeta.application('core', 'core', 'dto', 'OtherTestDTO', OtherTestDTO);

public primitiveField!: v.int.between<10, 100>;

// generate constructor in AOT
Expand Down
Loading
Loading