Last active
August 18, 2024 19:56
-
-
Save VldMrgnn/2e0c8b301a53a73e64136d4d128ae701 to your computer and use it in GitHub Desktop.
proxy to map the selector path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createSelector } from "starfx/store"; | |
/* SELECTORS */ | |
/** | |
* Creates a proxy around an object to track accessed properties. | |
* | |
* @param {object} obj - The object to create a proxy for. | |
* @returns {[object, Set<string>]} An array containing the proxy object and a Set of accessed property names. | |
*/ | |
function trackAccesses(obj) { | |
const accessedProps = new Set(); | |
const handler = { | |
get(target, prop) { | |
accessedProps.add(prop); | |
return target[prop]; | |
}, | |
}; | |
return [new Proxy(obj, handler), accessedProps]; | |
} | |
/** | |
* Creates a selector that captures the accessed data slices and treats them as paths. | |
* Applies the error state to the data selector and retrieves | |
* the error messages from the corresponding paths. | |
* | |
* @param {function} dataSelector - The original data selector function. | |
* @returns {function} A modified error selector function. | |
*/ | |
export const metaSelector = (dataSelector) => { | |
return createSelector( | |
(dataState) => dataState, | |
(dataState) => { | |
try { | |
// Collects the accessed data slices as path-like information | |
const [stateProxy, accessedSlices] = trackAccesses(dataState); | |
// Invokes the data selector to capture relevant slices | |
const _ = dataSelector(stateProxy); | |
// Retrieves the current error/messate state | |
const metaState = window.metaFx.getState(); | |
// Filters accessed slices for existing error states and maps to messages | |
const errors = Array.from(accessedSlices) | |
.filter((slice: string) => metaState[slice]) | |
.map((slice: string) => metaState[slice]); | |
// Returns the found error messages (if any) | |
return errors.length > 0 ? errors : []; | |
} catch (e) { | |
console.log(e); | |
return [e.message]; | |
} | |
} | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment