Skip to content
Anjunar/ DOCS

Schemas and rules

A schema lists the properties an entity exposes. A rule per property decides, per instance, whether it is visible and whether it may be written.

Schema

A companion that provides it

The companion object extends SchemaProvider and declares a nested class Schema. property selects a property type-safely through a macro from scala-reflect.

scala
import com.anjunar.json.mapper.provider.{DTO, EntityProvider} import com.anjunar.json.mapper.schema.{DefaultWritableRule, EntitySchema, SchemaProvider} class Article extends DTO with EntityProvider { @(JsonbProperty @field) var id: UUID = UUID.randomUUID() var version: Long = -1 @(JsonbProperty @field) var title: String = null @(JsonbProperty @field) var body: String = null @(JsonbProperty @field) var author: User = null } object Article extends SchemaProvider[Article.Schema] { class Schema extends EntitySchema[Article] { val title = property(_.title, classOf[DefaultWritableRule[Article]]) val body = property(_.body, classOf[AuthorRule[Article]]) val author = property(_.author) } }
Effect

Only what the schema lists

With a schema, a property that is not listed is neither serialized nor deserialized, even with @JsonbProperty. Without a rule argument, DefaultRule applies: visible, but read-only.

DefaultRule[E]
Visible, never writable. The default.
DefaultWritableRule[E]
Visible and writable.
VisibilityRule[E]
Your own rule: isVisible and isWriteable per instance and property.
Rules

Decisions per instance

A rule sees the instance and the property. It is created through the inject function, so it can take constructor dependencies such as the current user.

scala
import com.anjunar.json.mapper.schema.VisibilityRule import com.anjunar.scala.universe.introspector.AbstractProperty class AuthorRule[E <: Article](identity: CurrentUser) extends VisibilityRule[E] { def isVisible(instance: E, property: AbstractProperty): Boolean = true def isWriteable(instance: E, property: AbstractProperty): Boolean = instance.author != null && instance.author.id == identity.id }
Invisible means absent

A property the rule hides is left out of the JSON entirely, and a property it does not allow to write is ignored silently when it arrives. Clients never see an error for it.