From 23eb74822ff913296a872dd9df32d7a8f2117001 Mon Sep 17 00:00:00 2001 From: Ren Amamiya <123083837+reyamir@users.noreply.github.com> Date: Thu, 1 Jun 2023 10:42:38 +0700 Subject: [PATCH] add getProfile and getContacts function --- src/pool.ts | 46 +++++++++++++++++++++++++++++++++++++++++++++- test/pool.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/src/pool.ts b/src/pool.ts index 5e24048..56bd9f8 100644 --- a/src/pool.ts +++ b/src/pool.ts @@ -9,6 +9,21 @@ interface SubInfo { last_hit: number; } +interface UserInfo { + name?: string; + display_name?: string; + image?: string; + picture?: string; + banner?: string; + bio?: string; + nip05?: string; + lud06?: string; + lud16?: string; + about?: string; + website?: string; + zapService?: string; +} + // very thin wrapper using SimplePool + ArcadeIdentity export class NostrPool { ident: ArcadeIdentity; @@ -30,7 +45,10 @@ export class NostrPool { this.filters = new Map(); } - async list(filters: Filter[], db_only = false): Promise { + async list( + filters: Filter[], + db_only = false + ): Promise { if (this.db) { const since = await this.db.latest(filters); if (db_only) { @@ -246,6 +264,32 @@ export class NostrPool { }); } + async getProfile(pubkey: string, db_only = false): Promise { + const ev = await this.list([{ kinds: [0], authors: [pubkey] }], db_only); + console.log(ev); + if (ev.length > 0) { + const payload = JSON.parse(ev[0].content); + return { ...payload }; + } else { + throw new Error(`User not found`); + } + } + + async getContacts(db_only = false): Promise { + const ev = await this.list( + [{ kinds: [3], authors: [this.ident.pubKey] }], + db_only + ); + if (ev.length > 0) { + const contacts = []; + for (const item of ev[0].tags) { + contacts.push(item[1]); + } + return contacts; + } else { + throw new Error(`Relay not return anything`); + } + } /** * This function adds a callback function to an array of event callbacks. diff --git a/test/pool.test.ts b/test/pool.test.ts index e5fd3d5..08cdd66 100644 --- a/test/pool.test.ts +++ b/test/pool.test.ts @@ -155,4 +155,29 @@ describe('NostrPool', () => { expect(ret.length).toBe(4); pool1.close(); }); + + it('get user profile and contact', async () => { + const db = connectDb(); + const pool1 = new NostrPool(ident, db); + if (!pool1.db) throw Error; + await pool1.setRelays(relays); + + await pool1.send({ + content: JSON.stringify({ name: 'yo' }), + kind: 0, + tags: [], + }); + + await pool1.send({ + content: '', + kind: 3, + tags: [['p', ident.pubKey]], + }); + + const profile = await pool1.getProfile(ident.pubKey); + expect(profile.name).toBeTruthy; + + const contacts = await pool1.getContacts(); + expect(contacts).toBeTruthy; + }); });