Skip to content

Commit

Permalink
[validation] Add new assetRequired-flag (#1285)
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed May 3, 2019
1 parent 96b6689 commit 36428e8
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 9 deletions.
29 changes: 22 additions & 7 deletions packages/@sanity/validation/src/Rule.js
Expand Up @@ -16,16 +16,17 @@ const mergeRequired = (prev, next) => {

class Rule {
static FIELD_REF = Symbol('FIELD_REF')
static array = () => new Rule().type('Array')
static object = () => new Rule().type('Object')
static string = () => new Rule().type('String')
static number = () => new Rule().type('Number')
static boolean = () => new Rule().type('Boolean')
static dateTime = () => new Rule().type('Date')
static array = def => new Rule(def).type('Array')
static object = def => new Rule(def).type('Object')
static string = def => new Rule(def).type('String')
static number = def => new Rule(def).type('Number')
static boolean = def => new Rule(def).type('Boolean')
static dateTime = def => new Rule(def).type('Date')
static valueOfField = path => ({type: Rule.FIELD_REF, path})

constructor() {
constructor(typeDef) {
this.FIELD_REF = Rule.FIELD_REF
this._typeDef = typeDef

this.reset()
}
Expand Down Expand Up @@ -72,6 +73,7 @@ class Rule {
rule._rules = cloneDeep(this._rules)
rule._level = this._level
rule._fieldRules = this._fieldRules
rule._typeDef = this._typeDef
return rule
}

Expand Down Expand Up @@ -258,6 +260,19 @@ class Rule {
rule._fieldRules = rules
return rule
}

assetRequired() {
const base = getBaseType(this._typeDef)
let assetType = 'Asset'
if (base && ['image', 'file'].includes(base.name)) {
assetType = base.name === 'image' ? 'Image' : 'File'
}
return this.cloneWithRules([{flag: 'assetRequired', constraint: {assetType}}])
}
}

function getBaseType(type) {
return type && type.type ? getBaseType(type.type) : type
}

module.exports = Rule
2 changes: 1 addition & 1 deletion packages/@sanity/validation/src/inferFromSchemaType.js
Expand Up @@ -27,7 +27,7 @@ function inferFromSchemaType(typeDef, schema, visited = new Set()) {

const type = typeDef.type
const typed = Rule[typeDef.jsonType]
let base = typed ? typed() : new Rule()
let base = typed ? typed(typeDef) : new Rule(typeDef)

if (type && type.name === 'datetime') {
base = base.type('Date')
Expand Down
12 changes: 11 additions & 1 deletion packages/@sanity/validation/src/validators/objectValidator.js
Expand Up @@ -25,7 +25,17 @@ const reference = (unused, value, message) => {
return true
}

const assetRequired = (flag, value, message) => {
if (!value || !value.asset || !value.asset._ref) {
const assetType = flag.assetType || 'Asset'
return new ValidationError(message || `${assetType} required`)
}

return true
}

module.exports = Object.assign({}, genericValidator, {
presence,
reference
reference,
assetRequired
})

0 comments on commit 36428e8

Please sign in to comment.