Dcupl Class API

The Dcupl class is the main entry point for the dcupl SDK. It provides access to models, lists, data operations, and query functionality.

Constructor

new Dcupl(options?)

Creates a new dcupl instance.

Signature:

constructor(options?: DcuplInitOptions): Dcupl

Parameters:

Parameter Type Required Description
options DcuplInitOptions No Configuration options for initialization

Returns: Dcupl instance

Examples:

Create a basic instance
const dcupl = new Dcupl();
Create with configuration
const dcupl = new Dcupl({
  config: {
    projectId: 'your-project-id',
    apiKey: 'your-api-key',
    version: 'draft',
  },
});
Enable quality checks
const dcupl = new Dcupl({
  quality: {
    enabled: true,
  },
});
Enable performance caching
const dcupl = new Dcupl({
  performance: {
    cache: {
      enabled: true,
    },
  },
});
Enable auto-update for lists
const dcupl = new Dcupl({
  performance: {
    autoUpdateLists: {
      enabled: true,
    },
  },
});

Properties

models

Access to the models API for managing data models.

Type: ModelsAPI

See: Models API Reference

Example:

const model = dcupl.models.get('Product');

lists

Access to the lists API for managing data lists.

Type: ListsController

See: Lists API Reference

Example:

const list = dcupl.lists.create({ modelKey: 'Product' });

data

Access to the data API for managing data operations.

Type: DataAPI

See: Data API Reference

Example:

dcupl.data.set(products, { model: 'Product' });

query

Access to query operations.

Type: QueryAPI

Example:

const items = dcupl.query.execute({
  modelKey: 'Product',
  queries: [{ operator: 'eq', attribute: 'status', value: 'active' }],
});

fn

Access to analytical functions.

Type: FunctionsAPI

Example:

const facets = dcupl.fn.facets({
  modelKey: 'Product',
  options: { attribute: 'category' },
});

views

Access to view definitions. Views are pre-configured data representations (section views for groupBy, pivot views for cross-tabulation).

Type: ViewsAPI

Methods:

Method Signature Description
get (viewKey: string) => ViewDefinition | undefined Get a view definition by key
keys (options?: { modelKey: string }) => string[] Get all view keys, optionally filtered by model
set (view: ViewDefinition) => void Register a new view definition

View Types:

// Section View - for groupBy operations
type ViewDefinitionSection = {
  key: string;
  model: string;
  type: 'section';
  primaryAttribute: string;
  aggregates: AggregationOptions[];
};

// Pivot View - for pivot table operations
type ViewDefinitionPivot = {
  key: string;
  model: string;
  type: 'pivot';
  options: PivotOptions;
};

Examples:

// Register a section view
dcupl.views.set({
  key: 'productsByCategory',
  model: 'Product',
  type: 'section',
  primaryAttribute: 'category',
  aggregates: [{ attribute: 'price', types: ['sum', 'avg'] }],
});

// Register a pivot view
dcupl.views.set({
  key: 'salesPivot',
  model: 'Order',
  type: 'pivot',
  options: {
    rows: [{ attribute: 'region' }],
    columns: [{ attribute: 'quarter' }],
    values: [{ attribute: 'revenue', types: ['sum'] }],
  },
});

// Get a view
const view = dcupl.views.get('productsByCategory');

// Get all view keys for a model
const productViews = dcupl.views.keys({ modelKey: 'Product' });

scripts

Access to custom scripts. Scripts allow you to execute custom JavaScript code with access to the dcupl instance.

Type: ScriptsAPI

Methods:

Method Signature Description
set (key: string, script: string) => void Register a script by key
get (key: string) => string | undefined Get a script by key
remove (key: string) => void Remove a script
keys () => string[] Get all registered script keys
execute (key: string, options?: any) => any Execute a script synchronously
executeAsync (key: string, options?: any) => Promise Execute a script asynchronously

Script Context:

Scripts receive an args object containing:

  • dcupl - The dcupl instance
  • options - Custom options passed to execute
  • resolve/reject - For async scripts only

Examples:

// Register a synchronous script
dcupl.scripts.set(
  'calculateTotal',
  `
  const list = dcupl.lists.get('cart');
  const items = list.catalog.query.items();
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
`
);

// Execute synchronously
const total = dcupl.scripts.execute('calculateTotal');

// Register an async script
dcupl.scripts.set(
  'fetchAndUpdate',
  `
  fetch('/api/products')
    .then(res => res.json())
    .then(data => {
      dcupl.data.set(data, { model: 'Product' });
      resolve({ updated: data.length });
    })
    .catch(reject);
`
);

// Execute asynchronously
const result = await dcupl.scripts.executeAsync('fetchAndUpdate');

// Pass options to script
dcupl.scripts.set(
  'filterByCategory',
  `
  const list = dcupl.lists.get('products');
  list.catalog.query.addCondition({
    attribute: 'category',
    operator: 'eq',
    value: options.category,
  });
  return list.catalog.query.items();
`
);

const electronics = dcupl.scripts.execute('filterByCategory', { category: 'Electronics' });

// List all scripts
const scriptKeys = dcupl.scripts.keys();

// Remove a script
dcupl.scripts.remove('filterByCategory');

loaders

Access to data loaders. Loaders handle fetching and processing configuration and data from external sources.

Type: LoadersAPI

Methods:

Method Signature Description
add (loader: DcuplAppLoader, key: string) => void Register a loader by key
remove (key: string) => void Remove a loader
get (key: string) => DcuplAppLoader | undefined Get a loader by key

Example:

import { DcuplAppLoader } from '@dcupl/loader';

// Create and configure a loader
const loader = new DcuplAppLoader();
await loader.config.fetch({
  projectId: 'my-project',
  apiKey: 'my-api-key',
});

// Register with dcupl
dcupl.loaders.add(loader, 'main');

// Initialize dcupl (processes all loaders)
await dcupl.init();

// Access loader later
const mainLoader = dcupl.loaders.get('main');

initOptions

The initialization options passed to the constructor.

Type: DcuplInitOptions

Example:

console.log(dcupl.initOptions.performance?.cache?.enabled);

version

The version of the dcupl SDK.

Type: string

Example:

console.log(dcupl.version); // "1.12.0"

Methods

init()

Initializes the dcupl instance and processes all registered models and data.

Signature:

async init(): Promise<boolean>

Returns: Promise - true if initialization was successful, false otherwise

Examples:

Basic initialization
await dcupl.init();
With error handling
const success = await dcupl.init();
if (!success) {
  console.error('Initialization failed');
}
Complete workflow
const dcupl = new Dcupl();
dcupl.models.set({
  key: 'Product',
  properties: [
    { key: 'name', type: 'string' },
    { key: 'price', type: 'float' },
  ],
});
dcupl.data.set(products, { model: 'Product' });
await dcupl.init();

update()

Updates the dcupl instance with any pending data changes. Supports partial updates for better performance.

Signature:

async update(options?: DcuplUpdateOptions): Promise<boolean>

Parameters:

Parameter Type Required Description
options DcuplUpdateOptions No Update configuration options

Returns: Promise - true if update was successful, false otherwise

Examples:

Basic update
await dcupl.update();
Force auto-update for all lists
await dcupl.update({ autoUpdateLists: true });
Disable auto-update for this specific update
await dcupl.update({ autoUpdateLists: false });
Update workflow
dcupl.data.update([{ key: 'p1', name: 'Updated Product' }], { model: 'Product' });
await dcupl.update();
Batch updates
dcupl.data.update(batch1, { model: 'Product' });
dcupl.data.update(batch2, { model: 'Category' });
await dcupl.update(); // Processes both batches

destroy()

Destroys the dcupl instance and cleans up all resources.

Signature:

destroy(): void

Examples:

Clean up resources
dcupl.destroy();
Complete lifecycle
const dcupl = new Dcupl();
await dcupl.init();
// ... use dcupl
dcupl.destroy();

on()

Subscribes to change events from the dcupl instance.

Signature:

on(callback: CallbackFunction): () => void

Parameters:

Parameter Type Required Description
callback CallbackFunction Yes Function to call on changes

Returns: () => void - Unsubscribe function

Examples:

Subscribe to all changes
const unsubscribe = dcupl.on((message) => {
  console.log('Change detected:', message);
});
Unsubscribe when done
unsubscribe();
React to specific change types
dcupl.on((message) => {
  if (message.type === 'dcupl_updated_manually') {
    console.log('Data was updated');
  }
  if (message.type === 'dcupl_partial_update') {
    console.log('Partial update:', message.args);
  }
});
Multiple subscribers
const unsub1 = dcupl.on(callback1);
const unsub2 = dcupl.on(callback2);

// Cleanup all
unsub1();
unsub2();

Configuration Types

DcuplInitOptions

Configuration options for initializing a dcupl instance.

Type Definition:

type DcuplInitOptions = {
  config?: DcuplInitConfig;
  quality?: DcuplInitQualityConfig;
  performance?: DcuplInitPerformanceConfig;
  analytics?: DcuplInitErrorAnalyticsConfig;
  referenceMetadata?: DcuplInitReferenceMetadataConfig;
  logging?: DcuplInitLoggingConfig;
};

Properties:

Property Type Description
config DcuplInitConfig Project configuration (projectId, apiKey, version)
quality DcuplInitQualityConfig Data quality validation settings
performance DcuplInitPerformanceConfig Performance optimization settings
analytics DcuplInitErrorAnalyticsConfig Analytics tracking settings
referenceMetadata DcuplInitReferenceMetadataConfig Reference metadata settings
logging DcuplInitLoggingConfig Logging configuration

DcuplInitConfig

Project configuration settings.

Type Definition:

type DcuplInitConfig = {
  projectId?: string;
  apiKey?: string;
  version?: string;
};

Example:

const dcupl = new Dcupl({
  config: {
    projectId: 'my-project',
    apiKey: 'readonly-key',
    version: 'v1.0.0',
  },
});

DcuplInitQualityConfig

Data quality validation configuration.

Type Definition:

type DcuplInitQualityConfig = {
  enabled: boolean;
};

Example:

const dcupl = new Dcupl({
  quality: {
    enabled: true,
  },
});

DcuplInitPerformanceConfig

Performance optimization settings.

Type Definition:

type DcuplInitPerformanceConfig = {
  cache?: {
    enabled: boolean;
  };
  clone?: {
    enabled: boolean;
  };
  partialUpdates?: DcuplPartialUpdateConfig;
  containerBatchSize?: number;
  autoUpdateLists?: {
    enabled: boolean;
  };
};

Properties:

Property Type Description
cache.enabled boolean Enable internal API caching
clone.enabled boolean Enable deep cloning of data
partialUpdates DcuplPartialUpdateConfig Partial update optimization settings
containerBatchSize number Batch processing size (undefined = async, 0 = sync, N = batch)
autoUpdateLists.enabled boolean Automatically update lists when data changes

Examples:

Enable caching
const dcupl = new Dcupl({
  performance: {
    cache: { enabled: true },
  },
});
Optimize partial updates
const dcupl = new Dcupl({
  performance: {
    partialUpdates: {
      modelRatioThreshold: 0.5,
      itemRatioThreshold: 0.5,
      cacheInvalidationThreshold: 0.7,
      enableDetailedLogging: true,
    },
  },
});
Enable auto-update for lists
const dcupl = new Dcupl({
  performance: {
    autoUpdateLists: { enabled: true },
  },
});

DcuplPartialUpdateConfig

Partial update optimization configuration.

Type Definition:

type DcuplPartialUpdateConfig = {
  modelRatioThreshold?: number;
  itemRatioThreshold?: number;
  cacheInvalidationThreshold?: number;
  enableDetailedLogging?: boolean;
};

Properties:

Property Type Default Description
modelRatioThreshold number 0.5 Threshold for triggering full update (0-1)
itemRatioThreshold number 0.5 Item change threshold for full update (0-1)
cacheInvalidationThreshold number 0.7 Threshold for full cache clear (0-1)
enableDetailedLogging boolean false Enable detailed update logging

DcuplUpdateOptions

Options for the update() method.

Type Definition:

type DcuplUpdateOptions = {
  autoUpdateLists?: boolean;
};

Properties:

Property Type Description
autoUpdateLists boolean Override auto-update behavior for this specific update

Example:

Force update all lists
await dcupl.update({ autoUpdateLists: true });
Prevent list updates
await dcupl.update({ autoUpdateLists: false });

DcuplInitLoggingConfig

Logging configuration settings.

Type Definition:

type DcuplInitLoggingConfig = {
  level?: LogLevel;
  format?: 'json' | 'pretty';
  onLog?: (entry: LogEntry) => void;
  modules?: Record<string, LogLevel>;
};

Properties:

Property Type Description
level LogLevel Minimum log level ('debug', 'info', 'warn', 'error')
format 'json' | 'pretty' Output format
onLog function Custom log handler
modules Record Module-specific log levels

Example:

const dcupl = new Dcupl({
  logging: {
    level: 'debug',
    format: 'pretty',
    onLog: (entry) => {
      // Send to external service
      console.log(entry);
    },
    modules: {
      ModelParser: 'debug',
      Catalog: 'warn',
    },
  },
});

Complete Examples

Basic Setup

import { Dcupl } from '@dcupl/core';

// Create instance
const dcupl = new Dcupl();

// Define model
dcupl.models.set({
  key: 'Product',
  properties: [
    { key: 'name', type: 'string' },
    { key: 'price', type: 'float' },
    { key: 'status', type: 'string' },
  ],
});

// Add data
dcupl.data.set(
  [
    { key: 'p1', name: 'Product 1', price: 100, status: 'active' },
    { key: 'p2', name: 'Product 2', price: 200, status: 'active' },
  ],
  { model: 'Product' }
);

// Initialize
await dcupl.init();

// Query data
const products = dcupl.query.execute({
  modelKey: 'Product',
  queries: [{ operator: 'eq', attribute: 'status', value: 'active' }],
});

Advanced Configuration

const dcupl = new Dcupl({
  config: {
    projectId: 'my-project',
    apiKey: 'my-api-key',
    version: 'v1.0.0',
  },
  quality: {
    enabled: true,
  },
  performance: {
    cache: {
      enabled: true,
    },
    clone: {
      enabled: true,
    },
    partialUpdates: {
      modelRatioThreshold: 0.5,
      itemRatioThreshold: 0.5,
      cacheInvalidationThreshold: 0.7,
      enableDetailedLogging: false,
    },
    autoUpdateLists: {
      enabled: true,
    },
  },
  logging: {
    level: 'info',
    format: 'json',
  },
});

Update Lifecycle

// Initial setup
await dcupl.init();

// Update single item
dcupl.data.update([{ key: 'p1', price: 150 }], { model: 'Product' });
await dcupl.update();

// Batch updates
dcupl.data.update(batch1, { model: 'Product' });
dcupl.data.update(batch2, { model: 'Category' });
await dcupl.update();

// Force list updates
await dcupl.update({ autoUpdateLists: true });

Event Handling

Subscribe to changes
const unsubscribe = dcupl.on((message) => {
  console.log('Event type:', message.type);
  console.log('Scope:', message.scope);

  if (message.type === 'dcupl_partial_update') {
    const changeInfo = message.args[0];
    console.log('Changed models:', changeInfo.changedModels);
    console.log('Affected models:', changeInfo.affectedModels);
  }
});
Cleanup
unsubscribe();

Multiple Instances

Instance for products
const productsCore = new Dcupl();
productsCore.models.set(productModel);
await productsCore.init();
Instance for orders
const ordersCore = new Dcupl();
ordersCore.models.set(orderModel);
await ordersCore.init();
Independent data and queries
// Each instance has its own isolated data and queries

See Also