PouchDB adapter using HTTP for remote CouchDB connections and database operations
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Low-level HTTP access and utility functions for custom requests, direct server communication, and adapter validation in the PouchDB HTTP adapter.
Provides direct access to the underlying HTTP client for custom requests to the remote database server.
/**
* Make direct HTTP requests to the database server
* @param path - URL path relative to database URL, or absolute path from server root
* @param options - Fetch options including method, headers, and body
* @returns Promise resolving to fetch Response object
*/
api.fetch(path, options): Promise<Response>;Usage Examples:
// Get server information
db.fetch('/', {
method: 'GET'
}).then(response => response.json())
.then(info => {
console.log('CouchDB version:', info.version);
console.log('Server UUID:', info.uuid);
console.log('Vendor:', info.vendor);
})
.catch(err => {
console.error('Error getting server info:', err);
});
// Get database statistics
db.fetch('', {
method: 'GET'
}).then(response => response.json())
.then(dbInfo => {
console.log('Database name:', dbInfo.db_name);
console.log('Document count:', dbInfo.doc_count);
console.log('Data size:', dbInfo.data_size);
console.log('Disk size:', dbInfo.disk_size);
});
// Create custom design document
const designDoc = {
_id: '_design/users',
views: {
by_email: {
map: 'function(doc) { if (doc.email) emit(doc.email, doc); }'
},
active: {
map: 'function(doc) { if (doc.active) emit(doc._id, doc); }'
}
}
};
db.fetch('_design/users', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(designDoc)
}).then(response => response.json())
.then(result => {
console.log('Design document created:', result.rev);
})
.catch(err => {
console.error('Error creating design document:', err);
});Use direct HTTP access for advanced CouchDB features not exposed through standard PouchDB methods.
/**
* Execute custom queries and operations via direct HTTP access
* @param path - Database path for the operation
* @param options - HTTP options with query parameters
* @returns Promise with server response
*/
api.fetch(path, options): Promise<Response>;Usage Examples:
// Query a view with custom options
db.fetch('_design/users/_view/by_email?limit=10&include_docs=true', {
method: 'GET'
}).then(response => response.json())
.then(result => {
console.log('View results:', result.rows);
result.rows.forEach(row => {
console.log('Email:', row.key, 'User:', row.doc.name);
});
});
// Execute a temporary view
const tempView = {
map: 'function(doc) { if (doc.type === "user" && doc.created) emit(doc.created, doc.name); }'
};
db.fetch('_temp_view', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(tempView)
}).then(response => response.json())
.then(result => {
console.log('Temporary view results:', result.rows);
});
// Bulk operations with custom parameters
const bulkRequest = {
docs: [
{ _id: 'test1', name: 'Test Document 1' },
{ _id: 'test2', name: 'Test Document 2' }
],
new_edits: false
};
db.fetch('_bulk_docs', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(bulkRequest)
}).then(response => response.json())
.then(results => {
console.log('Bulk operation results:', results);
});Access CouchDB security and administrative features through direct HTTP calls.
/**
* Access security and administrative features
* @param path - Administrative endpoint path
* @param options - HTTP options with administrative data
* @returns Promise with administrative operation result
*/
api.fetch(path, options): Promise<Response>;Usage Examples:
// Get database security settings
db.fetch('_security', {
method: 'GET'
}).then(response => response.json())
.then(security => {
console.log('Database admins:', security.admins);
console.log('Database members:', security.members);
})
.catch(err => {
if (err.status === 401) {
console.log('Insufficient permissions to view security settings');
} else {
console.error('Error getting security settings:', err);
}
});
// Update database security (requires admin privileges)
const securityDoc = {
admins: {
names: ['admin1', 'admin2'],
roles: ['admin']
},
members: {
names: ['user1', 'user2'],
roles: ['editor']
}
};
db.fetch('_security', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(securityDoc)
}).then(response => response.json())
.then(result => {
console.log('Security updated:', result.ok);
})
.catch(err => {
console.error('Error updating security:', err);
});
// Get active tasks (replication, compaction, etc.)
db.fetch('/_active_tasks', {
method: 'GET'
}).then(response => response.json())
.then(tasks => {
console.log('Active server tasks:', tasks);
});Use direct HTTP access for advanced replication configuration and monitoring.
/**
* Advanced replication control via HTTP API
* @param path - Replication endpoint path
* @param options - Replication configuration options
* @returns Promise with replication result
*/
api.fetch(path, options): Promise<Response>;Usage Examples:
// Start continuous replication
const replicationDoc = {
source: 'source-database',
target: 'target-database',
continuous: true,
filter: 'myapp/important',
query_params: {
priority: 'high'
}
};
db.fetch('/_replicate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(replicationDoc)
}).then(response => response.json())
.then(result => {
console.log('Replication started:', result);
});
// Check replication status
db.fetch('/_active_tasks', {
method: 'GET'
}).then(response => response.json())
.then(tasks => {
const replicationTasks = tasks.filter(task => task.type === 'replication');
replicationTasks.forEach(task => {
console.log(`Replication: ${task.source} -> ${task.target}`);
console.log(`Progress: ${task.progress}%`);
console.log(`Documents processed: ${task.docs_written}/${task.docs_read}`);
});
});Static method to validate adapter compatibility and availability.
/**
* Validate that the HTTP adapter is available and functional
* @returns Always returns true for HTTP adapter
*/
HttpPouch.valid(): boolean;Usage Examples:
// Check if HTTP adapter is available
if (HttpPouch.valid()) {
console.log('HTTP adapter is available');
// Register the adapter with PouchDB
PouchDB.plugin(HttpAdapter);
// Create database connection
const db = new PouchDB('http://localhost:5984/mydb');
} else {
console.error('HTTP adapter is not available');
}
// Programmatically check available adapters
const availableAdapters = [];
if (HttpPouch && HttpPouch.valid()) {
availableAdapters.push('http');
}
console.log('Available adapters:', availableAdapters);// Handle different HTTP response types
async function processHttpResponse(response) {
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
const data = await response.json();
if (!response.ok) {
// Handle CouchDB error response
const error = new Error(data.reason || data.error);
error.status = response.status;
error.name = data.error;
throw error;
}
return data;
} else if (contentType && contentType.startsWith('text/')) {
return await response.text();
} else {
// Binary data
return await response.blob();
}
}
// Example usage with error handling
db.fetch('_design/users/_view/by_email')
.then(processHttpResponse)
.then(data => {
console.log('View data:', data);
})
.catch(err => {
if (err.status === 404) {
console.log('View not found, creating design document...');
} else if (err.status === 401) {
console.log('Authentication required');
} else {
console.error('Request failed:', err.message);
}
});// Add custom headers to requests
const customHeaders = {
'X-Custom-Header': 'MyValue',
'User-Agent': 'MyApp/1.0'
};
db.fetch('_all_docs?limit=5', {
method: 'GET',
headers: customHeaders
}).then(response => response.json())
.then(result => {
console.log('Documents with custom headers:', result.rows);
});
// Override authentication for specific requests
db.fetch('/_session', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'username',
password: 'password'
})
}).then(response => response.json())
.then(session => {
console.log('Session created:', session);
});// Fetch options (extends standard fetch API)
interface FetchOptions {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD';
headers?: { [key: string]: string } | Headers;
body?: string | Blob | BufferSource | FormData | URLSearchParams;
credentials?: 'omit' | 'same-origin' | 'include';
cache?: 'default' | 'no-store' | 'reload' | 'no-cache' | 'force-cache';
redirect?: 'follow' | 'error' | 'manual';
signal?: AbortSignal;
}
// HTTP Response (standard fetch Response)
interface Response {
ok: boolean;
status: number;
statusText: string;
headers: Headers;
url: string;
json(): Promise<any>;
text(): Promise<string>;
blob(): Promise<Blob>;
arrayBuffer(): Promise<ArrayBuffer>;
clone(): Response;
}
// CouchDB error response
interface CouchDBError {
error: string;
reason: string;
}
// Server info response
interface ServerInfo {
couchdb: string;
version: string;
uuid: string;
vendor: {
name: string;
version?: string;
};
}
// Database info response (from direct fetch)
interface DatabaseInfoResponse {
db_name: string;
doc_count: number;
doc_del_count: number;
update_seq: string | number;
purge_seq: number;
compact_running: boolean;
disk_size: number;
data_size: number;
instance_start_time: string;
disk_format_version: number;
committed_update_seq: string | number;
}
// Security document
interface SecurityDocument {
admins: {
names: string[];
roles: string[];
};
members: {
names: string[];
roles: string[];
};
}
// Active task info
interface ActiveTask {
type: 'replication' | 'database_compaction' | 'view_compaction' | 'indexer';
task: string;
status: string;
progress?: number;
source?: string;
target?: string;
docs_read?: number;
docs_written?: number;
doc_write_failures?: number;
started_on: number;
updated_on: number;
}Install with Tessl CLI
npx tessl i tessl/npm-pouchdb-adapter-http