DriveItem class for managing files and documents in drives

This class represents a file or document item within a drive in the Mosaia platform. Drive items contain metadata about files, including their location, size, and type.

Features:

  • File metadata management
  • Path and organization
  • Size and type tracking
  • URL access

Drive items represent:

  • Files stored in drives
  • Document metadata
  • File organization and paths
  • Access URLs

Basic drive item:

import { DriveItem } from 'mosaia-node-sdk';

// Create a drive item
const item = new DriveItem({
name: 'document.pdf',
path: '/documents',
size: 1024,
mime_type: 'application/pdf'
});

await item.save();

Hierarchy (View Summary)

Constructors

  • Creates a new DriveItem instance

    Initializes a drive item with the provided metadata and optional URI. The drive item represents a file or document within a drive.

    Parameters

    • data: Partial<DriveItemInterface>

      Drive item metadata

    • Optionaluri: string

      Optional URI path for the drive item endpoint. Defaults to '/drive/:driveId/item'

    Returns DriveItem

    const item = new DriveItem({
    name: 'report.pdf',
    path: '/reports',
    size: 2048,
    mime_type: 'application/pdf'
    });

Accessors

  • get indexes(): VectorIndexes

    Get the drive item's vector indexes collection

    This getter provides access to the drive item's vector indexes through the VectorIndexes collection. It enables management of all vector indexes associated with this drive item (folder).

    Note: Vector indexes are typically associated with folders, not individual files.

    Returns VectorIndexes

    VectorIndexes collection for managing vector indexes

    List indexes for a folder:

    const folder = await drive.items.get({}, folderId);
    const indexes = await folder.indexes.get({ active: true });
    indexes.forEach(index => {
    console.log(`Index: ${index.name}`);
    });

    Create index for a folder:

    const folder = await drive.items.get({}, folderId);
    const index = await folder.indexes.create({
    name: 'Folder Search Index',
    description: 'Index for searching folder contents'
    });
  • get access(): Access

    Get the access control functionality for this drive item

    This getter provides access to the drive item's access control methods through the Access class. It allows for granting and revoking permissions to users, org users, agents, and clients.

    Important: The available roles depend on whether the item is a directory (folder) or a file:

    • Directories can use: READ_ONLY, VIEWER, EDITOR, CONTRIBUTOR (includes create), MANAGER
    • Files can use: READ_ONLY, VIEWER, EDITOR (no create), MANAGER

    Returns Access

    An Access instance configured for this drive item

    Grant access to a directory (folder):

    const directory = await drive.items.get({}, directoryId);

    // Directories support all roles including CONTRIBUTOR
    await directory.access.grantByRole({ org_user: 'orguser123' }, 'CONTRIBUTOR');

    // Grant editor role
    await directory.access.grantByRole({ org_user: 'orguser123' }, 'EDITOR');

    // Grant path-based access
    await directory.access.grantByRole(
    { org_user: 'orguser123' },
    'EDITOR',
    { mode: 'path', folder_role: 'READ_ONLY' }
    );

    Grant access to a file:

    const file = await drive.items.get({}, fileId);

    // Files can use VIEWER, EDITOR, or MANAGER (not CONTRIBUTOR)
    await file.access.grantByRole({ org_user: 'orguser123' }, 'EDITOR');

    // CONTRIBUTOR is not valid for files
    // await file.access.grantByRole({ org_user: 'orguser123' }, 'CONTRIBUTOR'); // ❌ Invalid

    Revoke access:

    const item = await drive.items.get({}, itemId);

    // Revoke all access from a user
    const result = await item.access.revoke({ org_user: 'orguser123' });
    console.log(`Revoked ${result.revoked_count} permissions`);

    // Revoke all access from a client
    const result = await item.access.revoke({ client: clientObj });
    console.log(`Removed ${result.revoked_count} permissions`);

    List all accessors:

    const item = await drive.items.get({}, itemId);

    const result = await item.access.list();
    result.accessors.forEach(accessor => {
    console.log(`${accessor.accessor_type} ${accessor.accessor_id} has ${accessor.role} role`);
    });

Methods

  • Check if the entity is active

    This method checks the active status of the entity. Most entities in the system can be active or inactive, which affects their availability and usability in the platform.

    Returns boolean

    True if the entity is active, false otherwise

    const user = new User(userData);
    if (user.isActive()) {
    // Perform operations with active user
    } else {
    console.log('User is inactive');
    }
  • Convert model instance to interface data

    This method serializes the model instance to a plain object that matches the interface type. This is useful for:

    • Sending data to the API
    • Storing data in a database
    • Passing data between components
    • Debugging model state

    Returns DriveItemInterface

    The model data as a plain object matching the interface type

    const user = new User({
    email: 'user@example.com',
    firstName: 'John'
    });

    const data = user.toJSON();
    console.log(data); // { email: '...', firstName: '...' }

    // Use with JSON.stringify
    const json = JSON.stringify(user);
  • Convert model instance to API payload

    This method creates a payload suitable for API requests by:

    • Converting the model to a plain object
    • Removing read-only fields (like 'id')
    • Ensuring proper data format for the API

    Returns Partial<DriveItemInterface>

    A clean object suitable for API requests

    const user = new User({
    id: '123', // Will be removed from payload
    email: 'new@example.com',
    firstName: 'John'
    });

    const payload = user.toAPIPayload();
    // payload = { email: '...', firstName: '...' }
    // Note: 'id' is removed as it's read-only

    await apiClient.POST('/users', payload);
  • Update model data with new values

    This method updates the model's data and instance properties with new values. It performs a shallow merge of the updates with existing data, allowing for partial updates of the model's properties.

    Parameters

    Returns void

    const user = new User({
    email: 'old@example.com',
    firstName: 'John'
    });

    // Update multiple properties
    user.update({
    email: 'new@example.com',
    lastName: 'Doe'
    });

    // Save changes to API
    await user.save();

    This method only updates the local model instance. To persist changes to the API, call save after updating.

  • Save the model instance to the API

    This method persists the current state of the model to the API using a PUT request. It requires the model to have an ID (existing instance). For new instances, use the collection's create method instead.

    The method:

    1. Validates the model has an ID
    2. Sends current data to the API
    3. Updates local instance with API response

    Returns Promise<DriveItemInterface>

    Promise resolving to the updated model data

    When model has no ID

    When API request fails

    const user = new User({
    id: '123',
    email: 'user@example.com'
    });

    // Update and save
    user.update({ firstName: 'John' });
    await user.save();

    Error handling:

    try {
    await user.save();
    } catch (error) {
    if (error.message.includes('ID is required')) {
    // Handle missing ID error
    } else {
    // Handle API errors
    }
    }
  • Delete the model instance from the API

    This method permanently deletes the model instance from the API and clears the local data. This operation cannot be undone.

    The method:

    1. Validates the model has an ID
    2. Sends DELETE request to the API
    3. Clears local instance data on success

    Parameters

    • Optionalparams: object

      Optional query parameters for deletion (e.g., { delete: true, deleteS3: true })

    Returns Promise<void>

    Promise that resolves when deletion is successful

    When model has no ID

    When API request fails

    Basic deletion:

    const user = await users.get({}, 'user-id');
    if (user) {
    await user.delete();
    // User is now deleted and instance is cleared
    }

    Error handling:

    try {
    await user.delete();
    console.log('User deleted successfully');
    } catch (error) {
    if (error.message.includes('ID is required')) {
    console.error('Cannot delete - no ID');
    } else {
    console.error('Deletion failed:', error.message);
    }
    }

    Delete with query parameters:

    // Hard delete
    await item.delete({ delete: true });

    // Delete with S3 cleanup
    await item.delete({ deleteS3: true, delete: true });
  • Get the download URL for this file or folder

    Returns a URL that can be used to download the file directly or as a ZIP archive if it's a folder. The download is handled by the backend which either redirects to S3 for files or streams a ZIP archive for folders.

    Parameters

    • OptionalexpiresIn: number

      Number of seconds until the download URL expires (default: 3600 = 1 hour)

    Returns Promise<string>

    Promise resolving to the download URL

    If the item is unsaved or if download fails

    Download a file in the browser:

    const item = await drive.items.get({}, itemId);

    // Get download URL and trigger download
    const url = await item.downloadUrl();
    window.location.href = url;

    Download with custom expiration:

    // Download URL expires in 2 hours
    const url = await item.downloadUrl(7200);

    // Use with fetch for programmatic download
    const response = await fetch(url);
    const blob = await response.blob();

    Download a folder as ZIP:

    const folder = await drive.items.get({}, folderId);
    const zipUrl = await folder.downloadUrl();
    // Browser will download the ZIP file
    window.location.href = zipUrl;
    • For files: Returns a URL that redirects to S3 presigned URL
    • For folders: Returns a URL that streams a ZIP archive
    • The download URL is authenticated and validates permissions