Client API
Complete API reference for the Torrin client library.
createTorrinClient(options)
Creates a new Torrin client instance.
import { createTorrinClient } from '@torrin-kit/client';
const torrin = createTorrinClient({
endpoint: 'http://localhost:3000/api/uploads',
defaultChunkSize: 5 * 1024 * 1024,
maxConcurrency: 3,
retryAttempts: 5,
retryDelay: 1000,
headers: async () => ({
Authorization: `Bearer ${await getToken()}`,
}),
resumeStore: createLocalStorageResumeStore(),
});Options
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
endpoint | string | Yes | - | Server endpoint URL for upload operations |
defaultChunkSize | number | No | 1048576 (1MB) | Default chunk size in bytes |
maxConcurrency | number | No | 3 | Maximum concurrent chunk uploads |
retryAttempts | number | No | 3 | Number of retries for failed chunks |
retryDelay | number | No | 1000 | Initial delay in ms for retry (exponential backoff) |
headers | () => Record<string, string> | Promise<Record<string, string>> | No | - | Function returning custom headers for authentication |
resumeStore | TorrinResumeStore | No | - | Resume store for persistence (e.g., localStorage) |
Returns
TorrinClient instance
TorrinClient
createUpload(options)
Creates a new upload instance for a file.
const upload = torrin.createUpload({
file: myFile,
chunkSize: 10 * 1024 * 1024,
metadata: {
userId: '123',
projectId: 'abc',
},
});Options
| Option | Type | Required | Description |
|---|---|---|---|
file | File | Blob | Yes* | File or Blob to upload (browser) |
buffer | ArrayBuffer | Uint8Array | Yes* | Buffer to upload (Node.js) |
fileName | string | No | File name (required if using buffer) |
fileSize | number | No | File size in bytes (required if using buffer) |
mimeType | string | No | MIME type of the file |
chunkSize | number | No | Override default chunk size for this upload |
metadata | Record<string, any> | No | Custom metadata to send to server |
uploadId | string | No | Existing uploadId to resume |
*Either file or buffer is required
Returns
TorrinUpload instance
TorrinUpload
Upload instance with methods for control and event listening.
Properties
| Property | Type | Description |
|---|---|---|
uploadId | string | null | Upload ID from server (null until initialized) |
status | UploadClientStatus | Current upload status |
Methods
start(): Promise<TorrinCompleteResult>
Starts or resumes the upload.
const result = await upload.start();
console.log('Uploaded to:', result.location);Returns: Promise resolving to TorrinCompleteResult
Throws: TorrinError if upload fails
pause(): void
Pauses the upload. Can be resumed later with resume() or start().
upload.pause();resume(): void
Resumes a paused upload.
upload.resume();cancel(): Promise<void>
Cancels the upload and notifies the server to clean up.
await upload.cancel();Returns: Promise that resolves when cancellation is complete
on(event, handler): this
Registers an event listener.
upload.on('progress', (progress) => {
console.log(`${progress.percentage}%`);
});
upload.on('status', (status) => {
console.log('Status:', status);
});
upload.on('error', (error) => {
console.error('Error:', error);
});Parameters:
event: Event name ('progress','status', or'error')handler: Event handler function
Returns: Upload instance (for chaining)
off(event, handler): this
Removes an event listener.
const handler = (p) => console.log(p.percentage);
upload.on('progress', handler);
upload.off('progress', handler);Parameters:
event: Event namehandler: Handler function to remove
Returns: Upload instance (for chaining)
Events
progress
Emitted during upload with progress information.
upload.on('progress', (progress: TorrinProgress) => {
console.log(`${progress.percentage}% complete`);
console.log(`${progress.chunksCompleted}/${progress.totalChunks} chunks`);
console.log(`${progress.bytesUploaded}/${progress.totalBytes} bytes`);
});Payload: TorrinProgress
| Field | Type | Description |
|---|---|---|
uploadId | string | Upload ID |
percentage | number | Progress percentage (0-100) |
bytesUploaded | number | Bytes uploaded so far |
totalBytes | number | Total file size in bytes |
chunksCompleted | number | Number of chunks successfully uploaded |
totalChunks | number | Total number of chunks |
chunkIndex | number (optional) | Current chunk being uploaded |
status
Emitted when upload status changes.
upload.on('status', (status: UploadClientStatus) => {
console.log('Status changed to:', status);
});Payload: UploadClientStatus
Possible values:
'idle'- Upload not started'initializing'- Initializing upload session with server'uploading'- Actively uploading chunks'paused'- Upload paused by user'completing'- Finalizing upload on server'completed'- Upload finished successfully'failed'- Upload failed'canceled'- Upload canceled by user
error
Emitted when an error occurs.
upload.on('error', (error: TorrinError) => {
console.error(`Error [${error.code}]:`, error.message);
console.error('Details:', error.details);
});Payload: TorrinError
| Field | Type | Description |
|---|---|---|
message | string | Error message |
code | TorrinErrorCode | Error code (e.g., 'NETWORK_ERROR') |
statusCode | number | HTTP status code |
details | Record<string, any> (optional) | Additional error details |
Types
TorrinCompleteResult
Result returned when upload completes successfully.
interface TorrinCompleteResult {
uploadId: string;
status: 'completed';
location: TorrinStorageLocation;
metadata?: Record<string, any>;
}TorrinStorageLocation
Information about where the file was stored.
interface TorrinStorageLocation {
type: string; // 'local', 's3', etc.
path?: string; // For local storage
bucket?: string; // For S3
key?: string; // For S3
url?: string; // Public URL if available
[key: string]: any; // Custom fields
}Resume Stores
createLocalStorageResumeStore()
Creates a resume store using browser localStorage.
import { createLocalStorageResumeStore } from '@torrin-kit/client';
const resumeStore = createLocalStorageResumeStore();createInMemoryResumeStore()
Creates an in-memory resume store (for testing).
import { createInMemoryResumeStore } from '@torrin-kit/client';
const resumeStore = createInMemoryResumeStore();Custom Resume Store
Implement TorrinResumeStore interface:
interface TorrinResumeStore {
save(uploadId: string, state: TorrinUploadState): Promise<void> | void;
load(uploadId: string): Promise<TorrinUploadState | null> | TorrinUploadState | null;
remove(uploadId: string): Promise<void> | void;
findByFile?(fileKey: string): Promise<TorrinUploadState | null> | TorrinUploadState | null;
saveFileKey?(fileKey: string, uploadId: string): Promise<void> | void;
removeFileKey?(fileKey: string): Promise<void> | void;
}Examples
Basic Upload
const torrin = createTorrinClient({
endpoint: '/api/uploads',
});
const upload = torrin.createUpload({ file: myFile });
upload.on('progress', (p) => {
console.log(`${p.percentage}%`);
});
const result = await upload.start();
console.log('Done:', result.location);With Authentication
const torrin = createTorrinClient({
endpoint: '/api/uploads',
headers: async () => {
const token = await getAccessToken();
return { Authorization: `Bearer ${token}` };
},
});With Resume Support
const torrin = createTorrinClient({
endpoint: '/api/uploads',
resumeStore: createLocalStorageResumeStore(),
});
// Upload automatically resumes if interrupted
const upload = torrin.createUpload({ file: myFile });
await upload.start();Pause/Resume/Cancel
const upload = torrin.createUpload({ file: myFile });
upload.start();
// Later...
upload.pause();
upload.resume();
await upload.cancel();Next Steps
- Server API - Server-side API reference
- Configuration - Configure client options
- Error Handling - Handle errors gracefully