Effect CommunityEC
Effect Community2y ago
2 replies
whatplan

Handling Conditional Defaults in API Schema Parsing

I am parsing a schema for an api endpoint it has some optional options with defaults
however, there is one specific scenario where based on a condition I determine sometime after parsing I need to know whether a value was provided or from the default

basically if the condition is true I first need to check if foo was provided in the body, if not then look at another optional thing, and then finally use the default value of the schema

import * as S from "@effect/schema/Schema";

const Body = S.Struct({
  foo: S.String.pipe(S.optional({ default: () => "foo" })),
});

declare const bodyJson: unknown;

const result = S.decodeUnknownSync(Body)(bodyJson);

// use result.foo in a couple places where the default value is expected if the value was not provided

declare const otherThing: { foo: string | undefined };
declare const condition: boolean;

const finalValue = (() => {
  if (
    condition &&
    typeof bodyJson === "object" &&
    bodyJson !== null &&
    "foo" in bodyJson &&
    typeof bodyJson.foo === "string"
  ) {
    return bodyJson.foo;
  } else if (otherThing.foo) {
    return otherThing.foo;
  } else {
    return result.foo;
  }
})();


the solutions I have thought of are:
1. use S.optionalToRequired and map the
T | undefined
to { value: T, provided: boolean }
2. create a schema that requires some services that inject the otherThing and the condition and inject them and use the result of that special schema in this specific scenario

thoughts appriciated
Was this page helpful?