EventReduce JavaScript Implementation
This is the javascript version of the EventReduce algorithm.
Installation
npm run install event-reduce-js --save
Usage
In the following we will use EventReduce together with minimongo as an example. You can apply the code to any other database.
- First you need some
QueryParams
that can be used by EventReduce to analyze result-event combinations.
import {
getSortFieldsOfQuery,
ChangeEvent,
calculateActionName,
StateResolveFunctionInput,
runAction
} from 'event-reduce-js';
import {
compileDocumentSelector,
compileSort
} from 'minimongo/src/selector';
export function getQueryParamsByMongoQuery(query: MongoQuery): QueryParams<any> {
const sort = query.sort ? query.sort : ['_id'];
return {
primaryKey: '_id',
sortFields: getSortFieldsOfQuery(query),
skip: query.skip ? query.skip : undefined,
limit: query.limit ? query.limit : undefined,
queryMatcher: compileDocumentSelector(query.selector),
sortComparator: compileSort(sort)
};
}
const exampleQuery: MongoQuery = {
selector: {
age: {
$gt: 18
},
gender: 'm'
},
limit: 10,
sort: ['name', '_id']
};
const queryParams = getQueryParamsByMongoQuery(exampleQuery);
- Now lets say you have an
changeEvent
from whatever changestream or observable your database provides. You also have the currentResults
of the query.
const input: StateResolveFunctionInput<DocumentType> = {
changeEvent,
queryParams,
previousResults: currentResults,
keyDocumentMap: currentDocMap
};
const action = calculateActionName(input);
if (action === 'runFullQueryAgain') {
currentResults = await implementation.getRawResults(query);
currentDocMap.clear();
currentResults.forEach(doc => currentDocMap.set(doc._id, doc));
} else {
runAction(
action,
queryParams,
changeEvent,
currentResults,
currentDocMap
);
}
console.dir(currentResults);