Skip to content

Commit

Permalink
fix: improve array handling
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Mar 21, 2021
1 parent ee4341d commit f1a62f3
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 11 deletions.
25 changes: 16 additions & 9 deletions src/schema.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getType, isObject } from './utils'
import { getType, isObject, unique } from './utils'
import type { InputObject, InputValue, JSValue, Schema } from './types'

export function resolveSchema (obj: InputObject) {
Expand All @@ -11,10 +11,10 @@ export function resolveSchema (obj: InputObject) {
function _resolveSchema (input: InputValue, parent: InputObject, root: InputObject): Schema {
// Node is plain value
if (!isObject(input)) {
return {
return normalizeSchema({
type: getType(input),
default: input as JSValue
}
})
}

// Clone to avoid mutation
Expand Down Expand Up @@ -43,13 +43,20 @@ function _resolveSchema (input: InputValue, parent: InputObject, root: InputObje

// Infer type from default value
if (!schema.type) {
if (Array.isArray(schema.default)) {
schema.type = 'array'
schema.items = schema.default.map(i => getType(i)).map(type => ({ type }))
} else {
schema.type = getType(schema.default) || (schema.properties ? 'object' : 'any')
}
schema.type = getType(schema.default) || (schema.properties ? 'object' : 'any')
}

return normalizeSchema(schema)
}

function normalizeSchema (schema: Schema) {
if (schema.type === 'array' && !('items' in schema)) {
schema.items = {
type: unique((schema.default as any[]).map(i => getType(i)))
}
if (!schema.items.type.length) {
schema.items.type = 'any'
}
}
return schema
}
4 changes: 2 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ export type JSType =

// A subset of JSONSchema7
export interface Schema {
type?: JSType
items?: Schema[]
type?: JSType | JSType[]
items?: Schema
default?: JSValue
properties?: { [key: string]: Schema }
title?: string
Expand Down
4 changes: 4 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,7 @@ export function getType (val: any): JSType | null {
export function isObject (val: any): boolean {
return val !== null && !Array.isArray(val) && typeof val === 'object'
}

export function unique (arr: any[]) {
return Array.from(new Set(arr))
}

0 comments on commit f1a62f3

Please sign in to comment.