forked from nodejs/doc-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseOrama.mjs
More file actions
49 lines (41 loc) · 1.27 KB
/
useOrama.mjs
File metadata and controls
49 lines (41 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { create, search, load } from '@orama/orama';
import { useState, useEffect, useRef } from 'react';
import { relativeOrAbsolute } from '../utils/relativeOrAbsolute.mjs';
/**
* Hook for initializing and managing Orama search database.
* The search data is lazily fetched on the first search call.
*
* @param {string} pathname - The current page's path (e.g., '/api/fs')
*/
export default pathname => {
const [client, setClient] = useState(null);
const loaded = useRef(null);
useEffect(() => {
// Create the database instance
const db = create({
schema: {},
});
/**
* Ensures the search data is loaded.
* @returns {Promise<void>} A promise that resolves when the data is loaded.
*/
const ensureLoaded = () => {
if (!loaded.current) {
loaded.current = fetch(relativeOrAbsolute('/orama-db.json', pathname))
.then(response => response.ok && response.json())
.then(data => load(db, data));
}
return loaded.current;
};
// TODO(@avivkeller): Ask Orama to support this functionality natively
/**
* @param {any} options
*/
db.search = async options => {
await ensureLoaded();
return search(db, options);
};
setClient(db);
}, []);
return client;
};