01-initialization.ts raw
1 /**
2 * NDK Initialization Patterns
3 *
4 * Examples from: src/lib/stores/ndk.ts
5 */
6
7 import NDK from '@nostr-dev-kit/ndk'
8
9 // ============================================================
10 // BASIC INITIALIZATION
11 // ============================================================
12
13 const basicInit = () => {
14 const ndk = new NDK({
15 explicitRelayUrls: ['wss://relay.damus.io', 'wss://relay.nostr.band']
16 })
17
18 return ndk
19 }
20
21 // ============================================================
22 // PRODUCTION PATTERN - WITH MULTIPLE NDK INSTANCES
23 // ============================================================
24
25 const productionInit = (relays: string[], zapRelays: string[]) => {
26 // Main NDK instance for general operations
27 const ndk = new NDK({
28 explicitRelayUrls: relays
29 })
30
31 // Separate NDK for zap operations (performance optimization)
32 const zapNdk = new NDK({
33 explicitRelayUrls: zapRelays
34 })
35
36 return { ndk, zapNdk }
37 }
38
39 // ============================================================
40 // CONNECTION WITH TIMEOUT
41 // ============================================================
42
43 const connectWithTimeout = async (
44 ndk: NDK,
45 timeoutMs: number = 10000
46 ): Promise<void> => {
47 // Create connection promise
48 const connectPromise = ndk.connect()
49
50 // Create timeout promise
51 const timeoutPromise = new Promise<never>((_, reject) =>
52 setTimeout(() => reject(new Error('Connection timeout')), timeoutMs)
53 )
54
55 try {
56 // Race between connection and timeout
57 await Promise.race([connectPromise, timeoutPromise])
58 console.log('✅ NDK connected successfully')
59 } catch (error) {
60 if (error instanceof Error && error.message === 'Connection timeout') {
61 console.error('❌ Connection timed out after', timeoutMs, 'ms')
62 } else {
63 console.error('❌ Connection failed:', error)
64 }
65 throw error
66 }
67 }
68
69 // ============================================================
70 // FULL INITIALIZATION FLOW
71 // ============================================================
72
73 interface InitConfig {
74 relays?: string[]
75 zapRelays?: string[]
76 timeoutMs?: number
77 }
78
79 const defaultRelays = [
80 'wss://relay.damus.io',
81 'wss://relay.nostr.band',
82 'wss://nos.lol'
83 ]
84
85 const defaultZapRelays = [
86 'wss://relay.damus.io',
87 'wss://nostr.wine'
88 ]
89
90 const initializeNDK = async (config: InitConfig = {}) => {
91 const {
92 relays = defaultRelays,
93 zapRelays = defaultZapRelays,
94 timeoutMs = 10000
95 } = config
96
97 // Initialize instances
98 const ndk = new NDK({ explicitRelayUrls: relays })
99 const zapNdk = new NDK({ explicitRelayUrls: zapRelays })
100
101 // Connect with timeout protection
102 try {
103 await connectWithTimeout(ndk, timeoutMs)
104 await connectWithTimeout(zapNdk, timeoutMs)
105
106 return { ndk, zapNdk, isConnected: true }
107 } catch (error) {
108 return { ndk, zapNdk, isConnected: false, error }
109 }
110 }
111
112 // ============================================================
113 // CHECKING CONNECTION STATUS
114 // ============================================================
115
116 const getConnectionStatus = (ndk: NDK) => {
117 const connectedRelays = Array.from(ndk.pool?.relays.values() || [])
118 .filter(relay => relay.status === 1)
119 .map(relay => relay.url)
120
121 const isConnected = connectedRelays.length > 0
122
123 return {
124 isConnected,
125 connectedRelays,
126 totalRelays: ndk.pool?.relays.size || 0
127 }
128 }
129
130 // ============================================================
131 // USAGE EXAMPLE
132 // ============================================================
133
134 async function main() {
135 // Initialize
136 const { ndk, zapNdk, isConnected } = await initializeNDK({
137 relays: defaultRelays,
138 zapRelays: defaultZapRelays,
139 timeoutMs: 10000
140 })
141
142 if (!isConnected) {
143 console.error('Failed to connect to relays')
144 return
145 }
146
147 // Check status
148 const status = getConnectionStatus(ndk)
149 console.log('Connection status:', status)
150
151 // Ready to use
152 console.log('NDK ready for operations')
153 }
154
155 export {
156 basicInit,
157 productionInit,
158 connectWithTimeout,
159 initializeNDK,
160 getConnectionStatus
161 }
162
163