Effect CommunityEC
Effect Community•3y ago•
12 replies
attila

Title: Example of Schema Transformation with Tuple Validation

This works:
export const example: schema.Schema<string, { a: "a"; b: string }> =
  schema.transformResult(
    pipe(schema.string, arrayFromDelimitedString(":")),
    schema.struct({ a: schema.literal("a"), b: schema.string }),
    (arr) => {
      const myTuple = schema.tuple(
        schema.literal("a"),
        schema.string.pipe(schema.nonEmpty())
      );
      try {
        return pipe(arr, schema.parseSync(myTuple), ([a, b]) =>
          parseResult.success({ a, b })
        );
      } catch (_) {
        return parseResult.failure(parseResult.type(myTuple.ast, arr));
      }
    },
    ({ a, b }) => parseResult.success([a, b])
  );

but this
export const example: schema.Schema<string, { a: "a"; b: string }> =
  schema.transformResult(
    pipe(schema.string, arrayFromDelimitedString(":")),
    schema.struct({ a: schema.literal("a"), b: schema.string }),
    (arr) => {
      return pipe(
        arr,
        schema.parse(
          schema.tuple(
            schema.literal("a"),
            schema.string.pipe(schema.nonEmpty())
          )
        ),
        Effect.map(([a, b]) => ({ a, b }))
      );
    },
    ({ a, b }) => parseResult.success([a, b])
  );

fails with
[Error: {"_tag":"ParseError","errors":[{"_tag":"Forbidden"}]}
    undefined]

Any ideas why? 😅 This is the smallest reproducible example I could craft. I tried each part individually and they work. It's just when they're glued together somehow things start to fall apart. Both examples fully type check with my setup, so I can't see where the problem is.
NB: arrayFromDelimitedString comes from https://github.com/Effect-TS/schema/pull/353
Was this page helpful?