Remove empty tag filters

This commit is contained in:
Alex Gleason 2024-05-30 13:01:39 -05:00
parent 594be870e1
commit f4f3c8d4d1
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
1 changed files with 20 additions and 2 deletions

View File

@ -1,6 +1,5 @@
import { NostrEvent, NostrFilter, NSchema as n } from '@nostrify/nostrify'; import { NKinds, NostrEvent, NostrFilter, NSchema as n } from '@nostrify/nostrify';
import stringifyStable from 'fast-stable-stringify'; import stringifyStable from 'fast-stable-stringify';
import { getFilterLimit } from 'nostr-tools';
import { z } from 'zod'; import { z } from 'zod';
/** Microfilter to get one specific event by ID. */ /** Microfilter to get one specific event by ID. */
@ -65,6 +64,25 @@ function normalizeFilters<F extends NostrFilter>(filters: F[]): F[] {
}, []); }, []);
} }
/** Calculate the intrinsic limit of a filter. This function may return `Infinity`. */
function getFilterLimit(filter: NostrFilter): number {
if (filter.ids && !filter.ids.length) return 0;
if (filter.kinds && !filter.kinds.length) return 0;
if (filter.authors && !filter.authors.length) return 0;
for (const [key, value] of Object.entries(filter)) {
if (key[0] === '#' && Array.isArray(value) && !value.length) return 0;
}
return Math.min(
Math.max(0, filter.limit ?? Infinity),
filter.ids?.length ?? Infinity,
filter.authors?.length && filter.kinds?.every((kind) => NKinds.replaceable(kind))
? filter.authors.length * filter.kinds.length
: Infinity,
);
}
export { export {
type AuthorMicrofilter, type AuthorMicrofilter,
canFilter, canFilter,