Services
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).
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.