Member Junction
    Preparing search index...

    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.

    Index

    Constructors

    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
      • 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

    • 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>

    • Performs a full-text search across all entities with FullTextSearchEnabled=true. Uses the database-native full-text search capabilities through the provider stack.

      Parameters

      • params: FullTextSearchParams

        Search parameters — SearchText is required, EntityNames and MaxRowsPerEntity are optional

      • OptionalcontextUser: UserInfo

        Optional user context for permissions

      Returns Promise<FullTextSearchResult>

      Search results with title, snippet, and relevance score per match

      const md = new Metadata();
      const results = await md.FullTextSearch({
      SearchText: 'claude',
      MaxRowsPerEntity: 5
      });
      // results.Results contains matches across all FTS-enabled entities
      // Search only specific entities
      const results = await md.FullTextSearch({
      SearchText: 'quarterly report',
      EntityNames: ['MJ: AI Models', 'MJ: AI Prompts'],
      MaxRowsPerEntity: 10
      }, contextUser);

      /packages/MJCore/docs/FULL_TEXT_SEARCH_GUIDE.md

    • 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")

      • OptionalcontextUser: 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

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

      • OptionalcontextUser: UserInfo

        Optional user context for server-side operations

      Returns Promise<T>

      Promise resolving to the entity instance with the specified record loaded

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

      // Load by ID (most common case)
      const customer = await metadata.GetEntityObject<CustomerEntity>('Customers', CompositeKey.FromID(customerId));
      // Load by named field
      const user = await metadata.GetEntityObject<MJUserEntity>('Users', CompositeKey.FromKeyValuePair('Email', 'user@example.com'));
      // 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

      • entityName: string
      • primaryKey: CompositeKey
      • OptionalcontextUser: UserInfo
      • forceRefresh: boolean = false

      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 MJRecordChangeEntity class is defined. For this reason, we are not using the MJRecordChangeEntity class here, but rather returning a generic type T. When you call this method, you can specify the type T to be the MJRecordChangeEntity class or any other class that matches the structure of the record changes. For example:

      const md = new Metadata();
      const changes: MJRecordChangeEntity[] = await md.GetRecordChanges<MJRecordChangeEntity>('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 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>

    • Batch form of SearchEntity. Runs the per-entity ranking against many entities in one call. Transports as a single JSON payload in both directions over GraphQL when invoked through GraphQLDataProvider, so N entity searches cost one round-trip instead of N.

      Server-side providers fan the call out via Promise.all to independent SearchEntity invocations — each entity's lexical pass, semantic pass, blending, and permission filter run independently, and the per-entity result arrays come back aligned by input order.

      Use this whenever an agent or workflow needs ranked results from more than one entity for the same user request (e.g., "find anything relevant to 'overdue payments'" across Invoices, Customers, and Notes).

      Parameters

      Returns Promise<EntitySearchResult[][]>

      Array of result arrays, aligned by input order — result[i] holds the ranked matches for params[i].

    • Ranked search over one entity's records, blending lexical name/text-field matching with semantic embedding cosine. Results are post-filtered by the caller's row-level read permissions on that entity.

      Method Purpose
      EntityByName / EntityByID Look up an entity definition by name or ID. Deterministic, not ranked, returns EntityInfo.
      FullTextSearch Server-side text search across one or many entities using each entity's UserSearchString rule (DB-level LIKE / FTS). Returns flat per-entity result groups, no semantic ranking.
      SearchEntity (this) Hybrid lexical-plus-semantic ranking of records inside one entity, backed by an EntityDocument-driven vector index. Use when you need "the N most relevant records of this entity for the user's free-text request".
      SearchEntities Batch form — runs SearchEntity over many entities in one round-trip.

      Semantic ranking requires an Active EntityDocument of type Search registered for the target entity (see /metadata/entity-documents/ for the seeded one against MJ: Entities); without it, mode: 'semantic' returns no rows and mode: 'hybrid' degrades to lexical-only.

      Parameters

      Returns Promise<EntitySearchResult[]>

      Ranked EntitySearchResult[] — descending by score, sliced to topK.

    • 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>