
Security News
MCP Community Begins Work on Official MCP Metaregistry
The MCP community is launching an official registry to standardize AI tool discovery and let agents dynamically find and install MCP servers.
Define, create, and validate your business objects, based on well defined schema.
schemata allows you to define schemas to ensure your objects are well formed. This is similar to the concept of a schema in mongoose but unlike mongoose schemata has nothing to do with data persistence. This lightweight decoupled approach gives the ultimate flexibility and freedom to use the module within your application whether you are storing your objects or not.
This should be compatible with v6 but has some major rewrites, hence the version bump.
You can now validate using regular functions, promises and the old style callback.
const databaseLookup = async () => null
// Regular function
const isOfWizardingAge = (propertyName, name, entity) =>
entity[propertyName] < 17 && 'Sorry you are not of age'
// Promise
const isUniqueAge = async (propertyName, name, entity) => {
const found = await databaseLookup({ age: entity[propertyName] })
if (found) return `${entity[propertyName]} already exists`
}
const properties = createContactSchema().getProperties()
properties.age.validators = [
isOfWizardingAge,
isUniqueAge,
(propertyName, name, object, cb) =>
cb(null, `${propertyName} ${name} ${object[propertyName]}`)
]
const schema = createNamedSchemata(properties)
const errors = await schema.validate(
schema.makeDefault({ name: 'Paul', age: 16 })
)
console.error(errors)
This version is the first to be transpiled using babel and with async.js
removed.
Moves castProperty
to a static function.
The main initialization arguments have now changed so you must provide a name
and can also provide a description
. The schema definition is now set via the
properties
property.
Validate now return a promise if a callback is not provided.
Node 6+ upgrade. Direct access to the schema has been removed (schema.schema
) and getProperties()
must now be used.
schema.validators.all = []
. Now schema.validators = []
is equivalent.stripUnknownProperties()
was not stripping out properties of type array that were null.This version prevents you from using arrays and objects for defaultValue
. Now
only primitives and functions are allowed. If you are not doing this in your
project then you can safely upgrade from v2. See
https://github.com/serby/schemata/pull/34 for more details.
npm install schemata
const schemata = require('schemata')
const contactSchema = schemata({
name: 'Contact',
description: 'One of my friends or acquaintance',
properties: {
name: {
name: 'Full Name'
},
age: {
type: Number
defaultValue: 0
},
active: {
type: Boolean,
defaultValue: true
},
phoneNumber: { // If no type is given String will be assumed
},
createdDate: {
type: Date,
defaultValue: () => new Date()
}
}
})
.validators = [ validatorA, validatorB ]
as a shorthand. Since 4.0.0 you can also omit the callback and provide a promise.const blank = contactSchema.makeBlank()
{
name: null,
age: null,
active: null,
phoneNumber: null
}
const default = contactSchema.makeDefault()
{
name: null,
age: 0,
active: true,
phoneNumber: null
}
Sometimes you've receive data from a POST or another IO operation that may have more properties than your business object expect. stripUnknownProperties will take an object and strip out any properties that aren't defined in the schemata scheme.
var stripped = contactSchema.stripUnknownProperties({
name: 'Dom',
extra: 'This should not be here'
})
{
name: 'Dom'
}
Validation is easy in schemata, just call validate() on your schema passing in the object to validate:
contactSchema.validate(objectToValidate, function(error, errors) {
// errors
})
Validators are assigned to a field of the schema by adding them as an array to the validators property of the object as follows (this is an extension of the example at the top):
name: {
name: 'Full Name',
validators: { all: [validator1, validator2] }
}
Validators are functions that have the following signature:
function(propertyName, errorPropertyName, object, callback) {}
The callback must be called with a falsy value (such as undefined or null) if the validation passes, or with a string with the appropriate error message if it fails validation.
A full validator example:
const required = function (propertyName, errorPropertyName, object, callback) {
return callback(object[propertyName] ? undefined : errorPropertyName + ' is required')
}
name: {
name: 'Full Name',
validators: { all: [ required ] }
}
If any of the validators fail then the errors will be returned in the callback from validate() with the object key being the field name and the value being the error message.
For a comprehensive set of validators including: email, integer, string length, required & UK postcode. Check out validity.
Type casting is done in schemata using the cast() and castProperty() functions. cast() is used for when you want to cast multiple properties against a schema, castProperty() is used if you want to cast one property and explicitly provide the type.
const schemata = require('schemata')
const person = schemata({
name: 'Person',
description: 'Someone',
properties: {
name: {
type: String
},
age: {
type: Number
},
active: {
type: Boolean
},
birthday: {
type: Date
},
friends: {
type: Array
},
extraInfo: {
type: Object
}
}
})
const objectToCast = {
name: 123456,
age: '83',
active: 'no',
birthday: '13 February 1991',
friends: '',
extraInfo: undefined
}
var casted = person.cast(objectToCast)
{
name: '123456',
age: 83,
active: false,
birthday: Date('Wed Feb 13 1991 00:00:00 GMT+0000 (GMT)'),
friends: [],
extraInfo: {}
}
If you want to output the name of a schema property in a human-readable format then you need the propertyName() function. If your schema field has a name attribute, then that is returned. If that is not set then the name is obtained by decamelcasing the field name.
Consider the following example:
const schemata = require('schemata')
const address = schemata({
name: 'Address',
description: 'Postal location',
properties: {
addressLine1: {},
addressLine2: {},
addressLine3: {
name: 'Town'
},
addressLine4: {
name: 'Region'
}
}
})
console.log(address.propertyName('addressLine1'))
// Returns 'Address Line 1' because there is no name set
console.log(address.propertyName('addressLine3'))
// Returns 'Town' because there is a name set
Paul Serby follow me on twitter @serby
ISC
FAQs
Define, create, and validate your business objects, based on well defined schema.
The npm package schemata receives a total of 118 weekly downloads. As such, schemata popularity was classified as not popular.
We found that schemata demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The MCP community is launching an official registry to standardize AI tool discovery and let agents dynamically find and install MCP servers.
Research
Security News
Socket uncovers an npm Trojan stealing crypto wallets and BullX credentials via obfuscated code and Telegram exfiltration.
Research
Security News
Malicious npm packages posing as developer tools target macOS Cursor IDE users, stealing credentials and modifying files to gain persistent backdoor access.