decaporg / decaporg/decap-cms

Programmatically validate object against collection config

Open
#5,955 2 comments 0 reactions 0 assignees View on GitHub
area: configuration area: validation type: feature
Dominant language
JavaScript
Stars
19.4k
Forks
3.1k
Avg merge
1d 14h
Merged PRs (30d)
9

Description

**Is your feature request related to a problem? Please describe.**

In certain situations, it's useful to be able to validate an object against a collection config. For example, when the config is changed (e.g. a required field added), a CI job could use a validation API to detect content that is no longer in the right format.

**Describe the solution you'd like**

Something like this:

```js
const json = fs.readFileSync('path/to/content.json').toString()
const obj = JSON.parse(json)
const collection = config.collections.find(c => c.name = 'foo')
CMS.validate(collection, obj) // throws if obj doesn't conform to expected shape
```

**Possible implementation**

It may be achievable via a static function:

```js
const fieldToJsonSchema = field => {
if (field.widget === 'string') {
return { type: 'string' }
}
...

if (field.widget === 'object') {
const schema = {
properties: Object.fromEntries(
field.fields.map(f => [f.name, fieldToJsonSchema(f)]),
),
required: field.fields.map(f => f.name).filter(f => f.required !== true),
}

if (field.widget === 'list') {
// ...
}
}

CMS.validate = (collection, obj) => {
return someJsonSchemaValidatorFromNpm.validate(fieldToJsonSchema(collection), obj)
}
```

There are a fair few edge-cases though.

**Describe alternatives you've considered**

N/A.

**Additional context**

Originally asked in Slack: https://netlifycms.slack.com/archives/CPRR0PQ9E/p1636036471070400

___

Note: I'd be willing to work on this if it would be accepted.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.