ShareDB-Schema
- Racer plugin for schema validation module for ShareDB
- Uses z-schema, which supports JSON-Schema v4
- Schema validation executes in sync
validate
hook, so you validate the actual result of operation - Supports custom validators with async and sync logic
- Custom validators can preload data in async hook to use it later in sync
Known Issues
- Works only with JSON OT type
- Format functions should be sync
- For every op the whole doc validates each time, because it`s the only case when z-schema returns full path to wrong fields
Installation
yarn add @startupjs/sharedb-schema
Setting
Step 1. Options
var options = {
schemas: {
users: {
title: 'Example Schema',
type: 'object',
properties: {
nickname: {
type: 'string',
format: 'xstring',
minLength: 1,
maxLength: 10,
},
email: {
type: 'string',
format: 'email',
},
age: {
description: 'Age in years',
type: 'integer',
minimum: 0,
},
roleId: {
type: 'string',
collection: 'roles',
validators: ['join'],
},
hobbies: {
type: 'array',
maxItems: 3,
items: {
type: 'string',
},
uniqueItems: true,
},
},
required: ['email'],
}
},
formats: {
xstring: function(str) {
return str !== 'xxx';
}
},
validators: {
join: {
async: function (context, done) {
var id = context.value
if (!id) return done()
var collection = context.schema.collection
var model = this.store.createModel()
var $entity = model.at(collection + '.' + id)
model.fetch($entity, function (err) {
if (err) return done(err)
if (!$entity.get()) {
return done(Error('No ' + collection + ' with id ' + id))
}
done()
})
},
},
preload: {
async: function (context, done) {
var model = this.store.createModel()
var $someData = model.at('some.path')
model.fetch($someData, function (err) {
if (err) return done(err)
var data = $someData.get()
done(null, data)
})
},
sync: function (value, context) {
var data = context.data
return true || false
},
},
},
}
Step 2. Plugin
Add the sharedbSchemaInit
function to your server/index.js
const sharedbSchemaInit = require('@startupjs/sharedb-schema')
and then call this function in the backend event
eventEmitter.on('backend', async backend => {
sharedbSchemaInit(backend, options)
})
The MIT License
Copyright (c) 2016 Pavel Zhukov