add ndk cache
This commit is contained in:
56
src/libs/ndk/cache.tsx
Normal file
56
src/libs/ndk/cache.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
import { NDKCacheAdapter } from '@nostr-dev-kit/ndk';
|
||||
import { NDKEvent, NDKSubscription } from '@nostr-dev-kit/ndk';
|
||||
import { Store } from '@tauri-apps/plugin-store';
|
||||
|
||||
export default class TauriAdapter implements NDKCacheAdapter {
|
||||
public store: Store;
|
||||
readonly locking: boolean;
|
||||
|
||||
constructor() {
|
||||
this.store = new Store('.ndkcache.dat');
|
||||
this.locking = true;
|
||||
}
|
||||
|
||||
public async query(subscription: NDKSubscription): Promise<void> {
|
||||
const { filter } = subscription;
|
||||
|
||||
// if this filter uses both authors and kinds, then we need to query for each combination of author and kind
|
||||
// and then combine the results
|
||||
if (filter.authors && filter.kinds) {
|
||||
const promises = [];
|
||||
|
||||
for (const author of filter.authors) {
|
||||
for (const kind of filter.kinds) {
|
||||
const key = `${author}:${kind}`;
|
||||
promises.push(this.store.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
const results = await Promise.all(promises);
|
||||
|
||||
for (const result of results) {
|
||||
if (result) {
|
||||
const event = await this.store.get(result as string);
|
||||
|
||||
if (event) {
|
||||
const ndkEvent = new NDKEvent(subscription.ndk, JSON.parse(event as string));
|
||||
subscription.eventReceived(ndkEvent, undefined, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async setEvent(event: NDKEvent): Promise<void> {
|
||||
const nostrEvent = await event.toNostrEvent();
|
||||
const key = `${nostrEvent.pubkey}:${nostrEvent.kind}`;
|
||||
|
||||
return new Promise((resolve) => {
|
||||
Promise.all([
|
||||
this.store.set(event.id, JSON.stringify(nostrEvent)),
|
||||
this.store.set(key, event.id),
|
||||
this.store.save(),
|
||||
]).then(() => resolve());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { ndkAdapter } from '@nostr-fetch/adapter-ndk';
|
||||
import { NostrFetcher, normalizeRelayUrlSet } from 'nostr-fetch';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import TauriAdapter from '@libs/ndk/cache';
|
||||
import { getSetting } from '@libs/storage';
|
||||
|
||||
const setting = await getSetting('relays');
|
||||
@@ -19,7 +20,8 @@ export const NDKInstance = () => {
|
||||
}, []);
|
||||
|
||||
async function loadNdk(explicitRelayUrls: string[]) {
|
||||
const ndkInstance = new NDK({ explicitRelayUrls });
|
||||
const cacheAdapter = new TauriAdapter();
|
||||
const ndkInstance = new NDK({ explicitRelayUrls, cacheAdapter });
|
||||
|
||||
try {
|
||||
await ndkInstance.connect();
|
||||
|
||||
Reference in New Issue
Block a user