Cache getSigner instead of strictly memoizing

This commit is contained in:
Jon Staab
2024-11-13 13:11:55 -08:00
parent 78bc9df7a6
commit b1f92f05bb
2 changed files with 25 additions and 25 deletions
+22 -18
View File
@@ -1,5 +1,5 @@
import {derived} from "svelte/store" import {derived} from "svelte/store"
import {memoize, omit, equals, assoc} from "@welshman/lib" import {cached, hash, omit, equals, assoc} from "@welshman/lib"
import {withGetter, synced} from "@welshman/store" import {withGetter, synced} from "@welshman/store"
import {type Nip46Handler} from "@welshman/signer" import {type Nip46Handler} from "@welshman/signer"
import {Nip46Broker, Nip46Signer, Nip07Signer, Nip01Signer, Nip55Signer} from "@welshman/signer" import {Nip46Broker, Nip46Signer, Nip07Signer, Nip01Signer, Nip55Signer} from "@welshman/signer"
@@ -42,23 +42,27 @@ export const dropSession = (pubkey: string) =>
export const nip46Perms = "sign_event:22242,nip04_encrypt,nip04_decrypt,nip44_encrypt,nip44_decrypt" export const nip46Perms = "sign_event:22242,nip04_encrypt,nip04_decrypt,nip44_encrypt,nip44_decrypt"
export const getSigner = memoize((session: Session) => { export const getSigner = cached({
switch (session?.method) { maxSize: 100,
case "nip07": getKey: ([session]: [Session | null]) => hash(String(JSON.stringify(session))),
return new Nip07Signer() getValue: ([session]: [Session | null]) => {
case "nip01": switch (session?.method) {
return new Nip01Signer(session.secret!) case "nip07":
case "nip46": return new Nip07Signer()
return new Nip46Signer( case "nip01":
Nip46Broker.get({ return new Nip01Signer(session.secret!)
secret: session.secret!, case "nip46":
handler: session.handler!, return new Nip46Signer(
}) Nip46Broker.get({
) secret: session.secret!,
case "nip55": handler: session.handler!,
return new Nip55Signer(session.signer!) })
default: )
return null case "nip55":
return new Nip55Signer(session.signer!)
default:
return null
}
} }
}) })
+3 -7
View File
@@ -46,15 +46,11 @@ export function cached<T, V, Args extends any[]>({
const get = (...args: Args) => { const get = (...args: Args) => {
const k = getKey(args) const k = getKey(args)
let v = cache.get(k) if (!cache.has(k)) {
cache.set(k, getValue(args))
if (!v) {
v = getValue(args)
cache.set(k, v)
} }
return v return cache.get(k)
} }
get.cache = cache get.cache = cache