@coasys/ad4m / Exports / Ad4mModel
Class: Ad4mModel
Base class for defining data models in AD4M.
Description
Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives. Each model instance is represented as a subgraph in the perspective, with properties and collections mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter instances based on their properties and relationships.
Key concepts:
- Each model instance has a unique base expression that serves as its identifier
- Properties are stored as links with predicates defined by the
throughoption - Collections represent one-to-many relationships as sets of links
- Queries are translated to Prolog for efficient graph pattern matching
- Changes are tracked through the perspective's subscription system
Example
// Define a recipe model
@ModelOptions({ name: "Recipe" })
class Recipe extends Ad4mModel {
// Required property with literal value
@Property({
through: "recipe://name",
resolveLanguage: "literal"
})
name: string = "";
// Optional property with custom initial value
@Optional({
through: "recipe://status",
initial: "recipe://draft"
})
status: string = "";
// Read-only computed property
@ReadOnly({
through: "recipe://rating",
getter: `
findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
sum_list(Ratings, Sum),
length(Ratings, Count),
Value is Sum / Count
`
})
averageRating: number = 0;
// Collection of ingredients
@Collection({ through: "recipe://ingredient" })
ingredients: string[] = [];
// Collection of comments that are instances of another model
@Collection({
through: "recipe://comment",
where: { isInstance: Comment }
})
comments: Comment[] = [];
}
// Create and save a new recipe
const recipe = new Recipe(perspective);
recipe.name = "Chocolate Cake";
recipe.ingredients = ["flour", "sugar", "cocoa"];
await recipe.save();
// Query recipes in different ways
// Get all recipes
const allRecipes = await Recipe.findAll(perspective);
// Find recipes with specific criteria
const desserts = await Recipe.findAll(perspective, {
where: {
status: "recipe://published",
averageRating: { gt: 4 }
},
order: { name: "ASC" },
limit: 10
});
// Use the fluent query builder
const popularRecipes = await Recipe.query(perspective)
.where({ averageRating: { gt: 4.5 } })
.order({ averageRating: "DESC" })
.limit(5)
.get();
// Subscribe to real-time updates
await Recipe.query(perspective)
.where({ status: "recipe://cooking" })
.subscribe(recipes => {
console.log("Currently being cooked:", recipes);
});
// Paginate results
const { results, totalCount, pageNumber } = await Recipe.query(perspective)
.where({ status: "recipe://published" })
.paginate(10, 1);Table of contents
Constructors
Properties
Accessors
Methods
- cleanCopy
- delete
- get
- getData
- innerUpdate
- save
- setCollectionAdder
- setCollectionRemover
- setCollectionSetter
- setProperty
- update
- assignValuesToInstance
- count
- countQueryToProlog
- findAll
- findAllAndCount
- getClassName
- instancesFromPrologResult
- paginate
- query
- queryToProlog
Constructors
constructor
• new Ad4mModel(perspective, baseExpression?, source?)
Constructs a new model instance.
Parameters
| Name | Type | Description |
|---|---|---|
perspective | PerspectiveProxy | The perspective where this model will be stored |
baseExpression? | string | Optional unique identifier for this instance |
source? | string | Optional source expression this instance is linked to |
Example
// Create a new recipe with auto-generated base expression
const recipe = new Recipe(perspective);
// Create with specific base expression
const recipe = new Recipe(perspective, "recipe://chocolate-cake");
// Create with source link
const recipe = new Recipe(perspective, undefined, "cookbook://desserts");Defined in
model/Ad4mModel.ts:327
Properties
#baseExpression
• Private #baseExpression: string
Defined in
model/Ad4mModel.ts:274
#perspective
• Private #perspective: PerspectiveProxy
Defined in
model/Ad4mModel.ts:277
#source
• Private #source: string
Defined in
model/Ad4mModel.ts:276
#subjectClassName
• Private #subjectClassName: string
Defined in
model/Ad4mModel.ts:275
author
• author: string
Defined in
model/Ad4mModel.ts:278
timestamp
• timestamp: string
Defined in
model/Ad4mModel.ts:279
classNamesByClass
▪ Static Private classNamesByClass: WeakMap<typeof Ad4mModel, { [perspectiveId: string]: string; }>
Defined in
model/Ad4mModel.ts:281
Accessors
baseExpression
• get baseExpression(): string
Gets the base expression of the subject.
Returns
string
Defined in
model/Ad4mModel.ts:336
perspective
• Protected get perspective(): PerspectiveProxy
Protected getter for the perspective. Allows subclasses to access the perspective while keeping it private from external code.
Returns
Defined in
model/Ad4mModel.ts:344
Methods
cleanCopy
▸ Private cleanCopy(): Object
Returns
Object
Defined in
model/Ad4mModel.ts:765
delete
▸ delete(batchId?): Promise<void>
Deletes the model instance from the perspective.
Parameters
| Name | Type | Description |
|---|---|---|
batchId? | string | Optional batch ID for batch operations |
Returns
Promise<void>
Throws
Will throw if removal fails
Example
const recipe = await Recipe.findAll(perspective)[0];
await recipe.delete();
// Or with batch operations:
const batchId = await perspective.createBatch();
await recipe.delete(batchId);
await perspective.commitBatch(batchId);Defined in
model/Ad4mModel.ts:868
get
▸ get(): Promise<Ad4mModel>
Gets the model instance with all properties and collections populated.
Returns
Promise<Ad4mModel>
The populated model instance
Throws
Will throw if data retrieval fails
Example
const recipe = new Recipe(perspective, existingId);
await recipe.get();
console.log(recipe.name, recipe.ingredients);Defined in
model/Ad4mModel.ts:845
getData
▸ Private getData(): Promise<Ad4mModel>
Returns
Promise<Ad4mModel>
Defined in
model/Ad4mModel.ts:400
innerUpdate
▸ Private innerUpdate(setProperties?, batchId?): Promise<void>
Parameters
| Name | Type | Default value |
|---|---|---|
setProperties | boolean | true |
batchId? | string | undefined |
Returns
Promise<void>
Defined in
model/Ad4mModel.ts:776
save
▸ save(batchId?): Promise<void>
Saves the model instance to the perspective. Creates a new instance with the base expression and links it to the source.
Parameters
| Name | Type | Description |
|---|---|---|
batchId? | string | Optional batch ID for batch operations |
Returns
Promise<void>
Throws
Will throw if instance creation, linking, or updating fails
Example
const recipe = new Recipe(perspective);
recipe.name = "Spaghetti";
recipe.ingredients = ["pasta", "tomato sauce"];
await recipe.save();
// Or with batch operations:
const batchId = await perspective.createBatch();
await recipe.save(batchId);
await perspective.commitBatch(batchId);Defined in
model/Ad4mModel.ts:719
setCollectionAdder
▸ Private setCollectionAdder(key, value, batchId?): Promise<void>
Parameters
| Name | Type |
|---|---|
key | string |
value | any |
batchId? | string |
Returns
Promise<void>
Defined in
model/Ad4mModel.ts:655
setCollectionRemover
▸ Private setCollectionRemover(key, value, batchId?): Promise<void>
Parameters
| Name | Type |
|---|---|
key | string |
value | any |
batchId? | string |
Returns
Promise<void>
Defined in
model/Ad4mModel.ts:677
setCollectionSetter
▸ Private setCollectionSetter(key, value, batchId?): Promise<void>
Parameters
| Name | Type |
|---|---|
key | string |
value | any |
batchId? | string |
Returns
Promise<void>
Defined in
model/Ad4mModel.ts:631
setProperty
▸ Private setProperty(key, value, batchId?): Promise<void>
Parameters
| Name | Type |
|---|---|
key | string |
value | any |
batchId? | string |
Returns
Promise<void>
Defined in
model/Ad4mModel.ts:610
update
▸ update(batchId?): Promise<void>
Updates the model instance's properties and collections.
Parameters
| Name | Type | Description |
|---|---|---|
batchId? | string | Optional batch ID for batch operations |
Returns
Promise<void>
Throws
Will throw if property setting or collection updates fail
Example
const recipe = await Recipe.findAll(perspective)[0];
recipe.rating = 5;
recipe.ingredients.push("garlic");
await recipe.update();
// Or with batch operations:
const batchId = await perspective.createBatch();
await recipe.update(batchId);
await perspective.commitBatch(batchId);Defined in
model/Ad4mModel.ts:827
assignValuesToInstance
▸ Static assignValuesToInstance(perspective, instance, values): Promise<void>
Parameters
| Name | Type |
|---|---|
perspective | PerspectiveProxy |
instance | Ad4mModel |
values | ValueTuple[] |
Returns
Promise<void>
Defined in
model/Ad4mModel.ts:348
count
▸ Static count(perspective, query?): Promise<any>
Gets a count of all matching instances.
Parameters
| Name | Type | Description |
|---|---|---|
perspective | PerspectiveProxy | The perspective to search in |
query | Query | Optional query parameters to filter results |
Returns
Promise<any>
Total count of matching entities
Example
const totalRecipes = await Recipe.count(perspective);
const activeRecipes = await Recipe.count(perspective, {
where: { status: "active" }
});Defined in
model/Ad4mModel.ts:604
countQueryToProlog
▸ Static countQueryToProlog(perspective, query?, modelClassName?): Promise<string>
Parameters
| Name | Type |
|---|---|
perspective | PerspectiveProxy |
query | Query |
modelClassName? | string |
Returns
Promise<string>
Defined in
model/Ad4mModel.ts:571
findAll
▸ Static findAll<T>(this, perspective, query?): Promise<T[]>
Gets all instances of the model in the perspective that match the query params.
Type parameters
| Name | Type |
|---|---|
T | extends Ad4mModel<T> |
Parameters
| Name | Type | Description |
|---|---|---|
this | typeof Ad4mModel & (...args: any[]) => T | - |
perspective | PerspectiveProxy | The perspective to search in |
query | Query | Optional query parameters to filter results |
Returns
Promise<T[]>
Array of matching models
Example
// Get all recipes
const allRecipes = await Recipe.findAll(perspective);
// Get recipes with specific criteria
const recipes = await Recipe.findAll(perspective, {
where: {
name: "Pasta",
rating: { gt: 4 }
},
order: { createdAt: "DESC" },
limit: 10
});Defined in
model/Ad4mModel.ts:503
findAllAndCount
▸ Static findAllAndCount<T>(this, perspective, query?): Promise<ResultsWithTotalCount<T>>
Gets all instances with count of total matches without offset & limit applied.
Type parameters
| Name | Type |
|---|---|
T | extends Ad4mModel<T> |
Parameters
| Name | Type | Description |
|---|---|---|
this | typeof Ad4mModel & (...args: any[]) => T | - |
perspective | PerspectiveProxy | The perspective to search in |
query | Query | Optional query parameters to filter results |
Returns
Promise<ResultsWithTotalCount<T>>
Object containing results array and total count
Example
const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
where: { category: "Dessert" },
limit: 10
});
console.log(`Showing 10 of ${totalCount} dessert recipes`);Defined in
model/Ad4mModel.ts:530
getClassName
▸ Static getClassName(perspective): Promise<string>
Parameters
| Name | Type |
|---|---|
perspective | PerspectiveProxy |
Returns
Promise<string>
Defined in
model/Ad4mModel.ts:283
instancesFromPrologResult
▸ Static instancesFromPrologResult<T>(this, perspective, query, result): Promise<ResultsWithTotalCount<T>>
Type parameters
| Name | Type |
|---|---|
T | extends Ad4mModel<T> |
Parameters
| Name | Type |
|---|---|
this | typeof Ad4mModel & (...args: any[]) => T |
perspective | PerspectiveProxy |
query | Query |
result | AllInstancesResult |
Returns
Promise<ResultsWithTotalCount<T>>
Defined in
model/Ad4mModel.ts:446
paginate
▸ Static paginate<T>(this, perspective, pageSize, pageNumber, query?): Promise<PaginationResult<T>>
Helper function for pagination with explicit page size and number.
Type parameters
| Name | Type |
|---|---|
T | extends Ad4mModel<T> |
Parameters
| Name | Type | Description |
|---|---|---|
this | typeof Ad4mModel & (...args: any[]) => T | - |
perspective | PerspectiveProxy | The perspective to search in |
pageSize | number | Number of items per page |
pageNumber | number | Which page to retrieve (1-based) |
query? | Query | Optional additional query parameters |
Returns
Promise<PaginationResult<T>>
Paginated results with metadata
Example
const page = await Recipe.paginate(perspective, 10, 1, {
where: { category: "Main Course" }
});
console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);Defined in
model/Ad4mModel.ts:557
query
▸ Static query<T>(this, perspective, query?): ModelQueryBuilder<T>
Creates a query builder for fluent query construction.
Type parameters
| Name | Type |
|---|---|
T | extends Ad4mModel<T> |
Parameters
| Name | Type | Description |
|---|---|---|
this | typeof Ad4mModel & (...args: any[]) => T | - |
perspective | PerspectiveProxy | The perspective to query |
query? | Query | Optional initial query parameters |
Returns
A new query builder instance
Example
const recipes = await Recipe.query(perspective)
.where({ category: "Dessert" })
.order({ rating: "DESC" })
.limit(5)
.run();
// With real-time updates
await Recipe.query(perspective)
.where({ status: "cooking" })
.subscribe(recipes => {
console.log("Currently cooking:", recipes);
});Defined in
model/Ad4mModel.ts:895
queryToProlog
▸ Static queryToProlog(perspective, query, modelClassName?): Promise<string>
Parameters
| Name | Type |
|---|---|
perspective | PerspectiveProxy |
query | Query |
modelClassName? | string |
Returns
Promise<string>
Defined in
model/Ad4mModel.ts:420