Skip to content

Commit

Permalink
Add options argument to search method
Browse files Browse the repository at this point in the history
  • Loading branch information
leandrogehlen committed Aug 3, 2023
1 parent 69beb94 commit 6f30b7d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RxCollection, RxDatabase, RxDocument, RxPlugin } from 'rxdb';
import { Index } from 'flexsearch';
import { Index, SearchOptions, Limit } from 'flexsearch';

export type RxExportIndexHandler = (key: string, value: string) => void | Promise<void>;

Expand All @@ -12,7 +12,11 @@ export type RxDatabaseSearch = RxDatabase & RxDatabaseIndexMethods;

export type RxCollectionSearch<RxDocType = any> = RxCollection<RxDocType> & {
$index: Index;
search(this: RxCollectionSearch, query: string): Promise<RxDocument[]>;
search(
this: RxCollectionSearch,
query: string,
options?: Limit | SearchOptions
): Promise<RxDocument[]>;
};

function serialize(data: any, searchFields: string[]): string {
Expand Down Expand Up @@ -56,8 +60,12 @@ async function importIndexes(
);
}

async function search(this: RxCollectionSearch, query: string): Promise<RxDocument[]> {
const ids = this.$index.search(query) as string[];
async function search(
this: RxCollectionSearch,
query: string,
options?: Limit | SearchOptions
): Promise<RxDocument[]> {
const ids = this.$index.search(query, options) as string[];
const results = await this.findByIds(ids).exec();
return Array.from(results.values());
}
Expand Down
30 changes: 30 additions & 0 deletions tests/search.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,36 @@ describe('Replication', () => {
expect(results.length).toBe(0);
});

it('should perform search with options', async () => {
database = await initDatabase();

await database.addCollections({
users: {
schema: userSchema,
options: {
searchable: true,
},
},
});

const collection = database.users as RxCollectionSearch;

await collection.insert({
id: '1',
name: 'Bill Gates',
age: 67,
});

await collection.insert({
id: '2',
name: 'Bill James',
age: 53,
});

const results = await collection.search('bill', 1);
expect(results).toBe(1);
});

it('should import/export indexes', async () => {
let indexId: string;
let indexData: string;
Expand Down

0 comments on commit 6f30b7d

Please sign in to comment.