Skip to main content

JavaScript SDK

The AstraCollab JavaScript SDK provides a pure JavaScript client for Node.js and browser environments. Perfect for server-side applications, CLI tools, and browser-based file management.

Installation

npm install @astracollab/js

Quick Start

Basic Usage

import { AstraCollabClient } from '@astracollab/js';

const client = new AstraCollabClient({
  apiKey: 'your-api-key-here'
});

// List files
const files = await client.listFiles();
console.log('Files:', files);

// Upload a file
const fileId = await client.uploadFile({
  file: fileObject,
  fileName: 'example.jpg',
  folderId: 'optional-folder-id'
});
console.log('File uploaded:', fileId);

Node.js Example

import { AstraCollabClient } from '@astracollab/js';
import fs from 'fs';

const client = new AstraCollabClient({
  apiKey: process.env.ASTRACOLLAB_API_KEY
});

// Upload a file from the filesystem
const fileBuffer = fs.readFileSync('./example.jpg');
const file = new Blob([fileBuffer], { type: 'image/jpeg' });

const fileId = await client.uploadFile({
  file,
  fileName: 'example.jpg',
  folderId: 'my-folder'
});

console.log('File uploaded with ID:', fileId);

API Reference

Constructor

const client = new AstraCollabClient(config);
Parameters:
  • config.apiKey (string, required): Your AstraCollab API key
  • config.baseURL (string, optional): API base URL (defaults to https://api.astracollab.app)

File Management

List Files

const files = await client.listFiles(folderId);
Parameters:
  • folderId (string, optional): Folder ID to list files from
Returns: Array of file objects

Upload File

const fileId = await client.uploadFile(options);
Parameters:
  • options.file (File|Blob, required): File to upload
  • options.fileName (string, optional): Custom file name
  • options.folderId (string, optional): Folder to upload to
  • options.orgId (string, optional): Organization ID
  • options.onProgress (function, optional): Progress callback
Returns: File ID string

Download File

const fileBuffer = await client.downloadFile(fileId);
Parameters:
  • fileId (string, required): ID of the file to download
Returns: Buffer containing file data

Get File Details

const file = await client.getFile(fileId);
Parameters:
  • fileId (string, required): ID of the file
Returns: File object with metadata

Delete File

await client.deleteFile(fileId);
Parameters:
  • fileId (string, required): ID of the file to delete

Folder Management

List Folders

const folders = await client.listFolders(parentFolderId);
Parameters:
  • parentFolderId (string, optional): Parent folder ID
Returns: Array of folder objects

Create Folder

const folder = await client.createFolder(name, parentFolderId);
Parameters:
  • name (string, required): Folder name
  • parentFolderId (string, optional): Parent folder ID
Returns: Created folder object

API Key Management

List API Keys

const keys = await client.listApiKeys();
Returns: Array of API key objects

Create API Key

const key = await client.createApiKey(name);
Parameters:
  • name (string, required): API key name
Returns: Created API key object

Revoke API Key

await client.revokeApiKey(keyId);
Parameters:
  • keyId (string, required): API key ID to revoke

Examples

Upload Multiple Files

import { AstraCollabClient } from '@astracollab/js';

const client = new AstraCollabClient({
  apiKey: 'your-api-key-here'
});

const files = [
  { name: 'file1.jpg', data: file1Blob },
  { name: 'file2.pdf', data: file2Blob },
  { name: 'file3.txt', data: file3Blob }
];

for (const file of files) {
  try {
    const fileId = await client.uploadFile({
      file: file.data,
      fileName: file.name,
      folderId: 'my-folder'
    });
    console.log(`Uploaded ${file.name} with ID: ${fileId}`);
  } catch (error) {
    console.error(`Failed to upload ${file.name}:`, error);
  }
}

Progress Tracking

const fileId = await client.uploadFile({
  file: fileBlob,
  fileName: 'large-file.zip',
  onProgress: (progress) => {
    console.log(`Upload progress: ${progress}%`);
  }
});

Error Handling

try {
  const files = await client.listFiles();
  console.log('Files:', files);
} catch (error) {
  if (error.response?.status === 401) {
    console.error('Authentication failed. Check your API key.');
  } else if (error.response?.status === 429) {
    console.error('Rate limit exceeded. Try again later.');
  } else {
    console.error('An error occurred:', error.message);
  }
}

CLI Tool Example

#!/usr/bin/env node
import { AstraCollabClient } from '@astracollab/js';
import fs from 'fs';

const client = new AstraCollabClient({
  apiKey: process.env.ASTRACOLLAB_API_KEY
});

async function uploadFile(filePath) {
  try {
    const fileBuffer = fs.readFileSync(filePath);
    const fileName = filePath.split('/').pop();
    const file = new Blob([fileBuffer]);

    const fileId = await client.uploadFile({
      file,
      fileName
    });

    console.log(`✅ File uploaded successfully!`);
    console.log(`📁 File ID: ${fileId}`);
    console.log(`🔗 View at: https://app.astracollab.app/files/${fileId}`);
  } catch (error) {
    console.error('❌ Upload failed:', error.message);
    process.exit(1);
  }
}

// Usage: node upload.js path/to/file.jpg
const filePath = process.argv[2];
if (!filePath) {
  console.error('Please provide a file path');
  process.exit(1);
}

uploadFile(filePath);

Browser Example

<!DOCTYPE html>
<html>
<head>
    <title>AstraCollab File Upload</title>
</head>
<body>
    <input type="file" id="fileInput" multiple>
    <button onclick="uploadFiles()">Upload Files</button>
    <div id="progress"></div>

    <script type="module">
        import { AstraCollabClient } from 'https://unpkg.com/@astracollab/js@latest/dist/index.mjs';

        const client = new AstraCollabClient({
            apiKey: 'your-api-key-here'
        });

        window.uploadFiles = async function() {
            const fileInput = document.getElementById('fileInput');
            const progressDiv = document.getElementById('progress');
            
            const files = Array.from(fileInput.files);
            
            for (const file of files) {
                try {
                    const fileId = await client.uploadFile({
                        file,
                        fileName: file.name,
                        onProgress: (progress) => {
                            progressDiv.innerHTML = `Uploading ${file.name}: ${progress}%`;
                        }
                    });
                    
                    progressDiv.innerHTML += `<br>✅ ${file.name} uploaded (ID: ${fileId})`;
                } catch (error) {
                    progressDiv.innerHTML += `<br>❌ Failed to upload ${file.name}: ${error.message}`;
                }
            }
        };
    </script>
</body>
</html>

Error Handling

The SDK throws errors for various scenarios:
try {
  const files = await client.listFiles();
} catch (error) {
  switch (error.response?.status) {
    case 401:
      console.error('Invalid API key');
      break;
    case 403:
      console.error('Insufficient permissions');
      break;
    case 404:
      console.error('Resource not found');
      break;
    case 429:
      console.error('Rate limit exceeded');
      break;
    default:
      console.error('An error occurred:', error.message);
  }
}

Best Practices

  1. Environment Variables: Store API keys in environment variables
  2. Error Handling: Always implement proper error handling
  3. Progress Tracking: Use progress callbacks for large file uploads
  4. Rate Limiting: Respect API rate limits in your application
  5. File Validation: Validate files before upload (size, type, etc.)

Support

Need help with the JavaScript SDK?