Effect CommunityEC
Effect Community2y ago
2 replies
Stephen Bluck

Restricting Error Channel to Match Input Keys

How can I restrict this error channel to match the keys of the input?
import { Issue, formatError } from "@effect/schema/ArrayFormatter";
import { ParseError } from "@effect/schema/ParseResult";
import * as S from "@effect/schema/Schema";
import { Effect, Either, ReadonlyArray } from "effect";

export const parseFormData = <O extends Record<string, any>>(
  request: Request,
  parser: (u: unknown) => Effect.Effect<O, ParseError>,
): Effect.Effect<Either.Either<Record<string, [Issue, ...Issue[]]>, O>> => {
  const result = Effect.promise(() => request.formData()).pipe(
    Effect.map((data) => Object.fromEntries(data.entries())),
    Effect.flatMap(parser),
    Effect.mapError(formatError),
    Effect.mapError(ReadonlyArray.groupBy((a) => a.path.join("."))),
    Effect.either,
  );

  return result;
};

declare const request: Request;

type Person = S.Schema.To<typeof Person>;
const Person = S.struct({
  name: S.string,
  age: S.number,
});

// I want Effect.Effect<Either.Either<{ name: Issue[], age: Issue[] }, Person>>
// But I have Effect.Effect<Either.Either<Record<string, [Issue, ...Issue[]]>, Person>
const result = parseFormData(request, S.decodeUnknown(Person));

Thank you in advance!
Was this page helpful?