Effect CommunityEC
Effect Community3y ago
29 replies
aniravi

Exploring Schema Basics

New to schema and playing around with it to try to understand how to use it.

Why does "TO" log ISO strings within the date range correctly, but "FROM" just logs random strings, even though my annotation says to log years?

import { pipe } from "@effect/data/Function";
import * as S from "@effect/schema/Schema";
import * as A from "@effect/schema/Arbitrary";
import * as fc from "fast-check";
import * as PR from "@effect/schema/ParseResult";

export const DateWithinRangeSchema = S.transformResult(
  pipe(
    S.string,
    //     S.filter(s => !isNaN(new Date(s).getTime())),
    S.annotations({
      [A.ArbitraryHookId]: (): A.Arbitrary<string> => fc =>
        fc.date().map(d => `${d.getFullYear()}`),
    }),
  ),
  pipe(
    S.DateFromSelf,
    S.filter(b => b.getFullYear() > 2000 && b.getFullYear() <= 2021, {
      message: b => `Date ${b.toISOString()} is not between 2000 and 2021`,
    }),
    S.annotations({
      [A.ArbitraryHookId]: (): A.Arbitrary<Date> => fc =>
        fc.date({
          min: new Date("2000-01-01T00:00:00.000Z"),
          max: new Date("2021-01-01T00:00:00.000Z"),
        }),
    }),
  ),
  s =>
    !isNaN(new Date(s).getTime())
      ? PR.success(new Date(s))
      : PR.failure(PR.type(S.Date.ast, new Date(s))),
  b => PR.success(b.toISOString()),
);

const TestingDate = S.struct({
  date: DateWithinRangeSchema,
});

// Arbitrary for the To type
const TestingArbitraryTo = A.to(TestingDate)(fc);

console.log("TO", fc.sample(TestingArbitraryTo, 5));

// Arbitrary for the From type
const TestingArbitraryFrom = A.from(TestingDate)(fc);

console.log("FROM", fc.sample(TestingArbitraryFrom, 5));
Was this page helpful?