@memberjunction/core v2.48.0
@memberjunction/core
The @memberjunction/core
library provides a comprehensive interface for accessing and managing metadata within MemberJunction, along with facilities for working with entities, applications, and various other aspects central to the MemberJunction ecosystem. This library serves as the foundation for all MemberJunction applications and provides essential functionality for data access, manipulation, and metadata management.
Installation
npm install @memberjunction/core
Overview
The @memberjunction/core
library is the central package in the MemberJunction ecosystem, providing:
- Metadata Management: Complete access to MemberJunction metadata including entities, fields, relationships, permissions, and more
- Entity Data Access: Base classes and utilities for loading, saving, and manipulating entity records
- View Execution: Powerful view running capabilities for both stored and dynamic views
- Query & Report Execution: Tools for running queries and reports
- Security & Authorization: User authentication, role management, and permission handling
- Transaction Management: Support for grouped database transactions
- Provider Architecture: Flexible provider model supporting different execution environments
Core Components
Metadata Class
The Metadata
class is the primary entry point for accessing MemberJunction metadata and instantiating entity objects.
import { Metadata } from '@memberjunction/core';
// Create metadata instance
const md = new Metadata();
// Refresh cached metadata
await md.Refresh();
// Access various metadata collections
const applications = md.Applications;
const entities = md.Entities;
const currentUser = md.CurrentUser;
const roles = md.Roles;
const authorizations = md.Authorizations;
Key Metadata Properties
Applications
: Array of all applications in the systemEntities
: Array of all entity definitionsCurrentUser
: Current authenticated user (when available)Roles
: System rolesAuditLogTypes
: Available audit log typesAuthorizations
: Authorization definitionsLibraries
: Registered librariesQueries
: Query definitionsQueryFields
: Query field metadataQueryCategories
: Query categorizationQueryPermissions
: Query-level permissionsVisibleExplorerNavigationItems
: Navigation items visible to current userAllExplorerNavigationItems
: All navigation items (including hidden)
Helper Methods
// Get entity ID from name
const entityId = md.EntityIDFromName('Users');
// Get entity name from ID
const entityName = md.EntityNameFromID('12345');
// Find entity by name (case-insensitive)
const userEntity = md.EntityByName('users');
// Find entity by ID
const entity = md.EntityByID('12345');
// Get entity object instance (IMPORTANT: Always use this pattern)
const user = await md.GetEntityObject<UserEntity>('Users');
BaseEntity Class
The BaseEntity
class is the foundation for all entity record manipulation in MemberJunction. All entity classes generated by the MemberJunction code generator extend this class.
import { Metadata } from '@memberjunction/core';
// IMPORTANT: Never instantiate entity classes directly
// Always use Metadata.GetEntityObject() to ensure proper class registration
// ✅ Correct way to create entity instances
const md = new Metadata();
const user = await md.GetEntityObject<UserEntity>('Users');
// Load a record by ID
await user.Load(123);
// Create a new record
user.NewRecord();
user.FirstName = 'John';
user.LastName = 'Doe';
user.Email = 'john.doe@example.com';
// Save the record (creates new or updates existing)
const saveResult = await user.Save();
if (saveResult) {
console.log('User saved successfully:', user.ID);
} else {
console.log('Save failed:', user.LatestResult.Message);
}
// Delete a record
const deleteResult = await user.Delete();
Entity Fields
Each entity field is represented by an EntityField
object that tracks value, dirty state, and metadata:
// Access field value
const firstName = user.Get('FirstName');
// Set field value
user.Set('FirstName', 'Jane');
// Check if field is dirty
const isDirty = user.Fields.find(f => f.Name === 'FirstName').Dirty;
// Access field metadata
const field = user.Fields.find(f => f.Name === 'Email');
console.log(field.IsUnique); // true/false
console.log(field.IsPrimaryKey); // true/false
console.log(field.ReadOnly); // true/false
Save Options
import { EntitySaveOptions } from '@memberjunction/core';
const options = new EntitySaveOptions();
options.IgnoreDirtyState = true; // Force save even if no changes detected
options.SkipEntityAIActions = true; // Skip AI-related actions
options.SkipEntityActions = true; // Skip entity actions
options.SkipOldValuesCheck = true; // Skip concurrency check (client-side only)
await entity.Save(options);
RunView Class
The RunView
class provides powerful view execution capabilities for both stored views and dynamic queries.
import { RunView, RunViewParams } from '@memberjunction/core';
const rv = new RunView();
// Run a stored view by name
const params: RunViewParams = {
ViewName: 'Active Users',
ExtraFilter: 'CreatedDate > \'2024-01-01\'',
UserSearchString: 'john'
};
const results = await rv.RunView(params);
// Run a dynamic view with entity objects returned
const dynamicResults = await rv.RunView<UserEntity>({
EntityName: 'Users',
ExtraFilter: 'IsActive = 1',
OrderBy: 'LastName ASC, FirstName ASC',
Fields: ['ID', 'FirstName', 'LastName', 'Email'],
ResultType: 'entity_object' // Returns actual entity objects
});
// Access typed results
const users = dynamicResults.Results; // Properly typed as UserEntity[]
RunView Parameters
ViewID
: ID of stored view to runViewName
: Name of stored view to runViewEntity
: Pre-loaded view entity object (optimal for performance)EntityName
: Entity name for dynamic viewsExtraFilter
: Additional SQL WHERE clauseOrderBy
: SQL ORDER BY clause (overrides stored view sorting)Fields
: Array of field names to returnUserSearchString
: User search termExcludeUserViewRunID
: Exclude records from specific prior runExcludeDataFromAllPriorViewRuns
: Exclude all previously returned recordsSaveViewResults
: Store run results for future exclusionIgnoreMaxRows
: Bypass entity MaxRows settingMaxRows
: Maximum rows to returnStartRow
: Row offset for paginationResultType
: 'simple' (default) or 'entity_object'
RunQuery Class
Execute stored queries with parameters:
import { RunQuery, RunQueryParams } from '@memberjunction/core';
const rq = new RunQuery();
const params: RunQueryParams = {
QueryID: '12345',
Parameters: {
StartDate: '2024-01-01',
EndDate: '2024-12-31',
Status: 'Active'
}
};
const results = await rq.RunQuery(params);
RunReport Class
Execute reports with various output formats:
import { RunReport, RunReportParams } from '@memberjunction/core';
const rr = new RunReport();
const params: RunReportParams = {
ReportID: '12345',
Parameters: {
Year: 2024,
Department: 'Sales'
}
};
const results = await rr.RunReport(params);
Transaction Management
Group multiple operations in a transaction:
import { TransactionGroupBase } from '@memberjunction/core';
// Transaction management is provider-specific
// Consult your provider documentation for implementation details
Entity Relationships
MemberJunction automatically handles entity relationships through the metadata system:
// Load an entity with related data
const order = await md.GetEntityObject<OrderEntity>('Orders');
await order.Load(123, ['OrderDetails', 'Customer']);
// Access related entities
const orderDetails = order.OrderDetails; // Array of OrderDetailEntity
const customer = order.Customer; // CustomerEntity
Security & Permissions
The library provides comprehensive security features:
const md = new Metadata();
// Check current user
const user = md.CurrentUser;
console.log('Current user:', user.Email);
// Check user roles
const isAdmin = user.RoleName.includes('Admin');
// Entity permissions
const entity = md.EntityByName('Orders');
const canCreate = entity.CanCreate;
const canUpdate = entity.CanUpdate;
const canDelete = entity.CanDelete;
Error Handling
All operations return detailed error information:
const entity = await md.GetEntityObject('Users');
const result = await entity.Save();
if (!result) {
// Access detailed error information
const error = entity.LatestResult;
console.error('Error:', error.Message);
console.error('Details:', error.Details);
// Check validation errors
if (error.ValidationErrors && error.ValidationErrors.length > 0) {
error.ValidationErrors.forEach(ve => {
console.error(`Field ${ve.FieldName}: ${ve.Message}`);
});
}
}
Provider Architecture
MemberJunction uses a provider model to support different execution environments:
import { SetProvider } from '@memberjunction/core';
// Provider setup is typically handled by your application initialization
// The provider determines how data is accessed (direct database, API, etc.)
SetProvider(myProvider);
Best Practices
- Always use Metadata.GetEntityObject() to create entity instances - never use
new
- Use generic types with RunView for type-safe results
- Handle errors properly - check return values and LatestResult
- Use transactions for related operations that must succeed/fail together
- Leverage metadata for dynamic UI generation and validation
- Respect permissions - always check CanCreate/Update/Delete before operations
- Use ExtraFilter carefully - ensure SQL injection protection
- Cache metadata instances when possible to improve performance
Integration with Other MemberJunction Packages
- @memberjunction/global: Global utilities and constants
- @memberjunction/server: Server-side provider implementation
- @memberjunction/client: Client-side provider implementation
- @memberjunction/angular: Angular-specific components and services
- @memberjunction/react: React-specific components and hooks
- @memberjunction/ai: AI integration features
- @memberjunction/communication: Communication and messaging features
Dependencies
- @memberjunction/global: Core global utilities
- rxjs: Reactive programming support
- zod: Schema validation
- debug: Debug logging
TypeScript Support
This library is written in TypeScript and provides full type definitions. All generated entity classes include proper typing for IntelliSense support.
License
ISC License - see LICENSE file for details
Support
For support, documentation, and examples, visit MemberJunction.com
8 months ago
5 months ago
8 months ago
6 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
6 months ago
6 months ago
5 months ago
9 months ago
9 months ago
9 months ago
6 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
5 months ago
8 months ago
7 months ago
8 months ago
7 months ago
7 months ago
7 months ago
9 months ago
5 months ago
9 months ago
9 months ago
9 months ago
9 months ago
8 months ago
7 months ago
5 months ago
9 months ago
9 months ago
5 months ago
5 months ago
8 months ago
8 months ago
7 months ago
9 months ago
9 months ago
9 months ago
5 months ago
5 months ago
8 months ago
8 months ago
5 months ago
6 months ago
10 months ago
5 months ago
8 months ago
4 months ago
10 months ago
6 months ago
11 months ago
10 months ago
11 months ago
6 months ago
11 months ago
4 months ago
8 months ago
8 months ago
12 months ago
6 months ago
6 months ago
8 months ago
12 months ago
12 months ago
12 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago