src/app/core/entity/model/embedded-entity.ts

Description

Stand-in for a single entry of an embedded field (e.g. one row of a schema-embed-array field) while it is edited, so that the entry goes through the standard entity form logic like a record: its inner fields get the same validators, edit components and handling of empty values as top-level fields.

It only exists while editing; the entry is stored as a plain object in its record (see toEntryValue). It is never saved on its own (EntityMapperService refuses to), and permissions are checked on the field of the record holding it (see EntityAbility).

Create it with createEmbeddedEntity.

Extends

Entity

Relationships

Used by

No results matching.

Depends on

Index

Properties
Methods
Accessors

Properties

_embeddedIn
Type : EmbeddedEntityContext

Where this entry belongs. Set after construction, because copy() creates new instances only from an id.

Static Readonly ENTITY_TYPE
Type : string
Default value : "EmbeddedEntity"
Inherited from Entity
Static Optional _isCustomizedType
todo: This property is no longer used and will be removed in future versions.
Type : boolean
Inherited from Entity

True if this type's schema has been customized dynamically from the config.

_rev
Type : string
Decorators :
@DatabaseField({anonymize: 'retain', isInternalField: true})
Inherited from Entity

internal database doc revision, used to detect conflicts by PouchDB/CouchDB

anonymized
Type : boolean
Decorators :
@DatabaseField({anonymize: 'retain', isInternalField: true})
Inherited from Entity

Whether this entity has been anonymized and therefore cannot be re-activated.

Static color
Type : string | ColorMapping[]
Inherited from Entity

color used for to highlight this entity type across the app.

Can be either:

  • A simple string (hex color code) for a single color
  • An array of ColorMapping objects for conditional colors based on entity properties
created
Type : UpdateMetadata
Decorators :
@DatabaseField({anonymize: 'retain', isInternalField: true})
Inherited from Entity
Static DATABASE
Type : string
Default value : "app"
Inherited from Entity

The database where these entities are stored.

Static Readonly DATABASE_REMOTE_ONLY
Type : boolean
Default value : false
Inherited from Entity

Whether DATABASE exists on the server only and must never be replicated to the device.

Such a database is opened as a remote handle, is not watched for changes, and is left untouched when local databases are reset or destroyed. Use it for data that grows without bound or that the client must not keep a copy of.

Static Optional enableUserAccounts
Type : boolean
Inherited from Entity

Whether to enable user account creation for this entity type. When true, the UI will allow management of user accounts associated with this entity.

Static hasPII
Type : boolean
Default value : false
Inherited from Entity

whether this entity type can contain "personally identifiable information" (PII) and therefore should follow strict data protection requirements and offer a function to anonymize records.

Static icon
Type : IconName
Inherited from Entity

icon id used for this entity

inactive
Type : boolean
Decorators :
@DatabaseField({anonymize: 'retain', isInternalField: true})
Inherited from Entity
Static Optional isInternalEntity
Type : boolean
Inherited from Entity

if this entity type is an internal entity, i.e. only defined in the code base to store internal system data and not visible to the user for customization.

Static label
Type : string
Inherited from Entity

human-readable name/label of the entity in the UI

Static schema
Type : EntitySchema
Inherited from Entity

EntitySchema defining property transformations from/to the database. This is auto-generated from the property annotations @DatabaseField().

see /additional-documentation/how-to-guides/create-a-new-entity-type.html

Static Optional toBlockDetailsAttributes
Type : EntityBlockConfig
Inherited from Entity

Defining which attributes will be displayed in a tooltip on hover when the record is displayed as an entity-block.

Static toStringAttributes
Type : []
Default value : ["entityId"]
Inherited from Entity

Defining which attribute values of an entity should be shown in the .toString() method.

The default is the ID of the entity (entityId). This can be overwritten in subclasses or through the config.

updated
Type : UpdateMetadata
Decorators :
@DatabaseField({anonymize: 'retain', isInternalField: true})
Inherited from Entity

Methods

getRoot
getRoot()

The saved record holding this entry and the record's field holding it, walking up through entries nested in other embedded entries.

Returns : literal type | undefined
toEntryValue
toEntryValue(base: Record)

The entry as it is stored in the record's field: a plain object of its inner fields, without the properties of this stand-in. Inner fields without a value are left out.

Example :
        (e.g. of inner fields removed from the config) are kept
Parameters :
Name Type Optional Default value Description
base Record<string, any> No {}

the entry as it was before editing, whose properties that are no inner fields (e.g. of inner fields removed from the config) are kept

Returns : Record<string, any>
assertValid
assertValid()
Inherited from Entity

Checks if the entity is valid and if the check fails, throws an error explaining the failed check.

Returns : void
Public copy
copy(newId: string | boolean)
Inherited from Entity

Deep copy of the entity. The resulting entity will be of the same type as this (taking into account subclassing). All schema field values that are objects or arrays are deep-cloned to avoid shared mutable state between original and copy.

Parameters :
Name Type Optional Default value Description
newId string | boolean No false

if true, a new entityId will be generated; if a string, that value is used as new entityId

Returns : unknown
Static createPrefixedId
createPrefixedId(type: string, id: string)
Inherited from Entity

Create a prefixed id by adding the type prefix if it isn't already part of the given id.

Parameters :
Name Type Optional Description
type string No

The type prefix to be added.

id string No

The id to be extended with a prefix.

Returns : string
Static extractEntityIdFromId
extractEntityIdFromId(id: string)
Inherited from Entity

Extract entityId without prefix.

Parameters :
Name Type Optional Description
id string No

An entity's id including prefix.

Returns : string
Static extractTypeFromId
extractTypeFromId(id: string)
Inherited from Entity

Extract the ENTITY_TYPE from an id.

Parameters :
Name Type Optional Description
id string No

An entity's id including prefix.

Returns : string
Public getColor
getColor()
Inherited from Entity

Used by some generic UI components to set the color for the entity instance. Override this method as needed.

Returns : string
Static getColorWithConditions
getColorWithConditions(entity: Entity)
Inherited from Entity

Static method to evaluate conditional colors for an entity based on ColorMapping configuration.

Parameters :
Name Type Optional
entity Entity No
Returns : string
getConstructor
getConstructor()
Inherited from Entity

Get the class (Entity or the actual subclass of the instance) to call static methods on the correct class considering inheritance

Public getId
getId(withoutPrefix: unknown)
Inherited from Entity

Returns the id of this entity.

Note that an id is final and can't be changed after the object has been instantiated, hence there is no setId() method.

Parameters :
Name Type Optional Default value
withoutPrefix unknown No false
Returns : string

the unique id of this entity

getSchema
getSchema()
Inherited from Entity

Get the entity schema of this class

Returns : EntitySchema
Public getType
getType()
Inherited from Entity

Returns the type which is used to categorize this entity in the database.

Important: Do not overwrite this method! Types are handled internally.

Returns : string

the entity's type (which is the class name).

Public getWarningLevel
getWarningLevel()
Inherited from Entity

Override getWarningLevel() to define when the entity is in a critical condition and should be color-coded and highlighted in generic components of the UI.

Returns : WarningLevel

Accessors

isNew
getisNew()
import { Entity } from "./entity";
import { EntitySchema } from "../schema/entity-schema";

/**
 * Where an {@link EmbeddedEntity} belongs.
 */
export interface EmbeddedEntityContext {
  /**
   * The record holding the entry, which is saved instead of the entry
   * (itself an EmbeddedEntity if the entry is nested in another embedded entry).
   * Not set if the entry is edited without a record, e.g. for a default value in the Admin UI.
   */
  record?: Entity;

  /** id of the record's field holding the entry */
  field: string;

  /** whether the entry already exists in the record (edited instead of added) */
  existing: boolean;
}

/**
 * Stand-in for a single entry of an embedded field (e.g. one row of a `schema-embed-array` field)
 * while it is edited, so that the entry goes through the standard entity form logic like a record:
 * its inner fields get the same validators, edit components and handling of empty values as top-level fields.
 *
 * It only exists while editing; the entry is stored as a plain object in its record (see {@link toEntryValue}).
 * It is never saved on its own (`EntityMapperService` refuses to), and permissions are checked
 * on the field of the record holding it (see `EntityAbility`).
 *
 * Create it with {@link createEmbeddedEntity}.
 */
export abstract class EmbeddedEntity extends Entity {
  static override readonly ENTITY_TYPE = "EmbeddedEntity";

  /**
   * Where this entry belongs.
   * Set after construction, because `copy()` creates new instances only from an id.
   */
  _embeddedIn: EmbeddedEntityContext;

  override get isNew(): boolean {
    return !this._embeddedIn.existing;
  }

  /**
   * The saved record holding this entry and the record's field holding it,
   * walking up through entries nested in other embedded entries.
   */
  getRoot(): { record: Entity; field: string } | undefined {
    let context = this._embeddedIn;
    while (context.record instanceof EmbeddedEntity) {
      context = context.record._embeddedIn;
    }
    return context.record
      ? { record: context.record, field: context.field }
      : undefined;
  }

  /**
   * The entry as it is stored in the record's field: a plain object of its inner fields,
   * without the properties of this stand-in. Inner fields without a value are left out.
   *
   * @param base the entry as it was before editing, whose properties that are no inner fields
   *             (e.g. of inner fields removed from the config) are kept
   */
  toEntryValue(base: Record<string, any> = {}): Record<string, any> {
    const entry = { ...base };
    for (const key of this.getSchema().keys()) {
      if (this[key] === undefined) {
        delete entry[key];
      } else {
        entry[key] = this[key];
      }
    }
    return entry;
  }
}

/**
 * Wrap an entry of an embedded field as {@link EmbeddedEntity}, to edit it like a record.
 *
 * @param schema the inner fields of the entry (see `getEmbeddedSchema`)
 * @param context where the entry belongs
 * @param entry the current values of the entry (not changed); none for a new entry
 */
export function createEmbeddedEntity(
  schema: EntitySchema,
  context: EmbeddedEntityContext,
  entry?: Record<string, any>,
): EmbeddedEntity {
  class EmbeddedEntry extends EmbeddedEntity {
    static override readonly schema = schema;
  }

  const embeddedEntity = new EmbeddedEntry();
  Object.assign(embeddedEntity, entry);
  embeddedEntity._embeddedIn = context;
  return embeddedEntity;
}

/**
 * The record that is actually saved for the given entity:
 * the record holding it, if it is an {@link EmbeddedEntity}, otherwise the entity itself.
 */
export function getSavedRecord(entity: Entity): Entity {
  return entity instanceof EmbeddedEntity
    ? (entity.getRoot()?.record ?? entity)
    : entity;
}

results matching ""

    No results matching ""