Skip to content
Last updated

PERS SDK - v2.3.26 / Exports / FileManager

Class: FileManager

File Manager - Clean, high-level interface for file operations

Provides a comprehensive API for file management including secure file uploads, download URLs, media optimization, and cloud storage integration. Handles file operations for various entity types including tokens, campaigns, businesses, and user profiles with automatic security and optimization features.

Example

// Get signed URL for uploading a campaign image
const uploadUrl = await sdk.files.getSignedPutUrl(
  'campaign-123',
  'campaign',
  'jpg'
);

// Upload file using the signed URL
const file = document.getElementById('fileInput').files[0];
const response = await fetch(uploadUrl, {
  method: 'PUT',
  body: file,
  headers: { 'Content-Type': file.type }
});

console.log('File uploaded successfully:', response.ok);

Example

// Get secure download URL
const downloadUrl = await sdk.files.getSignedGetUrl(
  'token-456',
  'token',
  3600  // 1 hour expiry
);

// Get optimized thumbnail
const thumbnail = await sdk.files.optimizeMedia(
  downloadUrl,
  300,  // width
  300   // height
);

console.log('Thumbnail URL:', thumbnail);

Example

// Use flexible signed URL API
const customUrl = await sdk.files.getSignedUrl({
  operation: 'GET',
  entityId: 'business-789',
  entityType: 'business',
  expireSeconds: 7200,
  contentType: 'image/png'
});

Table of contents

Constructors

Methods

Constructors

constructor

• new FileManager(apiClient): FileManager

Parameters

NameType
apiClientPersApiClient

Returns

FileManager

Defined in

managers/file-manager.ts:74

Methods

getSignedPutUrl

▸ getSignedPutUrl(entityId, entityType, fileExtension): Promise<string>

Get signed URL for file upload

Generates a secure, time-limited URL for uploading files to cloud storage. The URL provides direct upload access while maintaining security and associating files with specific entities in the loyalty system.

Parameters

NameTypeDescription
entityIdstringUnique identifier of the entity to associate the file with
entityTypeFileUploadEntityTypeType of entity ('token', 'campaign', 'business', 'user', etc.)
fileExtensionstringFile extension without dot (e.g., 'jpg', 'png', 'pdf')

Returns

Promise<string>

Promise resolving to signed upload URL

Throws

When entity not found or upload not authorized

Example

try {
  // Get signed upload URL for campaign banner
  const uploadUrl = await sdk.files.getSignedPutUrl(
    'summer-campaign-2024',
    'campaign',
    'png'
  );
  
  console.log('Upload URL generated:', uploadUrl);
  
  // Upload file from input element
  const fileInput = document.getElementById('campaignBanner');
  const file = fileInput.files[0];
  
  if (file) {
    const uploadResponse = await fetch(uploadUrl, {
      method: 'PUT',
      body: file,
      headers: {
        'Content-Type': file.type
      }
    });
    
    if (uploadResponse.ok) {
      console.log('Campaign banner uploaded successfully');
    } else {
      console.log('Upload failed:', uploadResponse.status);
    }
  }
  
} catch (error) {
  console.log('Upload URL generation failed:', error.message);
}

Example

// Upload logo for loyalty token
const tokenLogoUrl = await sdk.files.getSignedPutUrl(
  'loyalty-points-token',
  'token',
  'svg'
);

// Upload SVG file
const svgFile = new File([svgContent], 'token-logo.svg', { type: 'image/svg+xml' });
await fetch(tokenLogoUrl, {
  method: 'PUT',
  body: svgFile,
  headers: { 'Content-Type': 'image/svg+xml' }
});

console.log('Token logo uploaded');

Example

// Upload business profile image
const businessImageUrl = await sdk.files.getSignedPutUrl(
  'partner-hotel-123',
  'business',
  'jpg'
);

// Handle file upload with progress tracking
const file = selectedFile;
const xhr = new XMLHttpRequest();

xhr.upload.addEventListener('progress', (e) => {
  if (e.lengthComputable) {
    const percentComplete = (e.loaded / e.total) * 100;
    console.log(`Upload progress: ${percentComplete}%`);
  }
});

xhr.open('PUT', businessImageUrl);
xhr.send(file);

Defined in

managers/file-manager.ts:173


getSignedGetUrl

▸ getSignedGetUrl(entityId, entityType, expireSeconds?): Promise<string>

Get signed URL for file access

Generates a secure, time-limited URL for accessing/downloading files from cloud storage. URLs automatically expire for security and can be used directly in image tags, download links, or API responses.

Parameters

NameTypeDescription
entityIdstringUnique identifier of the entity the file is associated with
entityTypeFileUploadEntityTypeType of entity ('token', 'campaign', 'business', 'user', etc.)
expireSeconds?numberOptional expiration time in seconds (default: 1 hour)

Returns

Promise<string>

Promise resolving to signed access URL

Throws

When entity or file not found or access denied

Example

try {
  // Get URL for displaying token logo
  const logoUrl = await sdk.files.getSignedGetUrl(
    'vip-status-token',
    'token',
    3600  // 1 hour expiry
  );
  
  // Use in image element
  const img = document.createElement('img');
  img.src = logoUrl;
  img.alt = 'VIP Status Token';
  img.style.width = '64px';
  img.style.height = '64px';
  
  document.getElementById('tokenContainer').appendChild(img);
  
  console.log('Token logo displayed');
  
} catch (error) {
  console.log('Failed to load token logo:', error.message);
  // Show fallback image
  img.src = '/images/default-token.png';
}

Example

// Get download URL for campaign assets
const downloadUrl = await sdk.files.getSignedGetUrl(
  'holiday-campaign',
  'campaign',
  7200  // 2 hours for download
);

// Create download link
const link = document.createElement('a');
link.href = downloadUrl;
link.download = 'holiday-campaign-assets.zip';
link.textContent = 'Download Campaign Assets';

document.body.appendChild(link);

// Or trigger immediate download
link.click();

Example

// Display business gallery images
const businessImages = ['image1', 'image2', 'image3'];
const gallery = document.getElementById('businessGallery');

for (const imageId of businessImages) {
  try {
    const imageUrl = await sdk.files.getSignedGetUrl(
      `business-gallery-${imageId}`,
      'business',
      1800  // 30 minutes
    );
    
    const img = document.createElement('img');
    img.src = imageUrl;
    img.className = 'gallery-image';
    img.loading = 'lazy';
    
    gallery.appendChild(img);
    
  } catch (error) {
    console.log(`Failed to load image ${imageId}:`, error.message);
  }
}

Defined in

managers/file-manager.ts:270


getSignedUrl

▸ getSignedUrl(request): Promise<string>

Get signed URL for any file operation

Flexible method for generating signed URLs with custom parameters for various file operations including uploads, downloads, and deletions. Provides fine-grained control over URL generation and file access permissions.

Parameters

NameTypeDescription
requestSignedUrlRequestSigned URL request configuration

Returns

Promise<string>

Promise resolving to signed URL

Throws

When request parameters are invalid or access denied

Example

// Create upload URL with specific content type and metadata
const advancedUploadUrl = await sdk.files.getSignedUrl({
  operation: 'PUT',
  entityId: 'premium-nft-123',
  entityType: 'token',
  fileExtension: 'png',
  contentType: 'image/png',
  expireSeconds: 300,  // 5 minutes for security
  metadata: {
    creator: 'artist-456',
    collection: 'premium-series',
    rarity: 'legendary'
  }
});

console.log('Advanced upload URL created:', advancedUploadUrl);

Example

// Create very short-lived URL for sensitive document
const secureUrl = await sdk.files.getSignedUrl({
  operation: 'GET',
  entityId: 'compliance-document-789',
  entityType: 'business',
  expireSeconds: 60,  // 1 minute only
  accessLevel: 'admin-only'
});

// Use immediately
window.open(secureUrl, '_blank');

Example

// Generate multiple URLs for batch file operations
const fileOperations = [
  { operation: 'GET', entityId: 'doc1', entityType: 'campaign' },
  { operation: 'GET', entityId: 'doc2', entityType: 'campaign' },
  { operation: 'PUT', entityId: 'doc3', entityType: 'campaign', fileExtension: 'pdf' }
];

const urls = await Promise.all(
  fileOperations.map(op => sdk.files.getSignedUrl(op))
);

console.log('Generated batch URLs:', urls);

Defined in

managers/file-manager.ts:340


optimizeMedia

▸ optimizeMedia(url, width?, height?): Promise<string>

Optimize media file

Creates optimized versions of media files with automatic resizing, format conversion, and compression. Perfect for generating thumbnails, responsive images, and bandwidth-optimized content while maintaining visual quality.

Parameters

NameTypeDescription
urlstringOriginal file URL (can be signed or public URL)
width?numberOptional target width in pixels
height?numberOptional target height in pixels

Returns

Promise<string>

Promise resolving to optimized file URL

Throws

When optimization fails or source file is invalid

Example

// Get original campaign banner URL
const originalUrl = await sdk.files.getSignedGetUrl('campaign-123', 'campaign');

// Generate multiple optimized sizes
const thumbnail = await sdk.files.optimizeMedia(originalUrl, 150, 150);
const medium = await sdk.files.optimizeMedia(originalUrl, 400, 300);
const large = await sdk.files.optimizeMedia(originalUrl, 800, 600);

// Use in responsive image setup
const img = document.createElement('img');
img.src = medium;  // Default size
img.srcset = `
  ${thumbnail} 150w,
  ${medium} 400w,
  ${large} 800w
`;
img.sizes = '(max-width: 400px) 150px, (max-width: 800px) 400px, 800px';

console.log('Responsive image configured');

Example

// Get user profile image and create avatars
const profileUrl = await sdk.files.getSignedGetUrl('user-456', 'user');

// Generate different avatar sizes
const smallAvatar = await sdk.files.optimizeMedia(profileUrl, 32, 32);   // Nav bar
const mediumAvatar = await sdk.files.optimizeMedia(profileUrl, 64, 64);  // Comments
const largeAvatar = await sdk.files.optimizeMedia(profileUrl, 128, 128); // Profile page

// Cache avatar URLs
const avatars = {
  small: smallAvatar,
  medium: mediumAvatar,
  large: largeAvatar
};

localStorage.setItem('userAvatars', JSON.stringify(avatars));
console.log('User avatars generated and cached');

Example

// Generate thumbnails for business product gallery
const productImages = await getBusinessProductImages('business-789');
const thumbnails = [];

for (const productImage of productImages) {
  try {
    const originalUrl = await sdk.files.getSignedGetUrl(
      productImage.id, 
      'business',
      3600
    );
    
    const thumbnail = await sdk.files.optimizeMedia(originalUrl, 200, 200);
    
    thumbnails.push({
      id: productImage.id,
      original: originalUrl,
      thumbnail: thumbnail,
      title: productImage.title
    });
    
  } catch (error) {
    console.log(`Failed to optimize ${productImage.id}:`, error.message);
  }
}

console.log(`Generated ${thumbnails.length} product thumbnails`);

// Display thumbnail gallery
thumbnails.forEach(item => {
  const img = document.createElement('img');
  img.src = item.thumbnail;
  img.alt = item.title;
  img.onclick = () => showLightbox(item.original);
  gallery.appendChild(img);
});

Example

// Optimize with automatic format selection
const tokenIcon = await sdk.files.getSignedGetUrl('token-123', 'token');

// System automatically chooses best format (WebP, AVIF, etc.)
const optimizedIcon = await sdk.files.optimizeMedia(tokenIcon, 48, 48);

console.log('Optimized token icon (auto format):', optimizedIcon);

// Use in token display
document.querySelector('.token-icon').src = optimizedIcon;

Defined in

managers/file-manager.ts:455


getFileService

▸ getFileService(): FileService

Get the full file service for advanced operations

Provides access to the complete FileService instance for advanced file operations, batch processing, storage analytics, and operations not covered by the high-level manager methods.

Returns

FileService

FileService instance with full API access

Example

const fileService = sdk.files.getFileService();

// Access storage analytics
const storageStats = await fileService.getStorageAnalytics();
console.log('Storage usage:', storageStats.totalSize);

// Access batch file operations
const batchResult = await fileService.batchDeleteFiles(['file1', 'file2', 'file3']);

// Access file metadata management
const metadata = await fileService.getFileMetadata('entity-123', 'campaign');

// Access advanced optimization options
const advancedOptimization = await fileService.optimizeMediaAdvanced(url, {
  width: 400,
  height: 300,
  quality: 85,
  format: 'webp',
  progressive: true,
  watermark: 'brand-logo'
});

// Access file upload monitoring
const uploadProgress = fileService.monitorUploadProgress('upload-session-123');
uploadProgress.on('progress', (percent) => {
  console.log(`Upload: ${percent}%`);
});

Defined in

managers/file-manager.ts:499