web_lib

Common web application libraries
git clone https://radroots.dev/git/web_lib.git
Log | Files | Refs | LICENSE

relays.ts (2148B)


      1 import {
      2     makeLoader as make_loader,
      3     publish as publish_events,
      4     request as request_events,
      5     type AdapterContext,
      6     type LoadOptions,
      7     type PublishOptions,
      8     type PublishResultsByRelay,
      9     type RequestOptions,
     10 } from "@welshman/net";
     11 import type { TrustedEvent } from "@welshman/util";
     12 import type { NostrContext } from "./types/nostr.js";
     13 
     14 const build_adapter_context = (context?: NostrContext): AdapterContext | undefined => {
     15     if (!context) return undefined;
     16     return {
     17         pool: context.pool,
     18         repository: context.repository,
     19     };
     20 };
     21 
     22 export type NostrRequestOptions = Omit<RequestOptions, "context"> & {
     23     context?: NostrContext;
     24 };
     25 
     26 export type NostrPublishOptions = Omit<PublishOptions, "context"> & {
     27     context?: NostrContext;
     28 };
     29 
     30 export type NostrLoadOptions = LoadOptions & {
     31     context?: NostrContext;
     32 };
     33 
     34 export const nostr_request = async (opts: NostrRequestOptions): Promise<TrustedEvent[]> => {
     35     const { context, ...rest } = opts;
     36     const adapter_context = build_adapter_context(context);
     37     return request_events({ ...rest, context: adapter_context });
     38 };
     39 
     40 export const nostr_load = async (opts: NostrLoadOptions): Promise<TrustedEvent[]> => {
     41     const { context, ...rest } = opts;
     42     const adapter_context = build_adapter_context(context);
     43     const loader = make_loader({ delay: 200, timeout: 3000, threshold: 0.5, context: adapter_context });
     44     return loader(rest);
     45 };
     46 
     47 export const nostr_publish = async (opts: NostrPublishOptions): Promise<PublishResultsByRelay> => {
     48     const { context, ...rest } = opts;
     49     const adapter_context = build_adapter_context(context);
     50     return publish_events({ ...rest, context: adapter_context });
     51 };
     52 
     53 export const nostr_relays_open = (context: NostrContext, relays: string[]): void => {
     54     for (const relay of relays) context.pool.get(relay).open();
     55 };
     56 
     57 export const nostr_relays_close = (context: NostrContext, relays: string[]): void => {
     58     for (const relay of relays) context.pool.remove(relay);
     59 };
     60 
     61 export const nostr_relays_clear = (context: NostrContext): void => {
     62     context.pool.clear();
     63 };
     64 
     65 export * from "./relay/lib.js";