Skip to content

Commit

Permalink
cleanup style
Browse files Browse the repository at this point in the history
  • Loading branch information
ianstormtaylor committed Feb 23, 2018
1 parent d23231d commit 15973e3
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 19 deletions.
34 changes: 20 additions & 14 deletions src/error.js
Expand Up @@ -7,29 +7,35 @@

class StructError extends TypeError {

static format(attrs) {
const { type, path, value } = attrs
const message = `Expected a value of type \`${type}\`${path.length ? ` for \`${path.join('.')}\`` : ''} but received \`${JSON.stringify(value)}\`.`
return message
}

constructor(attrs) {
super()
const errors = attrs.errors || []
this.message = this.constructor.format(attrs)
this.data = attrs.data
this.path = attrs.path
this.value = attrs.value
this.reason = attrs.reason
this.type = attrs.type
const message = StructError.format(attrs)
super(message)

const { data, path, value, reason, type, errors = [] } = attrs
this.data = data
this.path = path
this.value = value
this.reason = reason
this.type = type
this.errors = errors
if (!errors.length) errors.push(this)

if (!errors.length) {
errors.push(this)
}

if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor)
} else {
this.stack = (new Error()).stack
}
}

static format(attrs) {
const path = attrs.path.join('.')
return `Expected a value of type \`${attrs.type}\`${path.length ? ` for \`${path}\`` : ''} but received \`${JSON.stringify(attrs.value)}\`.`
}

}

/**
Expand Down
15 changes: 12 additions & 3 deletions src/kinds.js
Expand Up @@ -29,8 +29,13 @@ class Kind {
*/

function any(schema, defaults, options) {
if (isStruct(schema)) return schema[KIND]
if (schema instanceof Kind) return schema
if (isStruct(schema)) {
return schema[KIND]
}

if (schema instanceof Kind) {
return schema
}

switch (kindOf(schema)) {
case 'array': {
Expand Down Expand Up @@ -741,7 +746,11 @@ function union(schema, defaults, options) {

for (const k of kinds) {
const [ e, r ] = k.validate(value)
if (!e) return [undefined, r]

if (!e) {
return [undefined, r]
}

error = e
}

Expand Down
12 changes: 10 additions & 2 deletions src/superstruct.js
Expand Up @@ -57,7 +57,11 @@ function superstruct(config = {}) {

Struct.assert = (value) => {
const [ error, result ] = kind.validate(value)
if (error) throw new StructError(error)

if (error) {
throw new StructError(error)
}

return result
}

Expand All @@ -68,7 +72,11 @@ function superstruct(config = {}) {

Struct.validate = (value) => {
const [ error, result ] = kind.validate(value)
if (error) return [new StructError(error)]

if (error) {
return [new StructError(error)]
}

return [undefined, result]
}

Expand Down

0 comments on commit 15973e3

Please sign in to comment.