Skip to content

Watched Folders Examples

Last Updated: 2025-11-23

Complete examples for managing watched folders - monitoring local filesystem directories and synchronizing them with ocmonica.


Table of Contents


Add Watched Folder

Add a local filesystem directory to watch for changes.

REST API

Endpoint: POST /organizations/:orgId/watched-folders

curl Example

curl -X POST http://localhost:8080/organizations/org-789/watched-folders \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/Users/john/Documents",
    "enabled": true,
    "recursive": true
  }'

JavaScript/TypeScript Example

interface CreateWatchedFolderRequest {
  path: string;
  enabled?: boolean;
  recursive?: boolean;
}

async function addWatchedFolder(
  orgId: string,
  path: string,
  enabled = true,
  recursive = true
) {
  const response = await fetch(`http://localhost:8080/organizations/${orgId}/watched-folders`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      path,
      enabled,
      recursive
    })
  });

  return await response.json();
}

// Usage
const watchedFolder = await addWatchedFolder(
  'org-789',
  '/Users/john/Documents',
  true,
  true
);

console.log(`Watching folder: ${watchedFolder.path}`);
console.log(`Folder ID: ${watchedFolder.id}`);

Python Example

import requests

def add_watched_folder(org_id, path, access_token, enabled=True, recursive=True):
    response = requests.post(
        f'http://localhost:8080/organizations/{org_id}/watched-folders',
        headers={'Authorization': f'Bearer {access_token}'},
        json={
            'path': path,
            'enabled': enabled,
            'recursive': recursive
        }
    )

    return response.json()

# Usage
watched_folder = add_watched_folder(
    'org-789',
    '/Users/john/Documents',
    access_token,
    enabled=True,
    recursive=True
)

print(f"Watching folder: {watched_folder['path']}")
print(f"Folder ID: {watched_folder['id']}")

Go Example

type CreateWatchedFolderRequest struct {
    Path      string `json:"path"`
    Enabled   bool   `json:"enabled"`
    Recursive bool   `json:"recursive"`
}

type WatchedFolder struct {
    ID             string `json:"id"`
    Path           string `json:"path"`
    OrganizationID string `json:"organization_id"`
    Enabled        bool   `json:"enabled"`
    Recursive      bool   `json:"recursive"`
    LastScannedAt  string `json:"last_scanned_at,omitempty"`
    CreatedAt      string `json:"created_at"`
    UpdatedAt      string `json:"updated_at"`
}

func addWatchedFolder(orgID, path, accessToken string, enabled, recursive bool) (*WatchedFolder, error) {
    reqData := CreateWatchedFolderRequest{
        Path:      path,
        Enabled:   enabled,
        Recursive: recursive,
    }

    jsonData, _ := json.Marshal(reqData)
    req, _ := http.NewRequest("POST",
        fmt.Sprintf("http://localhost:8080/organizations/%s/watched-folders", orgID),
        bytes.NewBuffer(jsonData))

    req.Header.Set("Authorization", "Bearer "+accessToken)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var folder WatchedFolder
    json.NewDecoder(resp.Body).Decode(&folder)
    return &folder, nil
}

Response

{
  "id": "watched-folder-123",
  "path": "/Users/john/Documents",
  "organization_id": "org-789",
  "enabled": true,
  "recursive": true,
  "last_scanned_at": null,
  "created_at": "2025-11-23T10:00:00Z",
  "updated_at": "2025-11-23T10:00:00Z"
}

Parameters: - path (required): Absolute path to local directory - enabled (optional, default: true): Whether to actively watch the folder - recursive (optional, default: true): Whether to watch subdirectories


List Watched Folders

Get all watched folders for the current organization.

REST API

Endpoint: GET /organizations/:orgId/watched-folders

curl Example

# List all watched folders
curl -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  http://localhost:8080/organizations/org-789/watched-folders

# List only enabled folders
curl -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "http://localhost:8080/organizations/org-789/watched-folders?enabled=true"

JavaScript/TypeScript Example

interface ListWatchedFoldersOptions {
  enabled?: boolean;
}

async function listWatchedFolders(orgId: string, options: ListWatchedFoldersOptions = {}) {
  const params = new URLSearchParams();

  if (options.enabled !== undefined) {
    params.append('enabled', options.enabled.toString());
  }

  const response = await fetch(
    `http://localhost:8080/organizations/${orgId}/watched-folders?${params}`,
    {
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    }
  );

  return await response.json();
}

// Usage
const allFolders = await listWatchedFolders('org-789');
console.log(`Total watched folders: ${allFolders.length}`);

const enabledFolders = await listWatchedFolders('org-789', { enabled: true });
console.log(`Active watched folders: ${enabledFolders.length}`);

allFolders.forEach(folder => {
  console.log(`- ${folder.path} (${folder.enabled ? 'enabled' : 'disabled'})`);
});

Python Example

import requests

def list_watched_folders(org_id, access_token, enabled=None):
    params = {}

    if enabled is not None:
        params['enabled'] = str(enabled).lower()

    response = requests.get(
        f'http://localhost:8080/organizations/{org_id}/watched-folders',
        headers={'Authorization': f'Bearer {access_token}'},
        params=params
    )

    return response.json()

# Usage
all_folders = list_watched_folders('org-789', access_token)
print(f"Total watched folders: {len(all_folders)}")

enabled_folders = list_watched_folders('org-789', access_token, enabled=True)
print(f"Active watched folders: {len(enabled_folders)}")

for folder in all_folders:
    status = 'enabled' if folder['enabled'] else 'disabled'
    print(f"- {folder['path']} ({status})")

Go Example

type ListWatchedFoldersOptions struct {
    Enabled *bool
}

func listWatchedFolders(orgID, accessToken string, opts ListWatchedFoldersOptions) ([]WatchedFolder, error) {
    params := url.Values{}

    if opts.Enabled != nil {
        params.Add("enabled", strconv.FormatBool(*opts.Enabled))
    }

    url := fmt.Sprintf("http://localhost:8080/organizations/%s/watched-folders", orgID)
    if len(params) > 0 {
        url += "?" + params.Encode()
    }

    req, _ := http.NewRequest("GET", url, nil)
    req.Header.Set("Authorization", "Bearer "+accessToken)

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var folders []WatchedFolder
    json.NewDecoder(resp.Body).Decode(&folders)
    return folders, nil
}

Response

[
  {
    "id": "watched-folder-123",
    "path": "/Users/john/Documents",
    "organization_id": "org-789",
    "enabled": true,
    "recursive": true,
    "last_scanned_at": "2025-11-23T12:00:00Z",
    "created_at": "2025-11-23T10:00:00Z",
    "updated_at": "2025-11-23T10:00:00Z"
  },
  {
    "id": "watched-folder-456",
    "path": "/Users/john/Projects",
    "organization_id": "org-789",
    "enabled": false,
    "recursive": true,
    "last_scanned_at": "2025-11-22T18:00:00Z",
    "created_at": "2025-11-22T15:00:00Z",
    "updated_at": "2025-11-23T09:00:00Z"
  }
]

Get Watched Folder Details

Get detailed information about a specific watched folder.

REST API

Endpoint: GET /api/v1/watched-folders/:id

curl Example

curl -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  http://localhost:8080/api/v1/watched-folders/watched-folder-123

JavaScript/TypeScript Example

async function getWatchedFolder(folderId: string) {
  const response = await fetch(
    `http://localhost:8080/api/v1/watched-folders/${folderId}`,
    {
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    }
  );

  return await response.json();
}

// Usage
const folder = await getWatchedFolder('watched-folder-123');
console.log(`Path: ${folder.path}`);
console.log(`Enabled: ${folder.enabled}`);
console.log(`Last scanned: ${folder.last_scanned_at || 'Never'}`);

Python Example

import requests

def get_watched_folder(folder_id, access_token):
    response = requests.get(
        f'http://localhost:8080/api/v1/watched-folders/{folder_id}',
        headers={'Authorization': f'Bearer {access_token}'}
    )

    return response.json()

# Usage
folder = get_watched_folder('watched-folder-123', access_token)
print(f"Path: {folder['path']}")
print(f"Enabled: {folder['enabled']}")
print(f"Last scanned: {folder.get('last_scanned_at', 'Never')}")

Update Watched Folder

Update watched folder settings like path, enabled status, or recursive flag.

REST API

Endpoint: PUT /api/v1/watched-folders/:id

curl Example

# Disable watching
curl -X PUT http://localhost:8080/api/v1/watched-folders/watched-folder-123 \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "enabled": false
  }'

# Change path
curl -X PUT http://localhost:8080/api/v1/watched-folders/watched-folder-123 \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/Users/john/Documents/Work",
    "recursive": false
  }'

JavaScript/TypeScript Example

async function updateWatchedFolder(
  folderId: string,
  updates: {
    path?: string;
    enabled?: boolean;
    recursive?: boolean;
  }
) {
  const response = await fetch(
    `http://localhost:8080/api/v1/watched-folders/${folderId}`,
    {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(updates)
    }
  );

  return await response.json();
}

// Usage - disable watching temporarily
await updateWatchedFolder('watched-folder-123', {
  enabled: false
});

// Usage - change path
await updateWatchedFolder('watched-folder-123', {
  path: '/Users/john/Documents/Work',
  recursive: false
});

Python Example

import requests

def update_watched_folder(folder_id, access_token, **updates):
    response = requests.put(
        f'http://localhost:8080/api/v1/watched-folders/{folder_id}',
        headers={'Authorization': f'Bearer {access_token}'},
        json=updates
    )

    return response.json()

# Usage - disable watching
update_watched_folder('watched-folder-123', access_token, enabled=False)

# Usage - change settings
update_watched_folder(
    'watched-folder-123',
    access_token,
    path='/Users/john/Documents/Work',
    recursive=False
)

Go Example

type UpdateWatchedFolderRequest struct {
    Path      *string `json:"path,omitempty"`
    Enabled   *bool   `json:"enabled,omitempty"`
    Recursive *bool   `json:"recursive,omitempty"`
}

func updateWatchedFolder(folderID, accessToken string, updates UpdateWatchedFolderRequest) (*WatchedFolder, error) {
    jsonData, _ := json.Marshal(updates)
    req, _ := http.NewRequest("PUT",
        fmt.Sprintf("http://localhost:8080/api/v1/watched-folders/%s", folderID),
        bytes.NewBuffer(jsonData))

    req.Header.Set("Authorization", "Bearer "+accessToken)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var folder WatchedFolder
    json.NewDecoder(resp.Body).Decode(&folder)
    return &folder, nil
}

Remove Watched Folder

Stop watching a folder and remove it from the watched list.

REST API

Endpoint: DELETE /api/v1/watched-folders/:id

curl Example

curl -X DELETE \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  http://localhost:8080/api/v1/watched-folders/watched-folder-123

JavaScript/TypeScript Example

async function removeWatchedFolder(folderId: string) {
  const response = await fetch(
    `http://localhost:8080/api/v1/watched-folders/${folderId}`,
    {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    }
  );

  if (response.ok) {
    console.log('Watched folder removed successfully');
  }
}

// Usage with confirmation
if (confirm('Stop watching this folder?')) {
  await removeWatchedFolder('watched-folder-123');
}

Python Example

import requests

def remove_watched_folder(folder_id, access_token):
    response = requests.delete(
        f'http://localhost:8080/api/v1/watched-folders/{folder_id}',
        headers={'Authorization': f'Bearer {access_token}'}
    )

    return response.ok

# Usage
if remove_watched_folder('watched-folder-123', access_token):
    print('Watched folder removed successfully')

Note: Removing a watched folder does not delete the actual files from the filesystem, only stops monitoring.


Trigger Manual Scan

Manually trigger a scan of a watched folder to synchronize changes.

REST API

Endpoint: POST /api/v1/watched-folders/:id/scan

curl Example

curl -X POST \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  http://localhost:8080/api/v1/watched-folders/watched-folder-123/scan

JavaScript/TypeScript Example

async function triggerScan(folderId: string) {
  const response = await fetch(
    `http://localhost:8080/api/v1/watched-folders/${folderId}/scan`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    }
  );

  return await response.json();
}

// Usage
const result = await triggerScan('watched-folder-123');
console.log(`Scan completed`);
console.log(`Files scanned: ${result.files_scanned}`);
console.log(`New files: ${result.new_files}`);
console.log(`Updated files: ${result.updated_files}`);

Python Example

import requests

def trigger_scan(folder_id, access_token):
    response = requests.post(
        f'http://localhost:8080/api/v1/watched-folders/{folder_id}/scan',
        headers={'Authorization': f'Bearer {access_token}'}
    )

    return response.json()

# Usage
result = trigger_scan('watched-folder-123', access_token)
print(f"Scan completed")
print(f"Files scanned: {result['files_scanned']}")
print(f"New files: {result['new_files']}")
print(f"Updated files: {result['updated_files']}")

Go Example

type ScanResult struct {
    FilesScanned int       `json:"files_scanned"`
    NewFiles     int       `json:"new_files"`
    UpdatedFiles int       `json:"updated_files"`
    ScannedAt    time.Time `json:"scanned_at"`
}

func triggerScan(folderID, accessToken string) (*ScanResult, error) {
    req, _ := http.NewRequest("POST",
        fmt.Sprintf("http://localhost:8080/api/v1/watched-folders/%s/scan", folderID),
        nil)

    req.Header.Set("Authorization", "Bearer "+accessToken)

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var result ScanResult
    json.NewDecoder(resp.Body).Decode(&result)
    return &result, nil
}

Response

{
  "files_scanned": 127,
  "new_files": 5,
  "updated_files": 3,
  "scanned_at": "2025-11-23T14:30:00Z"
}

List files and directories within a watched folder.

REST API

Endpoint: GET /api/v1/watched-folders/:id/files

Query Parameters: - path (optional) - Relative path within watched folder - limit (optional) - Maximum number of results (default: 100) - offset (optional) - Pagination offset (default: 0)

curl Example

# List root of watched folder
curl -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  http://localhost:8080/api/v1/watched-folders/watched-folder-123/files

# List specific subdirectory
curl -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "http://localhost:8080/api/v1/watched-folders/watched-folder-123/files?path=Invoices"

# List with pagination
curl -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "http://localhost:8080/api/v1/watched-folders/watched-folder-123/files?limit=50&offset=100"

JavaScript/TypeScript Example

interface ListFilesOptions {
  path?: string;
  limit?: number;
  offset?: number;
}

async function listWatchedFolderFiles(
  folderId: string,
  options: ListFilesOptions = {}
) {
  const params = new URLSearchParams();

  if (options.path) params.append('path', options.path);
  if (options.limit) params.append('limit', options.limit.toString());
  if (options.offset) params.append('offset', options.offset.toString());

  const response = await fetch(
    `http://localhost:8080/api/v1/watched-folders/${folderId}/files?${params}`,
    {
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    }
  );

  return await response.json();
}

// Usage - list root
const rootFiles = await listWatchedFolderFiles('watched-folder-123');
console.log(`Files in root: ${rootFiles.files.length}`);

// Usage - list subdirectory
const invoices = await listWatchedFolderFiles('watched-folder-123', {
  path: 'Invoices'
});
console.log(`Invoices: ${invoices.files.length}`);

// Display file tree
rootFiles.files.forEach(file => {
  const type = file.is_directory ? 'DIR' : 'FILE';
  console.log(`[${type}] ${file.name}`);
});

Python Example

import requests

def list_watched_folder_files(folder_id, access_token, path=None, limit=100, offset=0):
    params = {
        'limit': limit,
        'offset': offset
    }

    if path:
        params['path'] = path

    response = requests.get(
        f'http://localhost:8080/api/v1/watched-folders/{folder_id}/files',
        headers={'Authorization': f'Bearer {access_token}'},
        params=params
    )

    return response.json()

# Usage
root_files = list_watched_folder_files('watched-folder-123', access_token)
print(f"Files in root: {len(root_files['files'])}")

# List subdirectory
invoices = list_watched_folder_files(
    'watched-folder-123',
    access_token,
    path='Invoices'
)
print(f"Invoices: {len(invoices['files'])}")

# Display file tree
for file in root_files['files']:
    file_type = 'DIR' if file['is_directory'] else 'FILE'
    print(f"[{file_type}] {file['name']}")

Response

{
  "files": [
    {
      "name": "Invoices",
      "path": "/Users/john/Documents/Invoices",
      "is_directory": true,
      "size": 0,
      "modified_at": "2025-11-20T10:00:00Z"
    },
    {
      "name": "report.pdf",
      "path": "/Users/john/Documents/report.pdf",
      "is_directory": false,
      "size": 524288,
      "mime_type": "application/pdf",
      "modified_at": "2025-11-23T09:30:00Z"
    },
    {
      "name": "notes.txt",
      "path": "/Users/john/Documents/notes.txt",
      "is_directory": false,
      "size": 2048,
      "mime_type": "text/plain",
      "modified_at": "2025-11-23T14:00:00Z"
    }
  ],
  "total": 27,
  "limit": 100,
  "offset": 0
}

Complete Workflow Example

Setting Up Watched Folder with Auto-Sync

const orgId = 'org-789';

// 1. Add watched folder
const watchedFolder = await addWatchedFolder(
  orgId,
  '/Users/john/Projects/current',
  true,  // enabled
  true   // recursive
);

console.log(`Created watched folder: ${watchedFolder.id}`);

// 2. Trigger initial scan
const scanResult = await triggerScan(watchedFolder.id);
console.log(`Initial scan: ${scanResult.new_files} files indexed`);

// 3. Set up periodic scanning (every 5 minutes)
setInterval(async () => {
  console.log('Running periodic scan...');
  const result = await triggerScan(watchedFolder.id);

  if (result.new_files > 0 || result.updated_files > 0) {
    console.log(`Changes detected: ${result.new_files} new, ${result.updated_files} updated`);
  }
}, 5 * 60 * 1000);

// 4. Browse folder contents
const contents = await listWatchedFolderFiles(watchedFolder.id);
console.log('Folder contents:');
contents.files.forEach(file => {
  const icon = file.is_directory ? '📁' : '📄';
  console.log(`${icon} ${file.name}`);
});

See Also