Lime Web Components API Documentation - v7.4.0
    Preparing search index...

    Interface TaskRepository

    Service for creating and monitoring long-running background tasks

    The TaskRepository provides a way to create background tasks that execute asynchronously on the server. This is useful for operations that take significant time to complete, such as bulk data processing, report generation, or data imports.

    Tasks are tracked by unique IDs and emit events (TaskEventType) as they progress through their lifecycle. A task created through create is followed for you, and an event is dispatched once it finishes. Listening to those events is the way to give users feedback on progress and completion. Use getStatus for tasks that were not created in this session, or for a one-off check.

    Since TaskRepository extends StateRepository, components can call StateRepository.subscribe to react to task state changes.

    import {
    PlatformServiceName,
    TaskEvent,
    TaskEventType,
    } from '@limetech/lime-web-components';

    const eventDispatcher = platform.get(PlatformServiceName.EventDispatcher);

    const onTaskSuccess = (event: TaskEvent) => {
    // Suppress the built-in snackbar and show our own message instead
    event.preventDefault();

    const { task } = event.detail;
    console.log('Task finished', task.id, task.result);
    };

    const onTaskFailure = (event: TaskEvent) => {
    const { error } = event.detail;
    console.error('Task failed', error);
    };

    eventDispatcher.addListener(TaskEventType.Success, onTaskSuccess);
    eventDispatcher.addListener(TaskEventType.Failed, onTaskFailure);

    // Remember to remove the listeners in `disconnectedCallback()`
    eventDispatcher.removeListener(TaskEventType.Success, onTaskSuccess);
    eventDispatcher.removeListener(TaskEventType.Failed, onTaskFailure);
    interface TaskRepository {
        create(
            url: string,
            data: unknown,
            cancelAction?: boolean,
            message?: string,
        ): Promise<string | void>;
        getStatus(ids: string[]): Promise<TaskStatus[]>;
        subscribe(
            callback: (...args: unknown[]) => void,
            options?: StateOptions,
        ): () => void;
    }

    Hierarchy (View Summary)

    Index

    Methods

    • Create a new background task on the server

      This method initiates a long-running operation on the server and returns a task ID that can be used to monitor the task's progress. The task will execute asynchronously, and task events will be emitted as it progresses.

      Parameters

      • url: string

        URL of the server endpoint that will create and execute the task. A URL without a leading slash is resolved against the current database

      • data: unknown

        Task-specific data to send to the server endpoint

      • OptionalcancelAction: boolean

        Whether the notification shows a cancel button that lets the user stop the task before it starts. Defaults to true

      • Optionalmessage: string

        Custom notification message to display to the user. If not provided, a default message will be shown

      Returns Promise<string | void>

      A promise that resolves to the task ID once the task has been created. Resolves to void if the user cancels, or if the task could not be created

      import { PlatformServiceName } from '@limetech/lime-web-components';

      const taskRepository = platform.get(PlatformServiceName.TaskRepository);

      const taskId = await taskRepository.create('api/v1/generate-report', {
      reportType: 'sales',
      year: 2024,
      });

      console.log('Report task created', taskId);
      import { PlatformServiceName } from '@limetech/lime-web-components';

      const taskRepository = platform.get(PlatformServiceName.TaskRepository);

      // `cancelAction` is `true` by default, so pass `false` to hide the cancel button
      const taskId = await taskRepository.create(
      'api/v1/import-data',
      { sourceFile: 'data.csv' },
      false,
      'Importing data from CSV file...'
      );

      // No id also means the task failed to start, not only that it was cancelled
      if (!taskId) {
      console.log('The import did not start');
      }
    • Get the current status of one or more tasks

      This method queries the server for the current state of the specified tasks. Use this to check task progress, retrieve results, or verify completion.

      Parameters

      • ids: string[]

        Array of task IDs to query

      Returns Promise<TaskStatus[]>

      A promise that resolves to an array of TaskStatus objects. A task whose status cannot be read is left out, so the array can be shorter than ids, or empty

      import { PlatformServiceName, TaskState } from '@limetech/lime-web-components';

      const taskRepository = platform.get(PlatformServiceName.TaskRepository);

      // The array is empty when the status could not be read
      const [status] = await taskRepository.getStatus(['task-123']);

      if (status?.status === TaskState.Success) {
      console.log('Task result', status.result);
      } else if (status?.status === TaskState.Failure) {
      console.error('Task failed');
      } else {
      console.log('Task still running...');
      }
      import { PlatformServiceName, TaskState } from '@limetech/lime-web-components';

      const taskRepository = platform.get(PlatformServiceName.TaskRepository);

      const taskIds = ['task-1', 'task-2', 'task-3'];

      // Tasks whose status could not be read are missing from the array
      const statuses = await taskRepository.getStatus(taskIds);

      const activeStates = new Set([
      TaskState.Pending,
      TaskState.Started,
      TaskState.Retry,
      ]);

      const completed = statuses.filter((s) => s.status === TaskState.Success);
      const failed = statuses.filter((s) => s.status === TaskState.Failure);
      const inProgress = statuses.filter((s) => activeStates.has(s.status));

      console.log(
      `${completed.length} completed, ${failed.length} failed, ${inProgress.length} in progress`
      );

      TaskState for the states a task can be in

    • Subscribe to state changes with optional transformation and filtering.

      The subscription will immediately invoke the callback with the current state (if any), then continue to call it whenever the state changes. The map and filter options allow you to transform and selectively receive updates.

      Parameters

      • callback: (...args: unknown[]) => void

        Function called with state updates (after map/filter applied)

      • Optionaloptions: StateOptions

        Optional transformations and filters for the subscription

      Returns () => void

      Unsubscribe function - call this to stop receiving updates

      • Map functions are applied sequentially to transform the state
      • Filter functions must all return true for the callback to be invoked
      • Functions in map/filter arrays are bound to the component instance
      • Always store and call the unsubscribe function when component is destroyed
      import { PlatformServiceName } from '@limetech/lime-web-components';

      const repository = platform.get(PlatformServiceName.Application);
      const logger = platform
      .get(PlatformServiceName.Logger)
      .createLogger('my-component');

      // Basic subscription
      const unsubscribeState = repository.subscribe((state) => {
      logger.debug('State updated', { state });
      });

      // With transformations
      const unsubscribeUserName = repository.subscribe(
      (userName) => logger.debug('User', { userName }),
      { map: [(state) => state.currentUser?.fullname] }
      );