Effect CommunityEC
Effect Community3y ago
128 replies
bigpopakap

Transformation logic for converting a Person object to a FormattedPerson object

Ok I'm not sure how dumb/nuanced/obtuse/abstract/esoteric/pathological this question is, but here goes
(More pointed questions in thread)

// Doesn't matter - this def just makes the types check,
// but below just assume "E" to be any old thing
type E = 'foo';

// Say you have these structs as "input" and "output"
interface Person {
    age: number;
}
interface FormattedPerson {
    age: string;
}

// And you have this logic to do that transformation
// Maybe this logic is inlined into the programs below, but to shorten up the examples I'm putting it in a helper
const formatPerson = (person: Person): T.Effect<never, E, FormattedPerson> =>
    // Pretend this is some complex async function
    T.succeed({
        age: `${person.age} years`,
    });

// EXAMPLE 1 WITH ARGS
const programWithArgs = (person: Person): T.Effect<never, E, void> => T.gen(function* (_) {
    const formattedPerson: FormattedPerson = yield* _(formatPerson(person));
});

// EXAMPLE 2 WITH SERVICE
const Person = CTX.Tag<Person>();

const programWithService: T.Effect<Person, E, void> = T.gen(function* (_) {
    const person: Person = yield* _(Person);
    const formattedPerson: FormattedPerson = yield* _(formatPerson(person));
});

// EXAMPLE 3 WITH LAYER
const FormattedPerson = CTX.Tag<FormattedPerson>();
const formattedPersonLayer: LAY.Layer<Person, E, FormattedPerson> =
    LAY.effect(FormattedPerson, T.gen(function* (_) {
        const person: Person = yield* _(Person);
        return yield* _(formatPerson(person));
    }));

const programWithLayer: T.Effect<Person, E, void> = T.gen(function* (_) {
    const formattedPerson: FormattedPerson = yield* _(FormattedPerson);
}).pipe(
    T.provideLayer(formattedPersonLayer),
);
Was this page helpful?