API Reference
classes
Ad4mmodel

@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 through option
  • 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

Constructors

constructor

new Ad4mModel(perspective, baseExpression?, source?)

Constructs a new model instance.

Parameters

NameTypeDescription
perspectivePerspectiveProxyThe perspective where this model will be stored
baseExpression?stringOptional unique identifier for this instance
source?stringOptional 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:319

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:328


perspective

Protected get perspective(): PerspectiveProxy

Protected getter for the perspective. Allows subclasses to access the perspective while keeping it private from external code.

Returns

PerspectiveProxy

Defined in

model/Ad4mModel.ts:336

Methods

delete

delete(): Promise<void>

Deletes the model instance from the perspective.

Returns

Promise<void>

Throws

Will throw if removal fails

Example

const recipe = await Recipe.findAll(perspective)[0];
await recipe.delete();

Defined in

model/Ad4mModel.ts:766


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:749


getData

Private getData(): Promise<Ad4mModel>

Returns

Promise<Ad4mModel>

Defined in

model/Ad4mModel.ts:370


save

save(): Promise<void>

Saves the model instance to the perspective. Creates a new instance with the base expression and links it to the source.

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();

Defined in

model/Ad4mModel.ts:682


setCollectionAdder

Private setCollectionAdder(key, value): Promise<void>

Parameters

NameType
keystring
valueany

Returns

Promise<void>

Defined in

model/Ad4mModel.ts:624


setCollectionRemover

Private setCollectionRemover(key, value): Promise<void>

Parameters

NameType
keystring
valueany

Returns

Promise<void>

Defined in

model/Ad4mModel.ts:646


setCollectionSetter

Private setCollectionSetter(key, value): Promise<void>

Parameters

NameType
keystring
valueany

Returns

Promise<void>

Defined in

model/Ad4mModel.ts:601


setProperty

Private setProperty(key, value): Promise<void>

Parameters

NameType
keystring
valueany

Returns

Promise<void>

Defined in

model/Ad4mModel.ts:580


update

update(): Promise<void>

Updates the model instance's properties and collections.

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();

Defined in

model/Ad4mModel.ts:705


assignValuesToInstance

Static assignValuesToInstance(perspective, instance, values): Promise<void>

Parameters

NameType
perspectivePerspectiveProxy
instanceAd4mModel
valuesValueTuple[]

Returns

Promise<void>

Defined in

model/Ad4mModel.ts:340


count

Static count(perspective, query?): Promise<any>

Gets a count of all matching instances.

Parameters

NameTypeDescription
perspectivePerspectiveProxyThe perspective to search in
queryQueryOptional 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:574


countQueryToProlog

Static countQueryToProlog(perspective, query?, modelClassName?): Promise<string>

Parameters

NameType
perspectivePerspectiveProxy
queryQuery
modelClassName?string

Returns

Promise<string>

Defined in

model/Ad4mModel.ts:541


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

NameType
Textends Ad4mModel<T>

Parameters

NameTypeDescription
thistypeof Ad4mModel & (...args: any[]) => T-
perspectivePerspectiveProxyThe perspective to search in
queryQueryOptional 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:473


findAllAndCount

Static findAllAndCount<T>(this, perspective, query?): Promise<ResultsWithTotalCount<T>>

Gets all instances with count of total matches without offset & limit applied.

Type parameters

NameType
Textends Ad4mModel<T>

Parameters

NameTypeDescription
thistypeof Ad4mModel & (...args: any[]) => T-
perspectivePerspectiveProxyThe perspective to search in
queryQueryOptional 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:500


getClassName

Static getClassName(perspective): Promise<string>

Parameters

NameType
perspectivePerspectiveProxy

Returns

Promise<string>

Defined in

model/Ad4mModel.ts:283


instancesFromPrologResult

Static instancesFromPrologResult<T>(this, perspective, query, result): Promise<ResultsWithTotalCount<T>>

Type parameters

NameType
Textends Ad4mModel<T>

Parameters

NameType
thistypeof Ad4mModel & (...args: any[]) => T
perspectivePerspectiveProxy
queryQuery
resultAllInstancesResult

Returns

Promise<ResultsWithTotalCount<T>>

Defined in

model/Ad4mModel.ts:416


paginate

Static paginate<T>(this, perspective, pageSize, pageNumber, query?): Promise<PaginationResult<T>>

Helper function for pagination with explicit page size and number.

Type parameters

NameType
Textends Ad4mModel<T>

Parameters

NameTypeDescription
thistypeof Ad4mModel & (...args: any[]) => T-
perspectivePerspectiveProxyThe perspective to search in
pageSizenumberNumber of items per page
pageNumbernumberWhich page to retrieve (1-based)
query?QueryOptional 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:527


query

Static query<T>(this, perspective, query?): ModelQueryBuilder<T>

Creates a query builder for fluent query construction.

Type parameters

NameType
Textends Ad4mModel<T>

Parameters

NameTypeDescription
thistypeof Ad4mModel & (...args: any[]) => T-
perspectivePerspectiveProxyThe perspective to query
query?QueryOptional initial query parameters

Returns

ModelQueryBuilder<T>

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:793


queryToProlog

Static queryToProlog(perspective, query, modelClassName?): Promise<string>

Parameters

NameType
perspectivePerspectiveProxy
queryQuery
modelClassName?string

Returns

Promise<string>

Defined in

model/Ad4mModel.ts:390