-
Notifications
You must be signed in to change notification settings - Fork 143
Description
Hello all,
I'd like to ask if anyone has experimented with composing Getters and how it turned out? Also I would like to propose one possible approach that opened a bunch of new possibilities for me.
In my codebase I often have many entities that are related(up to 5 levels in depth) and to reduce everything to required values it usually takes few roundtrips through reactor.evaluate function using multiple KeyPaths or Getters. Even when using approach with functions that create Getters like it's described here. And this clutters the rest of the app logic with filtering functions etc.
Example problem: pull the currently selected organization from organizations list, use that organization's id to select all the websites under that organization and then use that website ids to filter just the administrator names under that websites. You can see that here you need to either make multiple evaluate calls or nest the Getters which can be really hard to comprehend.
For this I created a small lib that receives a list of KeyPath, Getters, functions and composes them in a way that every successive Getter and function receive result from previous computation and share the same context for more complex decision making. As a result you get one fat Getter that returns exactly the data you need.
Lib repo to check out: https://github.com/popc0rn/nuclear-transform, also available as "nuclear-transform" module through npm if you want to test it out.
Code example:
import { transform } from 'nuclear-transform';
const adminNamesGetter = transform([
// 1st step
[
['currentlySelectedOrganization'],
['organizations'],
(selectedOrg, orgs) => {
return orgs[selectedOrg];
}
],
// 2nd step
[
['websites'],
(organization, websites) => websites.filter(web => web.organizationId === organization.id)
],
// 3rd step
[
['users'],
(websites, users) => users.filter(user => user.websiteId === websiteId && user.permission === 'administrator')
],
// 4th step
users => users.map(user => user.name)
]);
const administratorNames = reactor.evaluate(adminNamesGetter);
console.log(administratorNames);
What do you think about this approach? Anybody using something similar?