-
-
Save eznix86/b77f42c9cbb2878e99825061f3a15e6a to your computer and use it in GitHub Desktop.
Nostr Event Filter Example
This file contains 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment