Skip to content

Commit

Permalink
add NIP-78 interface
Browse files Browse the repository at this point in the history
  • Loading branch information
pablof7z committed Sep 24, 2024
1 parent f8c4d9d commit 98ca0f0
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
75 changes: 75 additions & 0 deletions ndk/src/app-settings/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { NDKKind } from "../events/kinds";
import { NDKEvent, type NostrEvent } from "../events/index.js";
import type { NDK } from "../ndk";
import { NDKRelaySet } from "../relay/sets";

/**
* Implements NIP-78 App Settings
*
* @example
* const appSettings = new NDKAppSettings(ndk)
* appSettings.appName = "My App";
* appSettings.set("my_key", "my_value");
* await appSettings.save();
*
* @example
* const appSettings = NDKAppSettings.from(event);
* appSettings.appName = "My App";
* console.log(appSettings.get("my_key"));
*
* @group Kind Wrapper
*
* @see https://github.com/nostr-protocol/nips/blob/master/78.md
*/
export class NDKAppSettings extends NDKEvent {
public appName: string | undefined;
public settings: Record<string, unknown> = {};

constructor(ndk: NDK | undefined, rawEvent?: NostrEvent | NDKEvent) {
super(ndk, rawEvent);
this.kind ??= NDKKind.AppSpecificData;
this.dTag ??= this.appName;

if (this.content.length > 0) {
try {
this.settings = JSON.parse(this.content);
} catch (error) {
console.error("Error parsing app settings", error);
}
}
}

static from(event: NDKEvent) {
return new NDKAppSettings(event.ndk, event);
}

/**
* Set a value for a given key.
*
* @param key
* @param value
*/
set(key: string, value: unknown) {
this.settings[key] = value;
}

/**
* Get a value for a given key.
*
* @param key
* @returns
*/
get(key: string) {
return this.settings[key];
}

public async publishReplaceable(
relaySet?: NDKRelaySet,
timeoutMs?: number,
requiredRelayCount?: number
) {
this.content = JSON.stringify(this.settings);

return super.publishReplaceable(relaySet, timeoutMs, requiredRelayCount);
}
}
2 changes: 2 additions & 0 deletions ndk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export * from "./events/kinds/simple-group/index.js";
export * from "./events/kinds/simple-group/metadata.js";
export * from "./events/kinds/simple-group/member-list.js";

export * from "./app-settings/index.js";

export * from "./relay/index.js";
export * from "./relay/auth-policies.js";
export * from "./relay/sets/index.js";
Expand Down

0 comments on commit 98ca0f0

Please sign in to comment.