Skip to content

Custom Queries

A custom query is simply a function that returns a Query object

For example here is a custom query that will subscribe to and parse a NIP-78 app event that contains json

ts
import { map } from "rxjs/operators";

function AppSettingsQuery<T>(pubkey: string): Query<T> {
  return {
    key: pubkey,
    run: (eventStore) => {
      return eventStore.replaceable(30078, pubkey, "app-settings").pipe(
        map((event) => {
          if (!event) return undefined;
          return JSON.parse(event.content) as T;
        }),
      );
    },
  };
}

const sub = queryStore
  .createQuery(AppSettingsQuery, "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d")
  .subscribe((json) => {
    // json will either be undefined or { theme: string }
    if (json) console.log("updated data", json);
  });

eventStore.add({
  kind: 30078,
  content: '{"theme": "dark"}',
  // rest of event
});