Configures a field in the schema. Cosmosnaut uses
JSON Schema as a standard, cross-language way to
validate data. This object is a JSON 7 Schema which is validated by
Ajv. The Ajv instance can be found as a static
property on BaseModel.ajv, which you can use to register custom
validation functions as needed.
Once you define validation on the schema field, you can get a JSON Schema
for the full model by calling schema.jsonSchema. Models can be
individually validated by calling BaseModel.validate, and they're
validated automatically when calling save, create, or update.
Additionally, you can pass a Transform in the transform property
here. Validation is run on the non-transformed, database version of the
properties.
Here's an example using all of these features:
constuserSchema = createSchema('users') .partitionKey('/id')// Do some basic length validation on the username: .field('username', asType<string>(), {type:'string',maxLength:20,minLength:2, })// Validate `favoriteColors`. Store it as an array in Cosmos DB, but// use it as a Set in the model. .field('favoriteColors', asType<Set<string>>(), {type:'array',maxItems:3,items: { type:'string' },transform:newTransform<string[], Set<string>>(stored=>newSet(stored),app=>Array.from(app), ), });
Configures a field in the schema. Cosmosnaut uses JSON Schema as a standard, cross-language way to validate data. This object is a JSON 7 Schema which is validated by Ajv. The Ajv instance can be found as a static property on BaseModel.ajv, which you can use to register custom validation functions as needed.
Once you define validation on the schema field, you can get a JSON Schema for the full model by calling
schema.jsonSchema
. Models can be individually validated by calling BaseModel.validate, and they're validated automatically when callingsave
,create
, orupdate
.Additionally, you can pass a Transform in the
transform
property here. Validation is run on the non-transformed, database version of the properties.Here's an example using all of these features: