rxjs/operators#map JavaScript Examples
The following examples show how to use
rxjs/operators#map.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js From sampo-ui with MIT License | 6 votes |
fetchByURIEpic = (action$, state$) => action$.pipe(
ofType(FETCH_BY_URI),
withLatestFrom(state$),
mergeMap(([action, state]) => {
const { perspectiveID, resultClass, facetClass, uri } = action
const params = stateToUrl({
perspectiveID,
facets: facetClass == null ? null : state[`${facetClass}Facets`].facets,
facetClass
})
const requestUrl = `${apiUrl}/${resultClass}/page/${encodeURIComponent(uri)}`
return ajax({
url: requestUrl,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: params
}).pipe(
map(ajaxResponse => updateInstanceTable({
resultClass,
data: ajaxResponse.response.data,
sparqlQuery: ajaxResponse.response.sparqlQuery
})),
catchError(error => of({
type: FETCH_BY_URI_FAILED,
resultClass: resultClass,
error: error,
message: {
text: backendErrorText,
title: 'Error'
}
}))
)
})
)
Example #2
Source File: OnlineAccountClient.js From invizi with GNU General Public License v3.0 | 6 votes |
// Fetch all trades, all deposits and withdraws
// returns obs
synchronizeTransactions (account, symbolCurrencyPair, apiKeys, params) {
const allTrades$ = this.getMyTradesObs(...arguments)
const withdrawals$ = this.getWithdrawalsObs(...arguments)
const deposits$ = from(this.getDepositsObs(...arguments))
const timer$ = timer(5000)
const maxIter = this.allTransactionsMaxIter(account.name)
let currentIter = 1
let load$ = concat(deposits$, timer$, withdrawals$, timer$, allTrades$).pipe(
tap(data => {
console.log(data)
}),
filter(data => data), // filter timerObs values
map(result => {
let tradesFiltered = result.data
// if (account.last_sync_at) {
// tradesFiltered = result.data.filter(trade => trade.date > account.last_sync_at / 1000)
// }
tradesFiltered.progress = (currentIter + 1) / maxIter
currentIter++
return result
})
)
return load$
}
Example #3
Source File: OnlineAccountClient.js From invizi with GNU General Public License v3.0 | 6 votes |
// Like loadBalance but convert into trades
async loadBalanceForTrades (account) {
let result = await this.loadBalance(account.name)
let importItems = TradeClient.balanceToTrades(result, account.name, account.account_type, {fromExchange: true})
// Remove from the imported balance the ones already present in db
let exchangeDbTrades = await TradeClient.account(account.name)
let exchangeOrderHistory = exchangeDbTrades.filter(trade => trade.fromExchange === true)
let newExchangeTrades = _.differenceWith(importItems, exchangeOrderHistory, (a, b) => {
return a.to === b.to && a.quantity_to === b.quantity_to
})
newExchangeTrades = newExchangeTrades.map(trade => Object.assign({}, trade, {_id: TradeClient.hashId(trade)}))
let oldLocalTrades = _.differenceWith(exchangeOrderHistory, importItems, (a, b) => {
return a.to === b.to && a.quantity_to === b.quantity_to
})
// Delete old local trades since they are not on exchange anymore
TradeClient.remove(oldLocalTrades.map(trade => trade.id))
return newExchangeTrades
}
Example #4
Source File: KrakenExchangeClient.js From invizi with GNU General Public License v3.0 | 6 votes |
getMyTradesObs (apiKey, symbolCurrencyPair = undefined, params = {}) {
let counter = -1
this.initializeApiKey(apiKey)
const fetchTrades = () => {
counter++
return super.getMyTrades(apiKey, undefined, {ofs: counter * 50})
}
const trades$ = defer(() => fetchTrades())
let load$ = new BehaviorSubject('')
const whenToRefresh$ = of('').pipe(
delay(5000),
tap(_ => load$.next('')),
skip(1))
const poll$ = concat(trades$, whenToRefresh$)
let result$ = load$.pipe(
concatMap(_ => poll$),
takeWhile(data => data.length > 0),
map(data => ({errors: [], data})),
catchError(error$ => {
return of({errors: [error$.toString()], data: []})
}))
return result$
}
Example #5
Source File: KrakenExchangeClient.js From invizi with GNU General Public License v3.0 | 6 votes |
// fetch deposits AND withdrawal
getDepositsObs (apiKey, symbolCurrencyPair = undefined, params = {}) {
let counter = -1
this.initializeApiKey(apiKey)
const query = () => {
counter++
return this.ccxt.fetchLedger(undefined, undefined, undefined, {ofs: counter * 50})
}
const trades$ = defer(query)
let load$ = new BehaviorSubject('')
const whenToRefresh$ = of('').pipe(
delay(5000),
tap(_ => load$.next('')),
skip(1))
const byDepositAndWithdrawal = trade => trade && ['deposit', 'withdrawal'].includes(trade.info.type)
const poll$ = concat(trades$, whenToRefresh$)
return load$.pipe(
concatMap(_ => poll$),
takeWhile(data => data.length > 0),
map(data => ({errors: [], data: data.filter(byDepositAndWithdrawal).map(parseLedger)})),
catchError(error$ => of({errors: [error$.toString()], data: []})))
}
Example #6
Source File: index.js From sampo-ui with MIT License | 6 votes |
fetchKnowledgeGraphMetadataEpic = (action$, state$) => action$.pipe(
ofType(FETCH_KNOWLEDGE_GRAPH_METADATA),
withLatestFrom(state$),
mergeMap(([action]) => {
const requestUrl = `${apiUrl}/void/${action.perspectiveID}/${action.resultClass}`
return ajax({
url: requestUrl,
method: 'GET'
}).pipe(
map(ajaxResponse => updateKnowledgeGraphMetadata({
resultClass: action.resultClass,
data: ajaxResponse.response.data ? ajaxResponse.response.data[0] : null,
sparqlQuery: ajaxResponse.response.sparqlQuery
})),
catchError(error => of({
type: FETCH_KNOWLEDGE_GRAPH_METADATA_FAILED,
perspectiveID: action.resultClass,
error: error,
message: {
text: backendErrorText,
title: 'Error'
}
}))
)
})
)
Example #7
Source File: index.js From sampo-ui with MIT License | 6 votes |
fetchGeoJSONLayersEpic = action$ => action$.pipe(
ofType(FETCH_GEOJSON_LAYERS),
mergeMap(async action => {
const { layerIDs, bounds } = action
try {
const data = await Promise.all(layerIDs.map(layerID => fetchGeoJSONLayer(layerID, bounds)))
return updateGeoJSONLayers({ payload: data })
} catch (error) {
return fetchGeoJSONLayersFailed({
error,
message: {
text: backendErrorText,
title: 'Error'
}
})
}
})
)
Example #8
Source File: index.js From sampo-ui with MIT License | 6 votes |
fetchGeoJSONLayersBackendEpic = (action$, state$) => action$.pipe(
ofType(FETCH_GEOJSON_LAYERS_BACKEND),
withLatestFrom(state$),
mergeMap(([action]) => {
const { layerIDs /* bounds */ } = action
// const { latMin, longMin, latMax, longMax } = boundsToValues(bounds)
const params = {
layerID: layerIDs
// latMin,
// longMin,
// latMax,
// longMax
}
const requestUrl = `${apiUrl}/wfs?${querystring.stringify(params)}`
return ajax.getJSON(requestUrl).pipe(
map(res => updateGeoJSONLayers({
payload: res
})),
catchError(error => of({
type: SHOW_ERROR,
error: error,
message: {
text: backendErrorText,
title: 'Error'
}
}))
)
})
)
Example #9
Source File: index.js From sampo-ui with MIT License | 6 votes |
fetchSimilarDocumentsEpic = (action$, state$) => action$.pipe(
ofType(FETCH_SIMILAR_DOCUMENTS_BY_ID),
withLatestFrom(state$),
mergeMap(([action]) => {
const { resultClass, id, modelName, resultSize } = action
const requestUrl = `${documentFinderAPIUrl}/top-similar/${modelName}/${id}?n=${resultSize}`
return ajax.getJSON(requestUrl).pipe(
map(res => updateInstanceTableExternal({
resultClass,
data: res.documents || null
})),
catchError(error => of({
type: FETCH_SIMILAR_DOCUMENTS_BY_ID_FAILED,
resultClass: action.resultClass,
id: action.id,
error: error,
message: {
text: backendErrorText,
title: 'Error'
}
}))
)
})
)
Example #10
Source File: index.js From sampo-ui with MIT License | 6 votes |
clientFSFetchResultsEpic = (action$, state$) => action$.pipe(
ofType(CLIENT_FS_FETCH_RESULTS),
withLatestFrom(state$),
debounceTime(500),
switchMap(([action, state]) => {
const { perspectiveID, jenaIndex } = action
const federatedSearchState = state[perspectiveID]
const selectedDatasets = pickSelectedDatasets(federatedSearchState.datasets)
const dsParams = selectedDatasets.map(ds => `dataset=${ds}`).join('&')
let requestUrl
if (action.jenaIndex === 'text') {
requestUrl = `${apiUrl}/federated-search?q=${action.query}&${dsParams}&perspectiveID=${perspectiveID}`
} else if (action.jenaIndex === 'spatial') {
const { latMin, longMin, latMax, longMax } = federatedSearchState.maps.boundingboxSearch
requestUrl = `${apiUrl}/federated-search?latMin=${latMin}&longMin=${longMin}&latMax=${latMax}&longMax=${longMax}&${dsParams}&perspectiveID=${perspectiveID}`
}
return ajax.getJSON(requestUrl).pipe(
map(response => clientFSUpdateResults({
results: response,
jenaIndex
})),
catchError(error => of({
type: CLIENT_FS_FETCH_RESULTS_FAILED,
error: error,
message: {
text: backendErrorText,
title: 'Error'
}
}))
)
})
)
Example #11
Source File: index.js From sampo-ui with MIT License | 6 votes |
fullTextSearchEpic = (action$, state$) => action$.pipe(
ofType(FETCH_FULL_TEXT_RESULTS),
withLatestFrom(state$),
debounceTime(500),
switchMap(([action, state]) => {
const requestUrl = `${apiUrl}/full-text-search?q=${action.query}`
return ajax.getJSON(requestUrl).pipe(
map(response => updateResults({
resultClass: 'fullTextSearch',
data: response.data,
sparqlQuery: response.sparqlQuery,
query: action.query,
jenaIndex: action.jenaIndex
})),
catchError(error => of({
type: FETCH_RESULTS_FAILED,
resultClass: 'fullTextSearch',
error: error,
message: {
text: backendErrorText,
title: 'Error'
}
}))
)
})
)
Example #12
Source File: index.js From sampo-ui with MIT License | 6 votes |
fetchResultCountEpic = (action$, state$) => action$.pipe(
ofType(FETCH_RESULT_COUNT),
withLatestFrom(state$),
mergeMap(([action, state]) => {
const { resultClass, facetClass } = action
const params = stateToUrl({
facets: state[`${facetClass}Facets`].facets
})
const requestUrl = `${apiUrl}/faceted-search/${resultClass}/count`
return ajax({
url: requestUrl,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: params
}).pipe(
map(ajaxResponse => updateResultCount({
resultClass,
data: ajaxResponse.response.data,
sparqlQuery: ajaxResponse.response.sparqlQuery
})),
catchError(error => of({
type: FETCH_RESULT_COUNT_FAILED,
resultClass,
error: error,
message: {
text: backendErrorText,
title: 'Error'
}
}))
)
})
)
Example #13
Source File: vehicle-search.js From real-time-map with MIT License | 6 votes |
export function _getDeviceList(selectedIDs) {
storage.selectedDevices = {};
return Promise.all(Object.values(selectedIDs).map(data => {
const {
id,
color,
visible
} = data;
if (!visible) {
return Promise.resolve("done");
}
if (color) { //It's a group
return getDevicesInGroups([{ id }]).then(devices =>
devices.forEach(device => {
const {
id,
name,
groups
} = device;
storage.selectedDevices[id] = { id, name, groups, visible: true };
})
);
}
else {
storage.selectedDevices[id] = data;
return Promise.resolve("done");
}
}));
}
Example #14
Source File: tokens.js From payroll-app with GNU Affero General Public License v3.0 | 5 votes |
export function getDenominationToken() {
return app
.call('denominationToken')
.pipe(first())
.pipe(map(getToken))
.toPromise()
}
Example #15
Source File: index.js From sampo-ui with MIT License | 5 votes |
fetchFacetEpic = (action$, state$) => action$.pipe(
ofType(FETCH_FACET),
withLatestFrom(state$),
mergeMap(([action, state]) => {
const { facetClass, facetID, constrainSelf } = action
const facets = state[`${facetClass}Facets`].facets
const facet = facets[facetID]
const { sortBy = null, sortDirection = null } = facet
const params = stateToUrl({
facets,
sortBy,
sortDirection,
constrainSelf
})
const requestUrl = `${apiUrl}/faceted-search/${action.facetClass}/facet/${facetID}`
return ajax({
url: requestUrl,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: params
}).pipe(
map(ajaxResponse => updateFacetValues({
facetClass,
id: ajaxResponse.response.id,
data: ajaxResponse.response.data || [],
flatData: ajaxResponse.response.flatData || [],
sparqlQuery: ajaxResponse.response.sparqlQuery
})),
catchError(error => of({
type: FETCH_FACET_FAILED,
facetClass,
facetID,
error: error,
message: {
text: backendErrorText,
title: 'Error'
}
}))
)
})
)
Example #16
Source File: index.js From sampo-ui with MIT License | 5 votes |
fetchFacetConstrainSelfEpic = (action$, state$) => action$.pipe(
ofType(FETCH_FACET_CONSTRAIN_SELF),
withLatestFrom(state$),
mergeMap(([action, state]) => {
const { facetClass, facetID } = action
const facets = state[`${facetClass}Facets`].facets
const facet = facets[facetID]
const { sortBy, sortDirection } = facet
const params = stateToUrl({
facets: facets,
sortBy: sortBy,
sortDirection: sortDirection,
constrainSelf: true
})
const requestUrl = `${apiUrl}/faceted-search/${action.facetClass}/facet/${facetID}`
return ajax({
url: requestUrl,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: params
}).pipe(
map(ajaxResponse => updateFacetValuesConstrainSelf({
facetClass,
id: facetID,
data: ajaxResponse.response.data || [],
flatData: ajaxResponse.response.flatData || [],
sparqlQuery: ajaxResponse.response.sparqlQuery
})),
catchError(error => of({
type: FETCH_FACET_FAILED,
resultClass: facetClass,
id: action.id,
error: error,
message: {
text: backendErrorText,
title: 'Error'
}
}))
)
})
)
Example #17
Source File: index.js From sampo-ui with MIT License | 5 votes |
fetchInstanceAnalysisEpic = (action$, state$) => action$.pipe(
ofType(FETCH_INSTANCE_ANALYSIS),
withLatestFrom(state$),
mergeMap(([action, state]) => {
const { resultClass, facetClass, fromID, toID, period, province } = action
const params = stateToUrl({
facets: facetClass ? state[`${facetClass}Facets`].facets : null,
facetClass,
uri: action.uri ? action.uri : null,
fromID,
toID,
period,
province
})
const requestUrl = `${apiUrl}/faceted-search/${resultClass}/all`
// https://rxjs-dev.firebaseapp.com/api/ajax/ajax
return ajax({
url: requestUrl,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: params
}).pipe(
map(ajaxResponse => updateInstanceAnalysisData({
resultClass,
data: ajaxResponse.response.data,
sparqlQuery: ajaxResponse.response.sparqlQuery
})),
catchError(error => of({
type: FETCH_RESULTS_FAILED,
resultClass,
error: error,
message: {
text: backendErrorText,
title: 'Error'
}
}))
)
})
)
Example #18
Source File: index.js From sampo-ui with MIT License | 5 votes |
fetchResultsEpic = (action$, state$) => action$.pipe(
ofType(FETCH_RESULTS),
withLatestFrom(state$),
mergeMap(([action, state]) => {
const { perspectiveID, resultClass, facetClass, limit, optimize } = action
const params = stateToUrl({
perspectiveID,
facets: facetClass ? state[`${facetClass}Facets`].facets : null,
facetClass,
uri: action.uri ? action.uri : null,
limit,
optimize
})
const requestUrl = `${apiUrl}/faceted-search/${resultClass}/all`
// https://rxjs-dev.firebaseapp.com/api/ajax/ajax
return ajax({
url: requestUrl,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: params
}).pipe(
map(ajaxResponse => updateResults({
resultClass,
data: ajaxResponse.response.data,
sparqlQuery: ajaxResponse.response.sparqlQuery,
order: action.order
})),
catchError(error => of({
type: FETCH_RESULTS_FAILED,
resultClass,
error: error,
message: {
text: backendErrorText,
title: 'Error'
}
}))
)
})
)
Example #19
Source File: index.js From sampo-ui with MIT License | 5 votes |
fetchPaginatedResultsEpic = (action$, state$) => action$.pipe(
ofType(FETCH_PAGINATED_RESULTS),
withLatestFrom(state$),
mergeMap(([action, state]) => {
const { resultClass, facetClass, sortBy } = action
const { page, pagesize, sortDirection } = state[resultClass]
const params = stateToUrl({
facets: state[`${facetClass}Facets`].facets,
facetClass: null,
page,
pagesize,
sortBy,
sortDirection
})
const requestUrl = `${apiUrl}/faceted-search/${resultClass}/paginated`
// https://rxjs-dev.firebaseapp.com/api/ajax/ajax
return ajax({
url: requestUrl,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: params
}).pipe(
map(ajaxResponse =>
updatePaginatedResults({
resultClass,
data: ajaxResponse.response.data,
sparqlQuery: ajaxResponse.response.sparqlQuery
})),
// https://redux-observable.js.org/docs/recipes/ErrorHandling.html
catchError(error => of({
type: FETCH_PAGINATED_RESULTS_FAILED,
resultClass,
error: error,
message: {
text: backendErrorText,
title: 'Error'
}
}))
)
})
)
Example #20
Source File: tokens.js From payroll-app with GNU Affero General Public License v3.0 | 5 votes |
function loadTokenDecimals(address) {
return app
.external(address, tokenDecimalsAbi)
.decimals()
.pipe(first())
.pipe(map(value => parseInt(value)))
.toPromise()
}
Example #21
Source File: vehicle-search.js From real-time-map with MIT License | 4 votes |
deviceSearch = {
shown: true,
deviceResultsCache: {},
selectedIDS: {},
get searchInput() {
return document.getElementById("RTM-vehicle-search-bar");
},
init(mapPropsToComponent) {
// Init rxjs debounce search.
const searchInputObservable = fromEvent(deviceSearch.searchInput, "input").pipe(map(i => i.currentTarget.value));
const debouncedInput = searchInputObservable.pipe(debounceTime(250));
debouncedInput.subscribe((searchInput) => deviceSearch.buildSearchList(searchInput, mapPropsToComponent));
},
loadSavedDeviceConfig(mapPropsToComponent) {
return getBlobStorage().then(val => {
if (val.length === 0) { return; }
const cachedDevices = JSON.parse(val[0].data);
if (cachedDevices.configData.Vehicle) {
deviceSearch.selectedIDS = cachedDevices.configData.Vehicle;
deviceSearch.applyFilter();
deviceSearch.buildDeviceDisplayList(mapPropsToComponent);
}
});
},
buildSearchList(searchInput, mapPropsToComponent) {
const nameSearchMultiCall = [
createDeviceByNameCall(searchInput),
createGroupsByNameCall(searchInput)
];
return makeAPIMultiCall(nameSearchMultiCall).then(results => {
// deviceList = results[0];
results[0]
.map(deviceSearch.saveDeviceDataToCache);
// groupList = results[1];
results[1]
.map(deviceSearch.saveGroupDataToCache);
mapPropsToComponent(Object.values(deviceSearch.deviceResultsCache));
});
},
saveDeviceDataToCache(deviceData) {
const data = {};
["id", "name", "groups"].forEach(prop => data[prop] = deviceData[prop]);
data.visible = true;
deviceSearch.deviceResultsCache[data.name] = data;
return data;
},
saveGroupDataToCache(deviceData) {
const data = {};
["id", "name", "color"].forEach(prop => data[prop] = deviceData[prop]);
data.visible = true;
data.name += " (Group)";
deviceSearch.deviceResultsCache[data.name] = data;
return data;
},
buildDeviceDisplayList(mapPropsToComponent) {
deviceSearch.mapPropsToComponent = mapPropsToComponent;
mapPropsToComponent(Object.values(deviceSearch.selectedIDS)
.filter(device => device.id && device.name));
},
handleItemSelected(event, mapPropsToComponent) {
event.preventDefault();
deviceSearch.saveSelectedValue(mapPropsToComponent);
},
saveSelectedValue(mapPropsToComponent) {
const { value } = deviceSearch.searchInput;
if (!deviceSearch.deviceResultsCache.hasOwnProperty(value)) {
return;
}
const deviceData = deviceSearch.deviceResultsCache[value];
deviceData.visible = true;
const {
id,
name,
groups,
color,
visible
} = deviceData;
if (color) { //It's a group
deviceSearch.selectedIDS[id] = { id, name, color, visible };
}
else {
deviceSearch.selectedIDS[id] = { id, name, groups, visible };
}
deviceSearch.searchInput.value = "";
deviceSearch.saveConfig(mapPropsToComponent);
return deviceData;
},
deleteItemFromdeviceList(id, mapPropsToComponent) {
delete deviceSearch.selectedIDS[id];
deviceSearch.saveConfig(mapPropsToComponent);
},
deleteAllItems(mapPropsToComponent) {
deviceSearch.selectedIDS = {};
deviceSearch.saveConfig(mapPropsToComponent);
},
saveConfig(mapPropsToComponent) {
storage.setBlobStorageObj ? setBlobStorage("Vehicle", deviceSearch.selectedIDS) : saveBlobStorage("Vehicle", deviceSearch.selectedIDS);
deviceSearch.applyFilter();
deviceSearch.buildDeviceDisplayList(mapPropsToComponent);
},
applyFilter() {
_getDeviceList(deviceSearch.selectedIDS).then(() => {
_applyDeviceFilter(Object.keys(storage.selectedDevices));
});
},
showAll(mapPropsToComponent) {
Object.values(deviceSearch.selectedIDS)
.forEach(selectedDevice =>
selectedDevice.visible = true
);
deviceSearch.saveConfig(mapPropsToComponent);
},
hideAll(mapPropsToComponent) {
Object.values(deviceSearch.selectedIDS)
.forEach(selectedDevice =>
selectedDevice.visible = false
);
deviceSearch.saveConfig(mapPropsToComponent);
},
toggleDeviceVisibility(id, mapPropsToComponent) {
const selectedDevice = deviceSearch.selectedIDS[id];
selectedDevice.visible = !selectedDevice.visible;
deviceSearch.saveConfig(mapPropsToComponent);
},
zoomIntoDevice(id) {
const deviceMarker = markerList[id];
if (deviceMarker) {
const newZoomLevel = Math.max(Math.min(storage.map.getZoom() + 1, 18), 15);
storage.map.flyTo(deviceMarker.currentlatLng, newZoomLevel);
} else {
alert("Sorry, no current day data for selected vehicle.");
}
}
}
Example #22
Source File: status-search.js From real-time-map with MIT License | 4 votes |
diagnosticSearch = {
resultsCache: {},
displayList: {},
get searchInput() {
return document.getElementById("RTM-status-search-bar");
},
init(mapPropsToComponent) {
// Init rxjs debounce search.
const searchInputObservable$ = fromEvent(diagnosticSearch.searchInput, "input").pipe(map(i => i.currentTarget.value));
const debouncedInput = searchInputObservable$.pipe(debounceTime(250));
debouncedInput.subscribe((searchInput) => diagnosticSearch.buildSearchList(searchInput, mapPropsToComponent));
},
loadSavedStatusConfig(mapPropsToComponent) {
return getBlobStorage().then(val => {
if (val.length === 0) { return; }
const cachedDiagnostics = JSON.parse(val[0].data);
if (cachedDiagnostics.configData.Status) {
diagnosticSearch.displayList = cachedDiagnostics.configData.Status;
storage.selectedStatuses = filterByVisibility(diagnosticSearch.displayList);
diagnosticSearch.buildStatusDisplayList(mapPropsToComponent);
}
});
},
buildSearchList(searchInput, mapPropstoComponent) {
return getDiagnosticByName(searchInput).then(diagnosticResults => {
diagnosticResults.forEach(diagnostic => {
const {
id,
name,
unitOfMeasure
} = diagnostic;
const visible = true;
diagnosticSearch.resultsCache[name] = { name, id, visible, unitOfMeasure };
});
mapPropstoComponent(Object.values(diagnosticSearch.resultsCache));
});
},
handleItemSelected(event, mapPropsToComponent) {
event.preventDefault();
diagnosticSearch.saveSelectedValue(mapPropsToComponent);
},
saveSelectedValue(mapPropsToComponent) {
const { value } = diagnosticSearch.searchInput;
const diagnosticData = diagnosticSearch.resultsCache[value];
if (diagnosticData) {
diagnosticSearch.displayList[diagnosticData.id] = diagnosticData;
diagnosticSearch.searchInput.value = "";
diagnosticSearch.saveConfig(mapPropsToComponent);
}
return diagnosticData;
},
buildStatusDisplayList(mapPropsToComponent) {
mapPropsToComponent(Object.values(diagnosticSearch.displayList)
.filter(diagnostic => diagnostic.id && diagnostic.name));
},
deleteItemFromStatusList(id, mapPropsToComponent) {
delete diagnosticSearch.displayList[id];
diagnosticSearch.saveConfig(mapPropsToComponent);
},
saveConfig(mapPropsToComponent) {
storage.selectedStatuses = filterByVisibility(diagnosticSearch.displayList);
storage.setBlobStorageObj ? setBlobStorage("Status", diagnosticSearch.displayList) : saveBlobStorage("Status", diagnosticSearch.displayList);
storage.dateKeeper$.update();
diagnosticSearch.buildStatusDisplayList(mapPropsToComponent);
},
toggleStatusVisibility(id, mapPropsToComponent) {
const selectedDiagnostic = diagnosticSearch.displayList[id];
selectedDiagnostic.visible = !selectedDiagnostic.visible;
diagnosticSearch.saveConfig(mapPropsToComponent);
},
deleteAllItems(mapPropsToComponent) {
diagnosticSearch.displayList = {};
diagnosticSearch.saveConfig(mapPropsToComponent);
},
showAllItems(mapPropsToComponent) {
Object.values(diagnosticSearch.displayList)
.forEach(selectedDiagnostic =>
selectedDiagnostic.visible = true
);
diagnosticSearch.saveConfig(mapPropsToComponent);
},
hideAllItems(mapPropsToComponent) {
Object.values(diagnosticSearch.displayList)
.forEach(selectedDiagnostic =>
selectedDiagnostic.visible = false
);
diagnosticSearch.saveConfig(mapPropsToComponent);
}
}
Example #23
Source File: exception-search.js From real-time-map with MIT License | 4 votes |
exceptionSearch = {
exceptionResultsCache: {},
displayList: {},
get searchInput() {
return document.getElementById("RTM-exception-search-bar");
},
init(mapPropsToComponent) {
// Init rxjs debounce search.
const searchInputObservable$ = fromEvent(exceptionSearch.searchInput, "input").pipe(map(i => i.currentTarget.value));
const debouncedInput = searchInputObservable$.pipe(debounceTime(250));
debouncedInput.subscribe((searchInput) => exceptionSearch.buildSearchList(searchInput, mapPropsToComponent));
},
loadSavedExceptionConfig(mapPropsToComponent) {
return getBlobStorage().then(val => {
if (val.length > 0 && !storage.setBlobStorageObj) { storage.setBlobStorageObj = val[0]; }
else {
return saveBlobStorage("Exception", {}).then(() => {
return getBlobStorage().then(val => {
storage.setBlobStorageObj = val[0];
});
});
};
exceptionSearch.searchInput.value = "";
const cachedExceptions = JSON.parse(val[0].data);
if (cachedExceptions.configData.Exception) {
exceptionSearch.displayList = cachedExceptions.configData.Exception;
storage.selectedExceptions = filterByVisibility(exceptionSearch.displayList);
exceptionSearch.buildExceptionDisplayList(mapPropsToComponent);
}
}).catch(error =>
console.warn("Server is unavailable, please try again later: ", error)
);
},
buildSearchList(searchInput, mapPropsToComponent) {
return getRulesByName(searchInput).then(ruleList => {
ruleList.forEach(rule => {
let {
color,
name,
id,
baseType
} = rule;
if (baseType === "Stock") { name += " (Default)"; };
const visible = true;
exceptionSearch.exceptionResultsCache[name] = { color, name, id, visible, baseType };
});
mapPropsToComponent(Object.values(exceptionSearch.exceptionResultsCache));
});
},
handleItemSelected(event, mapPropsToComponent) {
event.preventDefault();
exceptionSearch.saveSelectedValue(mapPropsToComponent);
},
saveSelectedValue(mapPropsToComponent) {
const { value } = exceptionSearch.searchInput;
const exceptionData = exceptionSearch.exceptionResultsCache[value];
if (exceptionData) {
exceptionSearch.displayList[exceptionData.id] = exceptionData;
exceptionSearch.saveConfig(mapPropsToComponent);
exceptionSearch.searchInput.value = "";
}
return exceptionData;
},
buildExceptionDisplayList(mapPropsToComponent) {
mapPropsToComponent(Object.values(exceptionSearch.displayList)
.filter(ruleData => ruleData.id && ruleData.name));
},
deleteItemFromExceptionList(id, mapPropsToComponent) {
delete exceptionSearch.displayList[id];
exceptionSearch.saveConfig(mapPropsToComponent);
},
saveConfig(mapPropsToComponent) {
storage.selectedExceptions = filterByVisibility(exceptionSearch.displayList);
storage.setBlobStorageObj ? setBlobStorage("Exception", exceptionSearch.displayList) : saveBlobStorage("Exception", exceptionSearch.displayList);
exceptionSearch.buildExceptionDisplayList(mapPropsToComponent);
storage.dateKeeper$.update();
},
toggleExceptionVisibility(ruleID, mapPropsToComponent) {
const selectedException = exceptionSearch.displayList[ruleID];
selectedException.visible = !selectedException.visible;
exceptionSearch.saveConfig(mapPropsToComponent);
},
deleteAllItems(mapPropsToComponent) {
exceptionSearch.displayList = {};
exceptionSearch.saveConfig(mapPropsToComponent);
},
setVisibilityForAllItems(visibility, mapPropsToComponent) {
Object.values(exceptionSearch.displayList)
.forEach(selectedItem =>
selectedItem.visible = visibility
);
exceptionSearch.saveConfig(mapPropsToComponent);
}
}