Skip to content

Commit

Permalink
Merge cb4e505 into 84a4a9e
Browse files Browse the repository at this point in the history
  • Loading branch information
lucaong committed May 15, 2023
2 parents 84a4a9e + cb4e505 commit 21f7dac
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,9 @@

# unreleased

- Add `getStoredFields` method to retrieve the stored fields for a document
given its ID.

- Pass stored fields to the `boostDocument` callback function, making it
easier to perform dynamic document boosting.

Expand Down
18 changes: 18 additions & 0 deletions src/MiniSearch.test.js
Expand Up @@ -945,6 +945,24 @@ describe('MiniSearch', () => {
})
})

describe('getStoredFields', () => {
it('returns the stored fields for the given document ID, or undefined if the document is not in the index', () => {
const documents = [
{ id: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' },
{ id: 2, title: 'I Promessi Sposi', text: 'Quel ramo del lago di Como' }
]
const ms = new MiniSearch({ fields: ['title', 'text'], storeFields: ['title', 'text'] })
ms.addAll(documents)

expect(ms.getStoredFields(1)).toEqual({ title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' })
expect(ms.getStoredFields(2)).toEqual({ title: 'I Promessi Sposi', text: 'Quel ramo del lago di Como' })
expect(ms.getStoredFields(3)).toBe(undefined)

ms.discard(1)
expect(ms.getStoredFields(1)).toBe(undefined)
})
})

describe('search', () => {
const documents = [
{ id: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' },
Expand Down
17 changes: 16 additions & 1 deletion src/MiniSearch.ts
Expand Up @@ -1033,10 +1033,25 @@ export default class MiniSearch<T = any> {
*
* @param id The document ID
*/
has (id: any) {
has (id: any): boolean {
return this._idToShortId.has(id)
}

/**
* Returns the stored fields (as configured in [[Options.storeFields]]) for
* the given document ID. Returns `undefined` if the document is not present
* in the index.
*
* @param id The document ID
*/
getStoredFields (id: any): Record<string, unknown> | undefined {
const shortId = this._idToShortId.get(id)

if (shortId == null) { return undefined }

return this._storedFields.get(shortId)
}

/**
* Search for documents matching the given search query.
*
Expand Down

0 comments on commit 21f7dac

Please sign in to comment.