Class used to access a wide array of MemberJunction metadata, to instantiate derived classes of BaseEntity for record access and manipulation and more. This class uses a provider model where different providers transparently plug-in to implement the functionality needed based on where the code is running. The provider in use is generally not of any importance to users of the class and code can be written indepdenent of tier/provider.

Constructors

Properties

_globalProviderKey: string = 'MJ_MetadataProvider'

Accessors

  • get CurrentUser(): UserInfo
  • Returns the current user, if known. In some execution environments, mainly on server tiers like in a node.js environment, there won't be a "current user" known to Metadata since the Metadata instance is shared across all requests. In this situation you should determine the current user from the server context where you get the user payload and find the user from the UserCache.

    Returns UserInfo

  • get LocalStorageProvider(): ILocalStorageProvider
  • Returns the local storage provider. This is used to store metadata locally on the client.

    Returns ILocalStorageProvider

    • the local storage provider

    Remarks

    • Use this for storing any type of data on the client. The Provider implements the storage mechanism which is persistent whenever possible, but in some cases purely in memory if local persistence is not available. Keep in mind that you must ensure that keys are unique so prefix all of your keys with something unique to avoid collisions.

Methods

  • Stores a dataset in the local cache. If itemFilters are provided, the combination of datasetName and the filters are used to build a key and determine a match in the cache

    Parameters

    Returns Promise<void>

  • If the specified datasetName is cached, this method will clear the cache. If itemFilters are provided, the combination of datasetName and the filters are used to determine a match in the cache

    Parameters

    Returns Promise<void>

  • Helper function to return an Entity Name from a given Entity ID.

    Parameters

    • entityName: string

    Returns string

  • Helper function to return an Entity Name from an Entity ID

    Parameters

    • entityID: string

    Returns string

  • Gets a dataset by name, if required, and caches it in a format available to the client (e.g. IndexedDB, LocalStorage, File, etc). The cache method is Provider specific If itemFilters are provided, the combination of datasetName and the filters are used to determine a match in the cache

    Parameters

    Returns Promise<DatasetResultType>

  • Creates a new instance of a BaseEntity subclass for the specified entity and automatically calls NewRecord() to initialize it. This method uses the MJGlobal ClassFactory to instantiate the correct subclass based on registered entity types. For entities with non-auto-increment uniqueidentifier primary keys, a UUID will be automatically generated.

    Type Parameters

    Parameters

    • entityName: string

      The name of the entity to create (e.g., "Users", "Customers", "Orders")

    • Optional contextUser: UserInfo

      Optional user context for server-side operations. Client-side code can typically omit this. Can be a UserInfo instance or an object with matching shape (ID, Name, Email, UserRoles)

    Returns Promise<T>

    Promise resolving to a strongly-typed entity instance ready for data entry

    Example

    // Create a new customer record
    const customer = await metadata.GetEntityObject<CustomerEntity>('Customers');
    customer.Name = 'Acme Corp';
    await customer.Save();

    Example

    // Server-side with context user
    const order = await metadata.GetEntityObject<OrderEntity>('Orders', contextUser);
    order.CustomerID = customerId;
    await order.Save();
  • Creates a new instance of a BaseEntity subclass and loads an existing record using the provided composite key. This overload combines entity instantiation with record loading in a single call for convenience.

    Type Parameters

    Parameters

    • entityName: string

      The name of the entity to create (e.g., "Users", "Customers", "Orders")

    • loadKey: CompositeKey

      CompositeKey containing the primary key value(s) to load. Use static helper methods: - CompositeKey.FromID(id) for single "ID" primary keys - CompositeKey.FromKeyValuePair(field, value) for single named primary keys - CompositeKey.FromKeyValuePairs([...]) for composite primary keys

    • Optional contextUser: UserInfo

      Optional user context for server-side operations

    Returns Promise<T>

    Promise resolving to the entity instance with the specified record loaded

    Throws

    Error if the entity name is invalid or the record cannot be found

    Example

    // Load by ID (most common case)
    const customer = await metadata.GetEntityObject<CustomerEntity>('Customers', CompositeKey.FromID(customerId));

    Example

    // Load by named field
    const user = await metadata.GetEntityObject<UserEntity>('Users', CompositeKey.FromKeyValuePair('Email', 'user@example.com'));

    Example

    // Load with composite key
    const orderItem = await metadata.GetEntityObject<OrderItemEntity>('OrderItems',
    CompositeKey.FromKeyValuePairs([
    { FieldName: 'OrderID', Value: orderId },
    { FieldName: 'ProductID', Value: productId }
    ])
    );
  • Returns the Name of the specific KeyValuePairs for a given entityName. This is done by looking for the IsNameField within the EntityFields collection for a given entity. If no IsNameField is found, but a field called "Name" exists, that value is returned. Otherwise null returned

    Parameters

    Returns Promise<string>

    the name of the record

  • Returns an array of records representing the list of changes made to a record. This functionality only works if an entity has TrackRecordChanges = 1, which is the default for most entities. If TrackRecordChanges = 0, this method will return an empty array.

    This method is defined in the @memberjunction/core package, which is lower level in the dependency hierarchy than the @memberjunction/core-entities package where the RecordChangeEntity class is defined. For this reason, we are not using the RecordChangeEntity class here, but rather returning a generic type T. When you call this method, you can specify the type T to be the RecordChangeEntity class or any other class that matches the structure of the record changes. For example:

    const md = new Metadata();
    const changes: RecordChangeEntity[] = await md.GetRecordChanges<RecordChangeEntity>('MyEntity', myPrimaryKey);

    Type Parameters

    • T

    Parameters

    Returns Promise<T[]>

  • Returns a list of dependencies - records that are linked to the specified Entity/Primary Key Value combination. A dependency is as defined by the relationships in the database. The MemberJunction metadata that is used for this simply reflects the foreign key relationships that exist in the database. The CodeGen tool is what detects all of the relationships and generates the metadata that is used by MemberJunction. The metadata in question is within the EntityField table and specifically the RelatedEntity and RelatedEntityField columns. In turn, this method uses that metadata and queries the database to determine the dependencies. To get the list of entity dependencies you can use the utility method GetEntityDependencies(), which doesn't check for dependencies on a specific record, but rather gets the metadata in one shot that can be used for dependency checking.

    Parameters

    • entityName: string

      the name of the entity to check

    • primaryKey: CompositeKey

      the primary key value to check

    Returns Promise<RecordDependency[]>

  • Returns true if the combination of userId/entityName/KeyValuePairs has a favorite status on (meaning the user has marked the record as a "favorite" for easy access)

    Parameters

    Returns Promise<boolean>

  • This routine checks to see if the local cache version of a given datasetName/itemFilters combination is up to date with the server or not

    Parameters

    Returns Promise<boolean>

  • Determines if a given datasetName/itemFilters combination is cached locally or not

    Parameters

    Returns Promise<boolean>

  • This method will merge two or more records based on the request provided. The RecordMergeRequest type you pass in specifies the record that will survive the merge, the records to merge into the surviving record, and an optional field map that can update values in the surviving record, if desired. The process followed is:

    1. The surviving record is loaded and fields are updated from the field map, if provided, and the record is saved. If a FieldMap not provided within the request object, this step is skipped.
    2. For each of the records that will be merged INTO the surviving record, we call the GetEntityDependencies() method and get a list of all other records in the database are linked to the record to be deleted. We then go through each of those dependencies and update the link to point to the SurvivingRecordKeyValuePair and save the record.
    3. The record to be deleted is then deleted.

    The return value from this method contains detailed information about the execution of the process. In addition, all attempted merges are logged in the RecordMergeLog and RecordMergeDeletionLog tables.

    IMPORTANT NOTE: This functionality ASSUMES that you are calling BEGIN TRANS and COMMIT TRANS/ROLLBACK TRANS outside of the work being done inside if you are on the database server side (not on the client side). The reason is that many API servers that use this object infrastructure have transaction wrappers for each individual API request so we are not doing BEGIN/COMMIT/ROLLBACK within this functionality. If you are using this on the client side, you don't need to do anything extra, the server side, however, must wrap this with begin/commit/rollback statements to the database server. If you're using MJAPI/MJServer this is done for you automatically.

    Parameters

    Returns Promise<RecordMergeResult>

  • Removes all the metadata from the local persistent storage method (which varies by provider). This generally shouldn't need to be called externally but is available to force an complete removal of local metadata in storage. NOTE: this does not remove Datasets, for removing datasets, use ClearDatasetCache()

    Returns Promise<void>

  • Saves all the in-memory metadata to be updated in the local persistent storage method (which varies by provider). This generally shouldn't need to be called externally but is available to force an update to local storage as desired.

    Returns Promise<void>

  • Sets the favorite status for a given user for a specific entityName/KeyValuePairs

    Parameters

    • userId: string
    • entityName: string
    • primaryKey: CompositeKey
    • isFavorite: boolean
    • contextUser: UserInfo = null

    Returns Promise<void>