0
# OrbitDB Factory
1
2
The OrbitDB factory creates and manages OrbitDB instances with IPFS integration and peer synchronization. It serves as the main entry point for creating distributed databases.
3
4
## Capabilities
5
6
### Creating OrbitDB Instances
7
8
Creates an OrbitDB instance with the provided IPFS instance and configuration.
9
10
```javascript { .api }
11
/**
12
* Creates an OrbitDB instance
13
* @param params Configuration parameters
14
* @param params.ipfs IPFS instance (required)
15
* @param params.id Identity ID (optional, auto-generated if not provided)
16
* @param params.identity Identity instance or provider configuration
17
* @param params.identities Identities system instance
18
* @param params.directory Storage directory (default: './orbitdb')
19
* @returns Promise resolving to OrbitDB instance
20
* @throws "IPFS instance is a required argument" if no IPFS instance provided
21
*/
22
function createOrbitDB(params: {
23
ipfs: IPFS;
24
id?: string;
25
identity?: Identity | { provider: IdentityProvider };
26
identities?: Identities;
27
directory?: string;
28
}): Promise<OrbitDB>;
29
```
30
31
**Usage Examples:**
32
33
```javascript
34
import { createHelia } from 'helia';
35
import { createOrbitDB } from '@orbitdb/core';
36
37
// Basic usage with Helia IPFS
38
const ipfs = await createHelia();
39
const orbitdb = await createOrbitDB({ ipfs });
40
41
// With custom directory
42
const orbitdb2 = await createOrbitDB({
43
ipfs,
44
directory: './my-orbitdb-data'
45
});
46
47
// With custom identity ID
48
const orbitdb3 = await createOrbitDB({
49
ipfs,
50
id: 'my-unique-id'
51
});
52
```
53
54
### OrbitDB Instance Interface
55
56
The OrbitDB instance provides methods for database management and system control.
57
58
```javascript { .api }
59
interface OrbitDB {
60
/** Opens or creates a database */
61
open(name: string, options?: DatabaseOptions): Promise<Database>;
62
/** Stops the OrbitDB instance and cleans up resources */
63
stop(): Promise<void>;
64
/** The IPFS instance used by this OrbitDB */
65
ipfs: IPFS;
66
/** The directory where OrbitDB stores data */
67
directory: string;
68
/** The keystore instance for cryptographic operations */
69
keystore: KeyStore;
70
/** The identities system for identity management */
71
identities: Identities;
72
/** The current identity used by this OrbitDB instance */
73
identity: Identity;
74
/** The peer ID of this OrbitDB instance */
75
peerId: PeerId;
76
}
77
```
78
79
### Opening Databases
80
81
Creates or opens databases with various configuration options.
82
83
```javascript { .api }
84
/**
85
* Opens or creates a database
86
* @param name Database name or address
87
* @param options Database configuration options
88
* @returns Promise resolving to Database instance
89
*/
90
open(name: string, options?: DatabaseOptions): Promise<Database>;
91
92
interface DatabaseOptions {
93
/** Database type (default: 'events') */
94
type?: string;
95
/** Database constructor function */
96
Database?: DatabaseConstructor;
97
/** Access controller constructor */
98
AccessController?: AccessControllerConstructor;
99
/** Storage directory for this database */
100
directory?: string;
101
/** Database metadata */
102
meta?: object;
103
/** Storage backend for log heads */
104
headsStorage?: Storage;
105
/** Storage backend for log entries */
106
entryStorage?: Storage;
107
/** Storage backend for database index */
108
indexStorage?: Storage;
109
/** Maximum distance between references (default: 16) */
110
referencesCount?: number;
111
/** Enable automatic peer synchronization (alias: sync) */
112
syncAutomatically?: boolean;
113
/** Callback fired when entries are added */
114
onUpdate?: (entry: Entry) => void;
115
/** Encryption configuration */
116
encryption?: {
117
encryptFn: (data: any) => any;
118
decryptFn: (data: any) => any;
119
};
120
}
121
```
122
123
**Usage Examples:**
124
125
```javascript
126
import { createHelia } from 'helia';
127
import { createOrbitDB, Documents, KeyValue } from '@orbitdb/core';
128
129
const ipfs = await createHelia();
130
const orbitdb = await createOrbitDB({ ipfs });
131
132
// Open default Events database
133
const events = await orbitdb.open('my-events');
134
135
// Open Documents database with custom index
136
const docs = await orbitdb.open('my-docs', {
137
Database: Documents({ indexBy: 'id' })
138
});
139
140
// Open KeyValue database with custom metadata
141
const kv = await orbitdb.open('my-kv', {
142
Database: KeyValue(),
143
meta: { description: 'My key-value store' }
144
});
145
146
// Open database with custom access control
147
const privateDb = await orbitdb.open('private-db', {
148
AccessController: OrbitDBAccessController({ write: ['alice', 'bob'] })
149
});
150
151
// Open database with automatic sync
152
const syncedDb = await orbitdb.open('synced-db', {
153
syncAutomatically: true,
154
onUpdate: (entry) => console.log('New entry:', entry)
155
});
156
```
157
158
### Database Address Handling
159
160
OrbitDB can open databases using either names or full addresses.
161
162
```javascript
163
// Open by name (creates new database or opens existing)
164
const db1 = await orbitdb.open('my-database');
165
166
// Open by full OrbitDB address
167
const address = '/orbitdb/zdpuAkstgbTVGHQmMi5TC84auhJ8rL5qoaNEtXo2d5PHXs2To';
168
const db2 = await orbitdb.open(address);
169
170
// Get database address for sharing
171
const dbAddress = db1.address.toString();
172
console.log('Share this address:', dbAddress);
173
```
174
175
### Identity Configuration
176
177
OrbitDB instances can be configured with custom identities for cryptographic operations.
178
179
```javascript
180
import { createOrbitDB, Identities, PublicKeyIdentityProvider } from '@orbitdb/core';
181
182
// Using default identity (auto-generated)
183
const orbitdb1 = await createOrbitDB({ ipfs });
184
185
// Using custom identity provider
186
const identities = await Identities({ ipfs });
187
const identity = await identities.createIdentity({
188
provider: PublicKeyIdentityProvider()
189
});
190
191
const orbitdb2 = await createOrbitDB({
192
ipfs,
193
identity
194
});
195
196
// Using pre-created identities instance
197
const orbitdb3 = await createOrbitDB({
198
ipfs,
199
identities
200
});
201
```
202
203
### Storage Configuration
204
205
Configure custom storage backends for different components.
206
207
```javascript
208
import {
209
createOrbitDB,
210
LevelStorage,
211
MemoryStorage,
212
ComposedStorage
213
} from '@orbitdb/core';
214
215
const ipfs = await createHelia();
216
const orbitdb = await createOrbitDB({ ipfs });
217
218
// Configure storage for specific database
219
const db = await orbitdb.open('my-db', {
220
headsStorage: await LevelStorage({ path: './heads' }),
221
entryStorage: await MemoryStorage(),
222
indexStorage: await ComposedStorage([
223
await MemoryStorage(),
224
await LevelStorage({ path: './index' })
225
])
226
});
227
```
228
229
### Lifecycle Management
230
231
Proper lifecycle management ensures clean shutdown and resource cleanup.
232
233
```javascript
234
const ipfs = await createHelia();
235
const orbitdb = await createOrbitDB({ ipfs });
236
237
try {
238
// Use OrbitDB
239
const db = await orbitdb.open('my-db');
240
await db.add('Hello World');
241
await db.close();
242
} finally {
243
// Always clean up
244
await orbitdb.stop();
245
await ipfs.stop();
246
}
247
```
248
249
### Error Handling
250
251
Common errors and how to handle them:
252
253
```javascript
254
import { createOrbitDB } from '@orbitdb/core';
255
256
try {
257
// Missing IPFS instance
258
const orbitdb = await createOrbitDB({});
259
} catch (error) {
260
console.error(error.message); // "IPFS instance is a required argument."
261
}
262
263
try {
264
const ipfs = await createHelia();
265
const orbitdb = await createOrbitDB({ ipfs });
266
267
// Invalid database address
268
const db = await orbitdb.open('invalid-address');
269
} catch (error) {
270
console.error('Failed to open database:', error.message);
271
}
272
```
273
274
## Integration with Helia and Libp2p
275
276
OrbitDB requires proper IPFS and Libp2p configuration for networking and storage:
277
278
```javascript
279
import { createHelia } from 'helia';
280
import { createLibp2p } from 'libp2p';
281
import { gossipsub } from '@chainsafe/libp2p-gossipsub';
282
import { identify } from '@libp2p/identify';
283
import { createOrbitDB } from '@orbitdb/core';
284
285
// Configure Libp2p for OrbitDB
286
const libp2pOptions = {
287
services: {
288
pubsub: gossipsub({
289
allowPublishToZeroTopicPeers: true
290
}),
291
identify: identify()
292
}
293
};
294
295
const libp2p = await createLibp2p(libp2pOptions);
296
const ipfs = await createHelia({ libp2p });
297
const orbitdb = await createOrbitDB({ ipfs });
298
299
// Now OrbitDB can sync with peers
300
const db = await orbitdb.open('shared-db');
301
```