Last active
October 10, 2024 13:04
-
-
Save cmdruid/720b6547471c2337481490de643e187d to your computer and use it in GitHub Desktop.
Nostr Event Filter Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Basic implementation of NIP 01 filters in typescript. */ | |
interface Event { | |
id : string | |
kind : number | |
created_at : number | |
pubkey : string | |
subject ?: string | |
content : string | |
sig : string | |
tags : string[][] | |
} | |
interface Filter { | |
ids ?: string[] | |
authors ?: string[] | |
kinds ?: number[] | |
since ?: number | |
until ?: number | |
limit ?: number | |
[ key : string ] : string | number | string[] | number[] | undefined | |
} | |
export function filterEvents ( | |
events : Event[], | |
filter : Filter = {} | |
) : Event[] { | |
const { authors, ids, kinds, since, until, limit, ...rest } = filter | |
events.sort((a, b) => b.created_at - a.created_at) | |
if (limit !== undefined && limit < events.length) { | |
events = events.slice(0, limit) | |
} | |
if (ids !== undefined) { | |
events = events.filter(e => ids.includes(e.id)) | |
} | |
if (since !== undefined) { | |
events = events.filter(e => e.created_at > since) | |
} | |
if (until !== undefined) { | |
events = events.filter(e => e.created_at < until) | |
} | |
if (authors !== undefined) { | |
events = events.filter(e => authors.includes(e.pubkey)) | |
} | |
if (kinds !== undefined) { | |
events = events.filter(e => kinds.includes(e.kind)) | |
} | |
for (const key in rest) { | |
if (key.startsWith('#')) { | |
const tag = key.slice(1, 2) | |
const keys = rest[key] | |
events = events.filter(e => { | |
return e.tags.some(t => { | |
return t[0] === tag && keys.includes(t[1]) | |
}) | |
}) | |
} | |
} | |
return events | |
} |
Thanks for posting this. Is NIP-50 considered a mandatory part of the spec now?
Nope, it is optional, just notifying
I should also mention that this script does not do partial matching of event ids or pubkeys, which is in the filter spec. To add partial matching to authors as an example, you can iterate through authors
and check if e.pubkey.startsWith(author)
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is now search field: https://github.com/nostr-protocol/nips/blob/master/50.md