Skip to content

Derived Properties

In Joist, Derived Properties are values that can be calculated/derived from other data within your domain model, for example:

  • Deriving an Author’s fullName from their firstName and lastName
  • Deriving an Author’s numberOfBooks from their books collection

Derived Properties are not stored in the database, but are calculated on-the-fly when accessed. Joist also supports Reactive Fields, which are similar to Derived Properties but are stored in the database.

hasReactiveAsyncMethod is a flavor of hasAsyncMethod that takes a reactive hint instead of a load hint, and allows applications to pass an onInvalidate callback that is called whenever these upstream dependencies change.

This allows the method’s implementation to cache expensive operations, typically on the entity’s transientFields, and know when to reset the cache because an in-progress mutation has changed the data.

For example, suppose an author has an expensive book-search method that ranks book titles for a query using each book’s title and tags. Caching is particularly useful if rankedBookTitles is called many times in a loop by other business logic. The application caches the ranked titles by query:

class Author extends AuthorCodegen {
readonly transientFields = {
rankedBookTitles: new Map<string, string[]>(),
};
readonly rankedBookTitles: AsyncMethod<Author, [string], string[]> = hasReactiveAsyncMethod(
{ books: { title: {}, tags: "name" } },
(author, query) => {
const cache = author.transientFields.rankedBookTitles;
if (!cache.has(query)) {
cache.set(query, rankBookTitles(author.books.get, query));
}
return cache.get(query)!;
},
{
onInvalidate: (author) => author.transientFields.rankedBookTitles.clear(),
},
);
}

Here, rankBookTitles is the application’s ranking function. Adding or removing a book, editing a title, changing a book’s tags, or renaming a tag (i.e. changing any data in the reactive hint) clears the cached results.

hasReactiveField accepts the same optional third argument for application-owned intermediate caches:

readonly searchIndex = hasReactiveField(
{ books: "title" },
(author) => buildSearchIndex(author.books.get, author.transientFields.searchTokens),
{ onInvalidate: (author) => author.transientFields.searchTokens.clear() },
);

Synchronous properties calculate their value from other values immediately available on the same entity; because of this, they can always be accessed, and are just getters:

class Author {
get fullName(): string {
return this.firstName + (this.lastName ? ` ${this.lastName}` : "");
}
}

Asynchronous Properties calculate their value from the entity and other related child/parent entities.

For example, to implement an Author’s numberOfBooks property that requires counting the Author’s books collection, use hasProperty with a populate hint stating it depends on the books collection:

export class Author {
readonly numberOfBooks: Property<Author, number> = hasProperty(
// Declare the relations to load
"books",
// Only `a.books` will be marked as loaded
(a) => { a.books.get.length }
);
}

Because this calculation fundamentally requires having the books loaded, it is marked as async and requires loading with a populate hint to access:

// Load an author without any populate hints
const a1 = await em.load(Author, "a:1");
// `.get` is not available, so `numberOfBooks` requires an await
const num1 = await a1.numberOfBooks.load();
// Load the author with `numberOfBooks` populated
const a2 = await em.load(Author, "a:1", "numberOfBooks");
// `.get` is now available and can be called immediately
const num2 = a2.numberOfBooks.get;

Like populate hints, hasPropertys can used nested hints:

export class Author {
readonly latestComments: Property<Author, Comment[]> = hasProperty(
// Pass a nested load hint
{ publisher: "comments", comments: {} },
// `a` will have the deep relations loaded
(a) => [...(a.publisher.get?.comments.get ?? []), ...a.comments.get],
);
}

If you want to access derived properties, like the fullName getter in the first example, from Reactive Fields, Joist needs to know which specific fields fullName depends.

You can do this by using hasReactiveGetter, which declares the business logic’s dependencies:

class Author {
readonly fullName: ReactiveGetter<Author, string> = hasReactiveGetter(
"fullName",
// Declare the other fields we depend on
["firstName", "lastName"],
// `a` will be limited to using only `firstName` and `lastName`
a => a.firstName + (a.lastName ? ` ${a.lastName}` : ""),
);
}

Now, even though Author.fullName itself is not stored in the database, if any other reactive values want to depend on Author.fullName, Joist will know when the fullName value becomes dirty, and those downstream values should be recalculated.

ReactiveGetters are limited to depending on fields directly on the entity itself, which means they can be accessed at any time, without being loaded:

// Load the author, without any populate hint
const a = await em.load(Author, "a:1");
// We can still call the fullName logic
console.log(a.fullName.get);

Similar to Reactive Getters, if you have a Reactive Field that wants to depend on an Async Property, you need to declare the property’s field-level dependencies by using hasReactiveProperty:

export class Author {
readonly numberOfBooks: Property<Author, number> =
hasReactiveProperty(
// Now this is a field-level reactive hint
{ books: "title" },
// `a` can only access fields declared by the hint
(a) => a.books.get.filter((b) => b.title !== undefined).length,
);
}

This is similar to regular hasPropertys, except that the hint declares the specific fields that the lambda uses, and the lambda will be restricted from using any field not declared in the hint.