-
-
Notifications
You must be signed in to change notification settings - Fork 246
Expand file tree
/
Copy pathdataController.js
More file actions
85 lines (67 loc) · 1.89 KB
/
dataController.js
File metadata and controls
85 lines (67 loc) · 1.89 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import eventEmitter from "../helpers/eventEmitter";
import search from "./searchController";
/**
* Get data from source
*
* @param {Object} ctx - autoComplete.js context
*/
const getData = async (ctx, query) => {
const { data } = ctx;
if (data.cache && data.store) return;
ctx.feedback = data.store =
typeof data.src === "function"
? data.src.constructor.name === "AsyncFunction"
? await data.src(query)
: data.src(query)
: data.src;
/**
* @emit {response} event on data request
**/
eventEmitter("response", ctx);
};
/**
* Find matches to "query"
*
* @param {String} query - User's search query string
* @param {Object} ctx - autoComplete.js context
*/
const findMatches = (query, ctx) => {
const { data, searchEngine } = ctx;
let matches = [];
// Find matches from data source
data.store.forEach((value, index) => {
const find = (key) => {
const record = key ? value[key] : value;
const match =
typeof searchEngine === "function"
? searchEngine(query, record)
: search(query, record, {
mode: searchEngine,
diacritics: ctx.diacritics,
highlight: ctx.resultItem.highlight,
caseSensitive: ctx.caseSensitive
});
if (!match) return;
let result = { match, value };
if (key) result.key = key;
matches.push(result);
};
if (data.keys) {
for (const key of data.keys) {
find(key);
}
} else {
find();
}
});
// Find results matching to the query
if (data.filter) matches = data.filter(matches);
const results = matches.slice(0, ctx.resultsList.maxResults);
// Prepare data feedback object
ctx.feedback = { query, matches, results };
/**
* @emit {results} event on search response with matches
**/
eventEmitter("results", ctx);
};
export { getData, findMatches };