Drive Items API client for the Mosaia SDK

Provides CRUD operations for managing drive items (files and documents) in the Mosaia platform. Drive items are files and documents stored within drives.

This class inherits from BaseCollection and provides the following functionality:

  • Retrieve drive items with filtering and pagination
  • Create new drive items (metadata-only or with file uploads)
  • Update drive item metadata
  • Delete drive items
  • Handle file uploads
import { Mosaia } from 'mosaia-node-sdk';

const mosaia = new Mosaia({ apiKey: 'your-api-key' });
const drive = await mosaia.drives.get({}, 'drive-id');
const items = drive.items;

// Get all items in the drive
const allItems = await items.get();

// Get a specific item
const item = await items.get({}, 'item-id');

// Create a metadata-only item
const newItem = await items.create({
name: 'document.pdf',
path: '/documents',
size: 1024
});

Hierarchy

Constructors

  • Creates a new Drive Items API client instance

    Initializes the drive items client with the appropriate endpoint URI and model class for handling drive item operations.

    The constructor sets up the API endpoint to /drive/:driveId/item (or ${uri}/drive/:driveId/item if a base URI is provided), which corresponds to the Mosaia API's drive items endpoint.

    Parameters

    • uri: string = ''

      Base URI path. Typically /drive/:driveId where :driveId is the drive ID. If not provided, defaults to /drive/item.

    Returns DriveItems

    // Create with drive URI
    const items = new DriveItems('/drive/drive-id-123');

    // Create via drive model instance
    const drive = await mosaia.drives.get({}, 'drive-id');
    const items = drive.items; // Uses drive.getUri() internally

Methods

  • Get entities with optional filtering and pagination

    This method retrieves entities from the API. When called without an ID, it returns a list of entities with optional filtering and pagination. When called with an ID, it returns a specific entity.

    Parameters

    • params: undefined | QueryParams

      Optional query parameters for filtering and pagination

      • undefined
      • QueryParams

        Query parameters interface for API requests

        Used to define common query parameters that can be passed to API endpoints for filtering, sorting, and pagination.

        • [key: string]: any

          Additional custom query parameters

        • Optionalq?: string

          Search term for text-based filtering

        • Optionallimit?: number

          Maximum number of items to return

        • Optionaloffset?: number

          Number of items to skip (for offset-based pagination)

        • Optionaltags?: string[]

          Array of tags to filter by

        • Optionalactive?: boolean

          Filter by active status

        • Optionalexternal_id?: string

          Filter by external ID

    • id: string

      Optional specific entity ID to retrieve

    Returns Promise<null | DriveItem>

    Promise resolving to: - BatchAPIResponse when getting multiple entities - M when getting a single entity by ID - null when entity is not found

    Get multiple entities with filtering:

    const result = await collection.get({
    limit: 10,
    offset: 0,
    q: 'search term',
    active: true,
    tags: ['tag1', 'tag2']
    });

    console.log('Items:', result.data);
    console.log('Total:', result.paging?.total);

    Get single entity by ID:

    const entity = await collection.get({}, 'entity-id');
    if (entity) {
    console.log('Found:', entity.id);
    } else {
    console.log('Entity not found');
    }

    When API request fails or response is invalid

  • Get entities with optional filtering and pagination

    This method retrieves entities from the API. When called without an ID, it returns a list of entities with optional filtering and pagination. When called with an ID, it returns a specific entity.

    Parameters

    • Optionalparams: QueryParams

      Optional query parameters for filtering and pagination

      Query parameters interface for API requests

      Used to define common query parameters that can be passed to API endpoints for filtering, sorting, and pagination.

      • [key: string]: any

        Additional custom query parameters

      • Optionalq?: string

        Search term for text-based filtering

      • Optionallimit?: number

        Maximum number of items to return

      • Optionaloffset?: number

        Number of items to skip (for offset-based pagination)

      • Optionaltags?: string[]

        Array of tags to filter by

      • Optionalactive?: boolean

        Filter by active status

      • Optionalexternal_id?: string

        Filter by external ID

    Returns Promise<BatchAPIResponse<DriveItem>>

    Promise resolving to: - BatchAPIResponse when getting multiple entities - M when getting a single entity by ID - null when entity is not found

    Get multiple entities with filtering:

    const result = await collection.get({
    limit: 10,
    offset: 0,
    q: 'search term',
    active: true,
    tags: ['tag1', 'tag2']
    });

    console.log('Items:', result.data);
    console.log('Total:', result.paging?.total);

    Get single entity by ID:

    const entity = await collection.get({}, 'entity-id');
    if (entity) {
    console.log('Found:', entity.id);
    } else {
    console.log('Entity not found');
    }

    When API request fails or response is invalid

  • Create a new entity

    This method creates a new entity in the system. The entity ID will be automatically generated by the server. The method returns a new model instance initialized with the created entity's data.

    Parameters

    Returns Promise<DriveItem>

    Promise resolving to a new model instance

    Create a new user:

    const newUser = await users.create({
    email: 'user@example.com',
    firstName: 'John',
    lastName: 'Doe',
    active: true
    });

    console.log('Created user:', newUser.id);

    Create with external ID:

    const newAgent = await agents.create({
    name: 'Customer Support',
    shortDescription: 'AI agent for support',
    external_id: 'agent-123',
    extensors: {
    customField: 'value'
    }
    });

    When API request fails or response is invalid

    When required fields are missing

  • Update an existing entity

    This method updates an existing entity in the system. Only the fields provided in the update data will be updated.

    Parameters

    • id: string

      The entity ID to update

    • updates: Partial<DriveItemInterface>

      Partial entity data for the update (only provided fields will be updated)

    • Optionalparams: QueryParams

      Optional query parameters for the request

    Returns Promise<DriveItem>

    Promise resolving to the updated model instance

    Update user's email:

    const updatedUser = await users.update('user-id', {
    email: 'newemail@example.com'
    });

    Update multiple fields:

    const updatedAgent = await agents.update('agent-id', {
    name: 'Updated Agent Name',
    shortDescription: 'Updated description',
    active: false
    });

    When API request fails or response is invalid

    When entity ID is not provided

  • Delete an entity

    This method permanently deletes an entity from the system. This action cannot be undone.

    Parameters

    • id: string

      The entity ID to delete

    • Optionalparams: QueryParams

      Optional query parameters object. Can include:

      • force: Force deletion even if entity has dependencies (boolean)

    Returns Promise<void>

    Promise that resolves when deletion is successful

    Basic deletion:

    await users.delete('user-id');
    

    Force delete:

    await organizations.delete('org-id', { force: true });
    

    When API request fails or entity not found

    When entity ID is not provided

  • Upload files to the drive using presigned URLs

    Uploads one or more files to the drive using presigned URLs for direct S3 uploads. This method supports batch file uploads and directory uploads with structure preservation. The backend returns presigned URLs that you can use to upload files directly to S3.

    Parameters

    • files: File[]

      Array of File objects to upload (required for file uploads)

    • Optionaloptions: {
          path?: string;
          relativePaths?: string | string[];
          preserveStructure?: boolean;
      }

      Optional upload options

      • Optionalpath?: string

        Base path where files should be uploaded (defaults to '/')

      • OptionalrelativePaths?: string | string[]

        Array of relative paths for directory structure preservation

      • OptionalpreserveStructure?: boolean

        Boolean flag to enable/disable structure preservation (default: true if relativePaths provided)

    Returns Promise<
        {
            message: string;
            uploadJob: {
                id: string;
                status: string;
                total_files: number;
                total_size: number;
                started_at: Date;
            };
            files: {
                fileId: string;
                filename: string;
                presignedUrl: string;
                mimeType: string;
                size: number;
                path: string;
                expiresIn: number;
                expiresAt: Date;
                failedUrl: string;
            }[];
            statusUrl: string;
            instructions: {
                step1: string;
                step2: string;
                step3: string;
                step4: string;
            };
        },
    >

    Promise resolving to upload job information with presigned URLs

    // Single file upload
    const fileInput = document.getElementById('fileInput') as HTMLInputElement;
    const file = fileInput.files[0];

    const result = await items.uploadFiles([file], {
    path: '/documents'
    });

    console.log('Upload job ID:', result.uploadJob.id);
    // Upload each file to S3 using presignedUrl
    for (const fileInfo of result.files) {
    await fetch(fileInfo.presignedUrl, {
    method: 'PUT',
    body: file
    });
    }
    // Batch file upload with directory structure
    const files = Array.from(fileInput.files);
    const result = await items.uploadFiles(files, {
    path: '/uploads',
    relativePaths: ['folder1/file1.txt', 'folder2/file2.txt'],
    preserveStructure: true
    });

    When upload fails

  • Upload a single file to the drive

    Convenience method for uploading a single file using presigned URLs for direct S3 upload.

    Parameters

    • file: File

      File object to upload

    • Optionaloptions: { path?: string; relativePath?: string; preserveStructure?: boolean }

      Optional upload options

      • Optionalpath?: string

        Optional path within the drive (defaults to '/')

      • OptionalrelativePath?: string

        Optional relative path for the file

      • OptionalpreserveStructure?: boolean

        Boolean flag to enable/disable structure preservation

    Returns Promise<
        {
            message: string;
            uploadJob: {
                id: string;
                status: string;
                total_files: number;
                total_size: number;
                started_at: Date;
            };
            files: {
                fileId: string;
                filename: string;
                presignedUrl: string;
                mimeType: string;
                size: number;
                path: string;
                expiresIn: number;
                expiresAt: Date;
                failedUrl: string;
            }[];
            statusUrl: string;
            instructions: {
                step1: string;
                step2: string;
                step3: string;
                step4: string;
            };
        },
    >

    Promise resolving to upload job information with presigned URL

    const fileInput = document.getElementById('fileInput') as HTMLInputElement;
    const file = fileInput.files[0];

    const result = await items.uploadFile(file, {
    path: '/documents',
    relativePath: 'folder/file.txt'
    });

    console.log('Upload job ID:', result.uploadJob.id);
    // Upload file to S3 using presignedUrl
    const fileInfo = result.files[0];
    await fetch(fileInfo.presignedUrl, {
    method: 'PUT',
    body: file
    });

    When upload fails

  • Get upload job status

    Retrieves the status of an asynchronous file upload job.

    Parameters

    • jobId: string

      The upload job ID returned from uploadFile or uploadFiles

    Returns Promise<
        {
            jobId: string;
            status: string;
            progress: {
                total: number;
                processed: number;
                successful: number;
                failed: number;
                percentage: number;
            };
            size: { total: number; uploaded: number; percentage: number };
            files: any[];
            startedAt?: Date;
            completedAt?: Date;
            errorSummary?: any;
        },
    >

    Promise resolving to upload job status information

    const result = await items.uploadFile(file);

    // Check upload status
    const status = await items.getUploadStatus(result.uploadJob.id);
    console.log('Upload progress:', status.progress.percentage + '%');
    console.log('Status:', status.status);

    When job not found or API request fails

  • Mark a file upload as failed

    Marks a file upload as failed if the client-side upload to S3 fails. This method should be called if the upload to the presigned URL fails.

    Parameters

    • fileId: string

      The file ID of the upload to mark as failed

    • Optionalerror: { error?: string; errorMessage?: string }

      Optional error message or object describing the failure

    Returns Promise<
        {
            fileId: string;
            status: string;
            upload_status: string;
            upload_error?: string;
        },
    >

    Promise resolving to the file status after marking as failed

    try {
    const result = await items.uploadFile(file);
    const fileInfo = result.files[0];

    // Try to upload to S3
    const uploadResponse = await fetch(fileInfo.presignedUrl, {
    method: 'PUT',
    body: file
    });

    if (!uploadResponse.ok) {
    // Mark as failed if S3 upload fails
    await items.markUploadFailed(fileInfo.fileId, {
    error: `Upload failed: ${uploadResponse.statusText}`
    });
    }
    } catch (error) {
    // Mark as failed if there's an exception
    await items.markUploadFailed(fileInfo.fileId, {
    error: error.message
    });
    }

    When file not found or API request fails