-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathautocomplete.js
76 lines (63 loc) · 2.29 KB
/
autocomplete.js
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
const _ = require("lodash");
const consts = require("./consts.json");
function listRegions(query = "") {
const autocompleteList = consts.ALL_AWS_REGIONS.map(({ regionId, regionLabel }) => (
toAutocompleteItemFromPrimitive(regionId, `${regionId} - ${regionLabel}`)
));
return filterItemsByQuery(autocompleteList, query);
}
function getRegionLabel(regionId) {
const foundRegion = consts.ALL_AWS_REGIONS.find((region) => region.regionId === regionId);
if (_.isNil(foundRegion)) {
throw new Error(`Could not find a region label for region id: "${regionId}"`);
}
return foundRegion.regionLabel;
}
function autocompleteListFromAwsCall(
Command,
pathToArray = "",
pathToValue = "",
prepareCommandInput = () => ({}),
) {
return async (query, params, awsServiceClient) => {
const response = await awsServiceClient.send(new Command(prepareCommandInput(params)));
if (pathToArray !== "" && !_.has(response, pathToArray)) {
throw new Error(`Path "${pathToArray}" doesn't exist on method call response`);
}
const autocompleteItems = (pathToArray === "" ? response : _.get(response, pathToArray))
.map((object) => {
if (pathToValue !== "" && (_.isArray(object) || !_.has(object, pathToValue))) {
throw new Error(`Path "${pathToValue}" doesn't exist on elements of array`);
}
return toAutocompleteItemFromPrimitive(pathToValue === "" ? object : _.get(object, pathToValue));
});
return filterItemsByQuery(autocompleteItems, query);
};
}
function filterItemsByQuery(autocompleteItems, query) {
if (!query) {
return sliceAndSortItems(autocompleteItems);
}
const queryWords = query.split(/[. ]/g).map(_.toLower);
const filteredResult = autocompleteItems.filter((item) => {
const wordIsPresentInValue = (word) => item.value.toLowerCase().includes(word);
return queryWords.every(wordIsPresentInValue);
});
return sliceAndSortItems(filteredResult);
}
function toAutocompleteItemFromPrimitive(value, label = value) {
return {
id: value,
value: label,
};
}
function sliceAndSortItems(items) {
return _.sortBy(items.slice(0, consts.MAX_AUTOCOMPLETE_RESULTS), ["value"]);
}
module.exports = {
listRegions,
getRegionLabel,
autocompleteListFromAwsCall,
filterItemsByQuery,
toAutocompleteItemFromPrimitive,
};