0
# HTTP Utilities
1
2
Low-level HTTP access and utility functions for custom requests, direct server communication, and adapter validation in the PouchDB HTTP adapter.
3
4
## Capabilities
5
6
### Direct HTTP Access
7
8
Provides direct access to the underlying HTTP client for custom requests to the remote database server.
9
10
```javascript { .api }
11
/**
12
* Make direct HTTP requests to the database server
13
* @param path - URL path relative to database URL, or absolute path from server root
14
* @param options - Fetch options including method, headers, and body
15
* @returns Promise resolving to fetch Response object
16
*/
17
api.fetch(path, options): Promise<Response>;
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
// Get server information
24
db.fetch('/', {
25
method: 'GET'
26
}).then(response => response.json())
27
.then(info => {
28
console.log('CouchDB version:', info.version);
29
console.log('Server UUID:', info.uuid);
30
console.log('Vendor:', info.vendor);
31
})
32
.catch(err => {
33
console.error('Error getting server info:', err);
34
});
35
36
// Get database statistics
37
db.fetch('', {
38
method: 'GET'
39
}).then(response => response.json())
40
.then(dbInfo => {
41
console.log('Database name:', dbInfo.db_name);
42
console.log('Document count:', dbInfo.doc_count);
43
console.log('Data size:', dbInfo.data_size);
44
console.log('Disk size:', dbInfo.disk_size);
45
});
46
47
// Create custom design document
48
const designDoc = {
49
_id: '_design/users',
50
views: {
51
by_email: {
52
map: 'function(doc) { if (doc.email) emit(doc.email, doc); }'
53
},
54
active: {
55
map: 'function(doc) { if (doc.active) emit(doc._id, doc); }'
56
}
57
}
58
};
59
60
db.fetch('_design/users', {
61
method: 'PUT',
62
headers: {
63
'Content-Type': 'application/json'
64
},
65
body: JSON.stringify(designDoc)
66
}).then(response => response.json())
67
.then(result => {
68
console.log('Design document created:', result.rev);
69
})
70
.catch(err => {
71
console.error('Error creating design document:', err);
72
});
73
```
74
75
### Custom Query Operations
76
77
Use direct HTTP access for advanced CouchDB features not exposed through standard PouchDB methods.
78
79
```javascript { .api }
80
/**
81
* Execute custom queries and operations via direct HTTP access
82
* @param path - Database path for the operation
83
* @param options - HTTP options with query parameters
84
* @returns Promise with server response
85
*/
86
api.fetch(path, options): Promise<Response>;
87
```
88
89
**Usage Examples:**
90
91
```javascript
92
// Query a view with custom options
93
db.fetch('_design/users/_view/by_email?limit=10&include_docs=true', {
94
method: 'GET'
95
}).then(response => response.json())
96
.then(result => {
97
console.log('View results:', result.rows);
98
result.rows.forEach(row => {
99
console.log('Email:', row.key, 'User:', row.doc.name);
100
});
101
});
102
103
// Execute a temporary view
104
const tempView = {
105
map: 'function(doc) { if (doc.type === "user" && doc.created) emit(doc.created, doc.name); }'
106
};
107
108
db.fetch('_temp_view', {
109
method: 'POST',
110
headers: {
111
'Content-Type': 'application/json'
112
},
113
body: JSON.stringify(tempView)
114
}).then(response => response.json())
115
.then(result => {
116
console.log('Temporary view results:', result.rows);
117
});
118
119
// Bulk operations with custom parameters
120
const bulkRequest = {
121
docs: [
122
{ _id: 'test1', name: 'Test Document 1' },
123
{ _id: 'test2', name: 'Test Document 2' }
124
],
125
new_edits: false
126
};
127
128
db.fetch('_bulk_docs', {
129
method: 'POST',
130
headers: {
131
'Content-Type': 'application/json'
132
},
133
body: JSON.stringify(bulkRequest)
134
}).then(response => response.json())
135
.then(results => {
136
console.log('Bulk operation results:', results);
137
});
138
```
139
140
### Security and Database Management
141
142
Access CouchDB security and administrative features through direct HTTP calls.
143
144
```javascript { .api }
145
/**
146
* Access security and administrative features
147
* @param path - Administrative endpoint path
148
* @param options - HTTP options with administrative data
149
* @returns Promise with administrative operation result
150
*/
151
api.fetch(path, options): Promise<Response>;
152
```
153
154
**Usage Examples:**
155
156
```javascript
157
// Get database security settings
158
db.fetch('_security', {
159
method: 'GET'
160
}).then(response => response.json())
161
.then(security => {
162
console.log('Database admins:', security.admins);
163
console.log('Database members:', security.members);
164
})
165
.catch(err => {
166
if (err.status === 401) {
167
console.log('Insufficient permissions to view security settings');
168
} else {
169
console.error('Error getting security settings:', err);
170
}
171
});
172
173
// Update database security (requires admin privileges)
174
const securityDoc = {
175
admins: {
176
names: ['admin1', 'admin2'],
177
roles: ['admin']
178
},
179
members: {
180
names: ['user1', 'user2'],
181
roles: ['editor']
182
}
183
};
184
185
db.fetch('_security', {
186
method: 'PUT',
187
headers: {
188
'Content-Type': 'application/json'
189
},
190
body: JSON.stringify(securityDoc)
191
}).then(response => response.json())
192
.then(result => {
193
console.log('Security updated:', result.ok);
194
})
195
.catch(err => {
196
console.error('Error updating security:', err);
197
});
198
199
// Get active tasks (replication, compaction, etc.)
200
db.fetch('/_active_tasks', {
201
method: 'GET'
202
}).then(response => response.json())
203
.then(tasks => {
204
console.log('Active server tasks:', tasks);
205
});
206
```
207
208
### Advanced Replication Control
209
210
Use direct HTTP access for advanced replication configuration and monitoring.
211
212
```javascript { .api }
213
/**
214
* Advanced replication control via HTTP API
215
* @param path - Replication endpoint path
216
* @param options - Replication configuration options
217
* @returns Promise with replication result
218
*/
219
api.fetch(path, options): Promise<Response>;
220
```
221
222
**Usage Examples:**
223
224
```javascript
225
// Start continuous replication
226
const replicationDoc = {
227
source: 'source-database',
228
target: 'target-database',
229
continuous: true,
230
filter: 'myapp/important',
231
query_params: {
232
priority: 'high'
233
}
234
};
235
236
db.fetch('/_replicate', {
237
method: 'POST',
238
headers: {
239
'Content-Type': 'application/json'
240
},
241
body: JSON.stringify(replicationDoc)
242
}).then(response => response.json())
243
.then(result => {
244
console.log('Replication started:', result);
245
});
246
247
// Check replication status
248
db.fetch('/_active_tasks', {
249
method: 'GET'
250
}).then(response => response.json())
251
.then(tasks => {
252
const replicationTasks = tasks.filter(task => task.type === 'replication');
253
replicationTasks.forEach(task => {
254
console.log(`Replication: ${task.source} -> ${task.target}`);
255
console.log(`Progress: ${task.progress}%`);
256
console.log(`Documents processed: ${task.docs_written}/${task.docs_read}`);
257
});
258
});
259
```
260
261
### Adapter Validation
262
263
Static method to validate adapter compatibility and availability.
264
265
```javascript { .api }
266
/**
267
* Validate that the HTTP adapter is available and functional
268
* @returns Always returns true for HTTP adapter
269
*/
270
HttpPouch.valid(): boolean;
271
```
272
273
**Usage Examples:**
274
275
```javascript
276
// Check if HTTP adapter is available
277
if (HttpPouch.valid()) {
278
console.log('HTTP adapter is available');
279
280
// Register the adapter with PouchDB
281
PouchDB.plugin(HttpAdapter);
282
283
// Create database connection
284
const db = new PouchDB('http://localhost:5984/mydb');
285
} else {
286
console.error('HTTP adapter is not available');
287
}
288
289
// Programmatically check available adapters
290
const availableAdapters = [];
291
292
if (HttpPouch && HttpPouch.valid()) {
293
availableAdapters.push('http');
294
}
295
296
console.log('Available adapters:', availableAdapters);
297
```
298
299
## Error Handling and Response Processing
300
301
### HTTP Response Processing
302
303
```javascript
304
// Handle different HTTP response types
305
async function processHttpResponse(response) {
306
const contentType = response.headers.get('content-type');
307
308
if (contentType && contentType.includes('application/json')) {
309
const data = await response.json();
310
311
if (!response.ok) {
312
// Handle CouchDB error response
313
const error = new Error(data.reason || data.error);
314
error.status = response.status;
315
error.name = data.error;
316
throw error;
317
}
318
319
return data;
320
} else if (contentType && contentType.startsWith('text/')) {
321
return await response.text();
322
} else {
323
// Binary data
324
return await response.blob();
325
}
326
}
327
328
// Example usage with error handling
329
db.fetch('_design/users/_view/by_email')
330
.then(processHttpResponse)
331
.then(data => {
332
console.log('View data:', data);
333
})
334
.catch(err => {
335
if (err.status === 404) {
336
console.log('View not found, creating design document...');
337
} else if (err.status === 401) {
338
console.log('Authentication required');
339
} else {
340
console.error('Request failed:', err.message);
341
}
342
});
343
```
344
345
### Custom Headers and Authentication
346
347
```javascript
348
// Add custom headers to requests
349
const customHeaders = {
350
'X-Custom-Header': 'MyValue',
351
'User-Agent': 'MyApp/1.0'
352
};
353
354
db.fetch('_all_docs?limit=5', {
355
method: 'GET',
356
headers: customHeaders
357
}).then(response => response.json())
358
.then(result => {
359
console.log('Documents with custom headers:', result.rows);
360
});
361
362
// Override authentication for specific requests
363
db.fetch('/_session', {
364
method: 'POST',
365
headers: {
366
'Content-Type': 'application/json'
367
},
368
body: JSON.stringify({
369
name: 'username',
370
password: 'password'
371
})
372
}).then(response => response.json())
373
.then(session => {
374
console.log('Session created:', session);
375
});
376
```
377
378
## Types
379
380
```javascript { .api }
381
// Fetch options (extends standard fetch API)
382
interface FetchOptions {
383
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD';
384
headers?: { [key: string]: string } | Headers;
385
body?: string | Blob | BufferSource | FormData | URLSearchParams;
386
credentials?: 'omit' | 'same-origin' | 'include';
387
cache?: 'default' | 'no-store' | 'reload' | 'no-cache' | 'force-cache';
388
redirect?: 'follow' | 'error' | 'manual';
389
signal?: AbortSignal;
390
}
391
392
// HTTP Response (standard fetch Response)
393
interface Response {
394
ok: boolean;
395
status: number;
396
statusText: string;
397
headers: Headers;
398
url: string;
399
json(): Promise<any>;
400
text(): Promise<string>;
401
blob(): Promise<Blob>;
402
arrayBuffer(): Promise<ArrayBuffer>;
403
clone(): Response;
404
}
405
406
// CouchDB error response
407
interface CouchDBError {
408
error: string;
409
reason: string;
410
}
411
412
// Server info response
413
interface ServerInfo {
414
couchdb: string;
415
version: string;
416
uuid: string;
417
vendor: {
418
name: string;
419
version?: string;
420
};
421
}
422
423
// Database info response (from direct fetch)
424
interface DatabaseInfoResponse {
425
db_name: string;
426
doc_count: number;
427
doc_del_count: number;
428
update_seq: string | number;
429
purge_seq: number;
430
compact_running: boolean;
431
disk_size: number;
432
data_size: number;
433
instance_start_time: string;
434
disk_format_version: number;
435
committed_update_seq: string | number;
436
}
437
438
// Security document
439
interface SecurityDocument {
440
admins: {
441
names: string[];
442
roles: string[];
443
};
444
members: {
445
names: string[];
446
roles: string[];
447
};
448
}
449
450
// Active task info
451
interface ActiveTask {
452
type: 'replication' | 'database_compaction' | 'view_compaction' | 'indexer';
453
task: string;
454
status: string;
455
progress?: number;
456
source?: string;
457
target?: string;
458
docs_read?: number;
459
docs_written?: number;
460
doc_write_failures?: number;
461
started_on: number;
462
updated_on: number;
463
}
464
```