Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Customize Monocle policy regarding missing interposed nodes? #169

Open
JasonKleban opened this issue Oct 27, 2021 · 0 comments
Open

Customize Monocle policy regarding missing interposed nodes? #169

JasonKleban opened this issue Oct 27, 2021 · 0 comments

Comments

@JasonKleban
Copy link

📖 Documentation

Posted here: https://stackoverflow.com/questions/69725346/customize-monocle-policy-regarding-missing-interposed-nodes

Is there a way in monocle (monocle-ts especially) to change the policy of how to handle missing interposed nodes in a structured data, such as in examples A, B and C below, to create them instead of no-oping? I have a use case where that different behavior is desirable. Can I work within the library to achieve it?

import { Optional } from "monocle-ts";

interface BazMaybe {
  baz?: number;
}

interface BarMaybe {
  bar?: BazMaybe;
}

interface FooMaybe {
  foo?: BarMaybe;
}

const baz = Optional.fromNullableProp<BazMaybe>()("baz");
const bar = Optional.fromNullableProp<BarMaybe>()("bar");
const foo = Optional.fromNullableProp<FooMaybe>()("foo");

const foo_bar_baz = foo.compose(bar).compose(baz);

// A) no op, gives `{}`
console.log(JSON.stringify(foo_bar_baz.set(42)({})));

// B) no op, gives `{"foo":{"bar":{}}}`
console.log(JSON.stringify(foo_bar_baz.set(42)({ foo: { bar: {} } })));

// C) no op, gives `{"foo":{"bar":{}}}`
console.log(JSON.stringify(foo_bar_baz.set(42)({ foo: { bar: { baz: undefined } } })));

// D) ok, finally, gives `{"foo":{"bar":{"baz":42}}}`
console.log(JSON.stringify(foo_bar_baz.set(42)({ foo: { bar: { baz: 0 } } }));

Further, can we define a policy to always replace empties during updates with undefined (recursively) so that the reverse operation is consistent?

// E) ideally, this should give `{}`
console.log(JSON.stringify(foo.compose(bar).modify(
    ( baz, ...rest ) => 
        (rest))({ foo: { bar: { baz: 42} } })));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant