Skip to content

Commit

Permalink
[field] Add basic value validation to differ
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Oct 6, 2020
1 parent ab16435 commit 5d590fd
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
5 changes: 5 additions & 0 deletions packages/@sanity/field/src/diff/changes/ValueError.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import * as React from 'react'

export function ValueError(props: any) {
return <div>Value error</div>
}
19 changes: 15 additions & 4 deletions packages/@sanity/field/src/diff/changes/buildChangeList.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import {pathToString} from '../../paths'
import {getValueError} from '../../validation'
import {getArrayDiffItemType} from '../../schema/helpers'
import {resolveDiffComponent} from '../resolve/resolveDiffComponent'
import {
ObjectSchemaType,
ObjectDiff,
Expand All @@ -9,9 +13,7 @@ import {
ArraySchemaType,
ArrayDiff
} from '../types'
import {getArrayDiffItemType} from '../../schema/helpers'
import {resolveDiffComponent} from '../resolve/resolveDiffComponent'
import {pathToString} from '../../paths'
import {ValueError} from './ValueError'

export function buildDocumentChangeList(schemaType: ObjectSchemaType, diff: ObjectDiff) {
const changes = buildChangeList(schemaType, diff)
Expand Down Expand Up @@ -44,6 +46,15 @@ export function buildChangeList(
}
}

let error
if (typeof diff.fromValue !== 'undefined') {
error = getValueError(diff.fromValue, schemaType)
}

if (!error && typeof diff.toValue !== 'undefined') {
error = getValueError(diff.toValue, schemaType)
}

return [
{
type: 'field',
Expand All @@ -52,7 +63,7 @@ export function buildChangeList(
titlePath,
schemaType,
key: pathToString(path),
diffComponent,
diffComponent: error ? ValueError : diffComponent,
childChanges:
childChanges.length === 1 && childChanges[0].type === 'group'
? childChanges[0].changes
Expand Down
20 changes: 20 additions & 0 deletions packages/@sanity/field/src/validation/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {SchemaType} from '../diff'

export function getValueError(value: unknown, schemaType: SchemaType) {
const {jsonType} = schemaType
const valueType = typeof value

if (value === null || valueType === 'undefined') {
return undefined
}

if (Array.isArray(value) && jsonType !== 'array') {
return {error: `Value is array, expected ${jsonType}`, value}
}

if (valueType !== jsonType) {
return {error: `Value is ${valueType}, expected ${jsonType}`, value}
}

return undefined
}

0 comments on commit 5d590fd

Please sign in to comment.