This is the multi-page printable view of this section.
Click here to print.
Return to the regular view of this page.
The Data Layer
Entities, services and data providers: schemas, caching, and view binding.
The data layer gives you schema-validated entities, a caching service layer,
and data providers that keep view state synchronized with the cache
automatically.
The three classes
| Class |
Role |
Entity |
A typed, schema-validated data object with composite-key support |
Service |
CRUD + custom operations against a remote API, with a client-side entity cache |
DataProvider |
Per-view state manager that binds view state to service cache data |
The flow is unidirectional:
View ←(state)— DataProvider ←(entityChanged/cacheChanged)— Service → remote API
—(create/update/delete)—→ Service —→ cache —→ all bound DataProviders updated
Views never talk to the network. They render whatever their data provider (or
plain state) gives them. Services cache every entity they see, so two views
showing the same entity are always consistent — when one view saves a change,
the other’s bound data updates automatically.
In This Section
1 - Entities
Defining typed, schema-validated data objects with the Entity class.
An Entity is a typed data object: you declare a static schema, and instances
validate, coerce and serialize their data against it.
Defining an entity
Extend Entity and declare a static schema. Each field descriptor
supports type, required, id, and entityClass (for nested entities):
import { Entity } from "/lib/altseven/dist/a7.js";
export class Todo extends Entity {
static schema = {
todoID: { type: "string", id: true },
title: { type: "string", required: true },
done: { type: "boolean" },
created: { type: "date" },
tags: { type: "array" },
priority: { type: "integer" }
};
}
Supported types: string, integer, float, boolean, date, array,
object (optionally with an entityClass for nested entities).
Creating instances
The constructor validates required fields, defines getters/setters for every
schema field, and coerces values:
const todo = new Todo( {
todoID: "t1",
title: "Write the docs",
created: "2026-11-16T09:00:00Z", // string → Date
done: 1 // 1/0 → true/false
} );
todo.title; // "Write the docs"
todo.created; // Date object
todo.done; // true
todo.id; // "t1" — .id returns the field marked id: true
todo.validate(); // true
Validation is strict: assigning a wrong type throws
(Invalid type for property done. Expected boolean, but got string.), missing
required fields throw at construction, and date fields accept either Date
objects or parseable date strings.
Composite keys
Marking several fields with id: true defines a composite primary key. The
service layer joins the values into a single string key ("user42|post7"), so
entities with multi-field identities cache and bind correctly:
export class Enrollment extends Entity {
static schema = {
userID: { type: "integer", id: true },
courseID:{ type: "integer", id: true },
grade: { type: "string" }
};
}
Nested entities
An object field with an entityClass is instantiated automatically:
export class Comment extends Entity {
static schema = {
commentID: { type: "string", id: true },
author: { type: "object", entityClass: User } // another Entity class
};
}
const c = new Comment( { commentID: "c1", author: { userID: 7, name: "Rob" } } );
c.author instanceof User; // true — the plain object was coerced
Custom getters and setters
Subclasses can define their own getters/setters for schema fields; the Entity
base detects them and wraps rather than replaces them — useful for computed
values or side effects on assignment.
Serialization
Entities convert to and from plain objects at the API boundary:
todo.toFlatObject();
// { todoID: "t1", title: "Write the docs", done: true, created: Date, ... }
todo.fromFlatObject( { title: "Rewrite the docs" } ); // validates via setters
Service uses fromFlatObject() internally to load JSON responses into entity
instances, so your endpoints just return plain JSON.
Where entities live
Entities are pure data — no network, no DOM. Instantiate them in services (the
service layer does it for you), and pass them around as values. Views render
entity data from their state; they don’t own entities.
2 - Services
CRUD operations against a REST API with client-side caching, filtering and sorting.
A Service wraps a remote API: it performs CRUD operations, caches every entity
it loads or saves in the application model, deduplicates concurrent identical
requests, and notifies data providers when cached data changes.
Remote modules first
Services call endpoints defined in remote modules — plain objects passed to
the application in the remote.modules option. Each method is either an object
{ url, params } or a function:
// remote/todo.js
export var todo = {
create: {
url: "/api/todos"
}, // POST /api/todos (create is POST by default)
read: {
url: "/api/todos/:todoID" // GET, :todoID replaced from params
},
update: {
url: "/api/todos/:todoID" // PUT, body = params
},
destroy: {
url: "/api/todos/:todoID" // DELETE
},
readAll: {
url: "/api/todos" // GET
},
readMany: {
url: "/api/todos/byids", // custom method: method from params, default GET
params: { method: "POST" }
},
deleteByList: { // any custom name works
url: "/api/todos/batch",
params: { method: "DELETE" }
}
};
The framework maps the standard action names to HTTP verbs: create → POST,
read/readAll → GET, update → PUT, destroy → DELETE. :param segments
in URLs are replaced from the params object ({ todoID: "t1" } →
/api/todos/t1).
Function modules take the params object and do their own fetching:
export var stats = {
mostActive: function( params ) {
return myApp.remote.fetch( "/api/stats/mostActive", { method: "GET" }, true );
}
};
Defining a service
Extend Service and pass four things: an id (also the cache key), a key
(the fallback single-key field), the entityClass, and remoteMethods —
a map of operation names to "module.action" strings:
import { Service } from "/lib/altseven/dist/a7.js";
import { Todo } from "../entity/todo.js";
export class TodoService extends Service {
constructor() {
super( {
id: "todos", // service id and model cache key
key: "todoID", // fallback key field
entityClass: Todo,
remoteMethods: {
create: "todo.create",
read: "todo.read",
update: "todo.update",
delete: "todo.destroy", // Service.delete → remote action "destroy"
readAll: "todo.readAll",
readMany:"todo.readMany"
}
} );
}
}
Register the service — either declaratively in options:
import { TodoService } from "./service/todo.js";
export const myApp = new Application( {
remote: { modules: { todo, stats } },
services: [ new TodoService() ] // registered automatically at init
// ...
} );
or manually after init: myApp.services.register( new TodoService() ).
CRUD operations
All service methods are async and return entity instances:
const todoService = myApp.services.getService( "todos" );
// create — POSTs, caches the saved entity (with its server-assigned id)
const todo = await todoService.create( { title: "Write the docs" } );
// read one — cache first; only a cache miss hits the network
const t1 = await todoService.read( { todoID: "t1" } );
// read many — fetches ONLY the ids missing from the cache
const list = await todoService.readMany( [ "t1", "t2", "t3" ] ); // → array
// read all — one request if the cache is empty
const all = await todoService.readAll(); // → Map keyed by entity id
// update — PUTs, re-caches, fires entityChanged
todo.done = true;
await todoService.update( todo );
// delete — DELETEs, evicts from cache, fires entityDeleted
await todoService.delete( todo );
Every create/update/delete updates the cache and fires entityChanged /
entityDeleted events, which is what keeps bound views in sync.
Request deduplication
Concurrent identical read, readMany, readAll and invoke calls share one
network request: the second caller receives the first caller’s promise. This
matters when several views mount at once and all ask for the same data.
Custom methods
invoke() calls any remote module method not in the standard CRUD set, with
optional caching and filtering:
// remoteMethods: { byUser: "todo.readMany" }
const todos = await todoService.invoke( "byUser", { userID: 7 } );
// options (all optional):
const result = await todoService.invoke( "byUser", { userID: 7 }, {
checkCache: true, // return cached data without a network call when possible
merge: true, // merge the response into the cache
filter: { done: [ "=", false ] },
returnType: "Array" // or "Map"
} );
Cache access
The cache is a Map stored in the model under the service id:
todoService.get(); // whole cache Map
todoService.get( "t1" ); // one entity, or undefined if absent
// since 9.1.3: get() with NO argument returns everything; a *present but
// falsy* key (null, 0, "") is a lookup that MISSES and returns undefined —
// never the whole map. Rely on that; guard for undefined.
Filtering and sorting
filter() and sort() work on arrays or Maps of entities, client-side:
const open = todoService.filter( cached, {
done: [ "=", false ],
priority: [ ">=", 2 ],
title: [ "=", "^write", true ], // regex: [operator, pattern, useRegex]
tags: [ "in", [ "docs", "api" ] ] // also "not in", "=", "!=", ">", "<", ">=", "<="
} );
const sorted = todoService.sort( open, { priority: "desc", title: "asc" } );
// a bare value means equality:
const mine = todoService.filter( cached, { userID: 7 } );
A word on caching strategy
The cache never expires on its own — it is a session cache, not a database.
readAll() will not re-fetch once the cache has data, so for data that changes
server-side outside your app, either call invoke() with explicit options, or
re-fetch into the cache with merge() when you know data changed (e.g. after a
WebSocket notification).
3 - DataProviders
Binding view state to service cache data — automatic synchronization without plumbing.
A DataProvider owns a view’s state and keeps it synchronized with service cache
data through declarative bindings.
Why a DataProvider
Without one, you wire data into views by hand: call a service, setState(),
repeat on every change. A DataProvider replaces that with a declaration: “this
view’s todos state key is the Todo entities matching this filter, kept
up to date automatically.”
Defining one
A DataProvider takes the view it serves, an initial state, an optional
schema, and a binding map — one rule per state key:
import { DataProvider } from "/lib/altseven/dist/a7.js";
import { Todo } from "../entity/todo.js";
export class TodoListDP extends DataProvider {
constructor( props ) {
props.binding = {
todos: {
entityClass: Todo,
func: todoService.refreshActiveTodos, // how to (re)load the data
renderOn: [ "create", "delete" ] // which cache actions re-render
},
selected: {
entityClass: Todo,
id: null // bound to a single entity; id fixed at runtime
}
};
props.schema = {
todos: { type: "map", entityClass: Todo },
selected: { type: "object", entityClass: Todo },
filterText: { type: "string" }
};
super( props );
}
}
Binding rule properties:
| Property |
Meaning |
entityClass |
The entity type this key holds — used to find the matching service |
func |
A refresh function (usually on the service) that returns the entities to bind |
id |
Bind to a single entity by id instead of a collection |
filter |
Client-side filter applied to bound data, e.g. { done: [ "=", false ] } |
sort |
Sort applied to bound data, e.g. { created: "desc" } |
renderOn |
Only re-render on these cache actions: create, update, delete |
dependencies |
Re-run the binding when these state keys change (see below) |
Registration — two steps
A DataProvider must be registered with both the application and the view:
const dp = new TodoListDP( { view: todosView } );
myApp.dataproviders.register( dp ); // wires bindings to services
todosView.registerDataProvider( dp ); // view state now flows through the DP
Once registered, todosView.setState() / getState() delegate to the
DataProvider, and cache changes push new data into view state automatically —
the view repaints through the normal stateChanged → mustRender path.
Collection binding
With a func (or the service cache as a whole), the DataProvider listens to
the service’s cacheChanged event, re-resolves the bound data, applies
filter/sort, and writes the result into view state. renderOn limits which
actions trigger this — e.g. a list that doesn’t need to repaint when an
existing item is merely updated can declare renderOn: [ "create", "delete" ].
Entity-specific binding
With an id, the binding tracks a single entity: when that entity changes, the
view’s state key is set to the new entity; when it is deleted, the key is set
to null. This is the normal shape for a detail view.
For an entity whose id is not known until runtime, declare the binding with
id: null. The first matching entityChanged event sets the state (since
9.1.3 an id-less object binding correctly receives the event’s entity rather
than the whole cache map).
Dependencies
dependencies re-runs a binding when related state changes — either in the
same view ("filterText") or another view ("toolbar.selectedUserID"):
props.binding = {
todos: {
entityClass: Todo,
func: todoService.refreshByFilter,
dependencies: [ "filterText", "toolbar.selectedUserID" ]
}
};
When filterText changes in this view (or selectedUserID changes in the
toolbar view), the todos binding re-resolves — the func receives the
current DP state and can use those values as its query parameters.
EntityMap relations
For master/detail loads (a page of items plus their parents), declare a
relation in the schema and load it explicitly:
props.schema = {
todos: {
type: "entityMap",
service: "todos", // service id
fetchMethod: "todo.byUser", // returns an array of ids (or { ids: [...] })
defaultCriteria: { userID: 7, limit: 20 }
}
};
// fetch the id list, then readMany() the entities (cache-aware)
await dp.loadRelation( "todos", { userID: 7 } );
// paginate: merges with the stored criteria by default
await dp.refresh( "todos", { limit: 40 } );
await dp.refresh( "todos", { limit: 20 }, { reload: true } ); // replace criteria
dp.getRelationCriteria( "todos" ); // the currently stored criteria
dp.clearRelation( "todos" ); // empty the Map and forget the criteria
loadRelation fires relationLoaded, refresh fires relationRefreshed,
clearRelation fires relationCleared.
When to use what
- Plain view state — UI-only values (drafts, tab selection). No DataProvider needed.
- DataProvider with bindings — view state that mirrors cached entities.
- Model bindings (
data-bind) — simple two-way field binding for form
inputs backed by the application model.