Skip to content

Custom Operations

Custom operations are declared when you create the schema.

javascript
const userSchema = createSchema({
  id: { type: 'id', required: true },
  email: { type: 'string', required: true },
  role: { type: 'string', defaultTo: 'guest' }
}, {
  operations: {
    upsert: {
      targetFields: 'schema',
      enforceRequired: false,
      applyDefaults: true,
      outputFields: 'validated'
    }
  }
})

const result = userSchema.upsert({ email: 'alex@example.com' })
const sameResult = userSchema.validateWith('upsert', { email: 'alex@example.com' })

Operation aliases are generated automatically from the operation registry, so create, replace, and patch keep working exactly as before. If you intentionally redefine one of those names in operations, the built-in behavior is replaced for that schema instance.

Supported operation descriptor keys:

KeyAllowed ValuesMeaning
targetFields'schema' or 'input'Which fields are validated. 'schema' walks the schema definition, 'input' only validates explicitly provided fields.
enforceRequiredtrue or falseWhether missing required fields produce errors.
applyDefaultstrue or falseWhether omitted fields with defaultTo are materialized into the result.
outputFields'validated' or 'input'Which field set is considered when building validatedObject. 'validated' follows schema fields, 'input' follows only explicitly provided fields.
rejectExplicitUndefinedtrue or falseWhether an explicitly provided undefined value is treated as a type error. Defaults to true.

Method names are generated automatically from operation names. Names that already exist on Schema are reserved and rejected. In practice that means names such as validateWith, toJsonSchema, getFieldDefinitions, getFieldDefinition, getFieldMessages, and cleanup cannot be used as operation aliases.

GPL-3.0-only