Skip to content

Instantly share code, notes, and snippets.

@cmdruid
Last active January 3, 2024 22:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cmdruid/720b6547471c2337481490de643e187d to your computer and use it in GitHub Desktop.
Save cmdruid/720b6547471c2337481490de643e187d to your computer and use it in GitHub Desktop.
Nostr Event Filter Example
/** 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
}
@eznix86
Copy link

eznix86 commented Dec 8, 2023

@cmdruid
Copy link
Author

cmdruid commented Dec 11, 2023

Thanks for posting this. Is NIP-50 considered a mandatory part of the spec now?

@eznix86
Copy link

eznix86 commented Jan 3, 2024

Nope, it is optional, just notifying

@cmdruid
Copy link
Author

cmdruid commented Jan 3, 2024

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