refactor: move getPubkeysBySearch () function to a new location

This commit is contained in:
P. Reis
2024-09-16 14:24:26 -03:00
parent 4d0ae401b3
commit 2fe6a8fde5
4 changed files with 20 additions and 17 deletions

21
src/utils/search.test.ts Normal file
View File

@@ -0,0 +1,21 @@
import { assertEquals } from '@std/assert';
import { createTestDB } from '@/test.ts';
import { getPubkeysBySearch } from '@/utils/search.ts';
Deno.test('fuzzy search works', async () => {
await using db = await createTestDB();
await db.kysely.insertInto('author_search').values({
pubkey: '47259076c85f9240e852420d7213c95e95102f1de929fb60f33a2c32570c98c4',
search: 'patrickReiis patrickdosreis.com',
}).execute();
assertEquals(await getPubkeysBySearch(db.kysely, { q: 'pat rick', limit: 1 }), []);
assertEquals(await getPubkeysBySearch(db.kysely, { q: 'patrick dos reis', limit: 1 }), [
'47259076c85f9240e852420d7213c95e95102f1de929fb60f33a2c32570c98c4',
]);
assertEquals(await getPubkeysBySearch(db.kysely, { q: 'dosreis.com', limit: 1 }), [
'47259076c85f9240e852420d7213c95e95102f1de929fb60f33a2c32570c98c4',
]);
});

16
src/utils/search.ts Normal file
View File

@@ -0,0 +1,16 @@
import { Kysely, sql } from 'kysely';
import { DittoTables } from '@/db/DittoTables.ts';
/** Get pubkeys whose name and NIP-05 is similar to 'q' */
export async function getPubkeysBySearch(kysely: Kysely<DittoTables>, opts: { q: string; limit: number }) {
const { q, limit } = opts;
const pubkeys = (await sql<{ pubkey: string }>`
SELECT *, word_similarity(${q}, search) AS sml
FROM author_search
WHERE ${q} % search
ORDER BY sml DESC, search LIMIT ${limit}
`.execute(kysely)).rows.map(({ pubkey }) => pubkey);
return pubkeys;
}