loopback-jsonschema-registry
v1.1.2
Published
JSON Schema based validation for LoopBack through a custom model registry
Downloads
3
Readme
LoopBack JSON Schema Registry
Example Usage
server.js
:
import loopback from 'loopback'
import Registry from 'loopback-jsonschema-registry'
import path from 'path'
// Configure the app to not load the built-in models, so that the registry
// can be overridden first, allowing to change the way model.json configs are
// parsed.
const app = loopback({
localRegistry: true,
loadBuiltinModels: false
})
// Override app.registry with a JSON Schema Registry
app.registry = new Registry({
// Load and register all validators (keywords or formats) from ./validators
loadValidators: path.resolve(__dirname, 'validators'),
// Disable and emulate default LoopBack validations through JSON schema:
emulateValidations: true,
// Define further processing / translation of model JSON properties:
configureProperty(schema) {
if (schema.computed) {
// Don't include computed properties in LB schema.
return false
}
// App-wide rules:
const {type} = schema
if (type === 'integer') {
// JSON 'integer' is translated to LB 'number'
schema.type = 'number'
} else if (type === 'number' && !schema.postgresql) {
// JSON 'number' is used for double precision fields by adding postgresql
// specific information
schema.postgresql = {
dataType: 'double precision'
}
}
}
})
validators/range.js
:
export default {
keyword: 'range',
type: ['number', 'integer'],
metaSchema: {
type: 'array',
items: [
{ type: 'number' },
{ type: 'number' }
],
additionalItems: false
},
macro(config) {
return {
minimum: config[0],
maximum: config[1]
}
}
}
models/test.json
:
{
"name": "Test",
"base": "PersistedModel",
"properties": {
"factor": {
"type": "integer",
"range": [0, 50],
"required": true
}
}
}
DEBUG=loopback:contrib:jsonschema-registry yarn start
loopback:contrib:jsonschema-registry LoopBack Schema for Model `Test`:
{
"name": "Test",
"base": "PersistedModel",
"properties": {
"factor": {
"type": "number",
"required": true
}
}
}
loopback:contrib:jsonschema-registry JSON Schema for Model `Test`:
{
"id": "Test",
"$schema": "http://json-schema.org/draft-06/schema#",
"$async": true,
"type": "object",
"properties": {
"factor": {
"type": "integer",
"range": [
0,
50
],
"format": "required"
},
"id": {
"type": [
"number",
"null"
]
}
},
"required": [
"factor"
],
"additionalProperties": false
}