Skip to content

Commit

Permalink
fix(validator): array support
Browse files Browse the repository at this point in the history
  • Loading branch information
AliMD committed Mar 7, 2023
1 parent e8e0d0f commit 08f5215
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 12 deletions.
2 changes: 1 addition & 1 deletion core/type/src/type-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export type Stringifyable =
| null
| undefined
| { [P: string]: Stringifyable }
| Array<Stringifyable>;
| Array<StringifyableRecord>;


export interface StringifyableRecord {
Expand Down
34 changes: 23 additions & 11 deletions core/validator/src/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ export type {JsonSchema};

export function validator<T extends StringifyableRecord>(
validSchema: JsonSchema,
targetObject?: StringifyableRecord | Array<StringifyableRecord> | null,
targetObject?: StringifyableRecord | null,
additionalProperties = false,
path = '.',
): T {
if (typeof targetObject !== 'object' || targetObject == null) {
if (targetObject == null || typeof targetObject !== 'object') {
throw new Error('invalid_type', {
cause: {
message: 'targetObject is not a function or null',
message: 'targetObject root not valid',
itemPath: path,
itemSchema: 'JsonSchema',
itemValue: String(targetObject),
Expand Down Expand Up @@ -45,24 +45,36 @@ export function validator<T extends StringifyableRecord>(

if (Array.isArray(itemSchema)) {
// array
for (const index in itemSchema) {
if (!Array.isArray(itemValue)) {
throw new Error('invalid_type', {
cause: {
message: 'invalid type',
itemPath,
itemSchema: 'Array',
itemValue: String(itemValue),
},
});
}
// else
const schema = itemSchema[0];
for (const index in itemValue) {
if (!Object.prototype.hasOwnProperty.call(itemSchema, index)) continue;
const item = itemSchema[index];
const item = itemValue[index];
targetObject[index] = validator<StringifyableRecord>(
schema,
item,
itemValue[index] as Array<StringifyableRecord>,
additionalProperties,
itemPath[index],
`${itemPath}[${index}]`,
);
}
}
else if (typeof itemSchema === 'object' && itemSchema != null) {
// nested object
targetObject[itemName] = validator<StringifyableRecord>(
itemSchema,
itemValue as StringifyableRecord,
additionalProperties,
itemPath,
itemValue as StringifyableRecord,
additionalProperties,
itemPath,
);
}
else if (itemSchema === Boolean) {
Expand All @@ -86,7 +98,7 @@ export function validator<T extends StringifyableRecord>(
}
else if (itemSchema === Number) {
if (isNumber(itemValue)) {
targetObject[itemName] = +<string>itemValue;
targetObject[itemName] = +(<string>itemValue);
}
else {
throw new Error('invalid_type', {
Expand Down

0 comments on commit 08f5215

Please sign in to comment.