Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: type without a key #62

Open
OliverJAsh opened this issue Nov 28, 2021 · 0 comments
Open

Suggestion: type without a key #62

OliverJAsh opened this issue Nov 28, 2021 · 0 comments

Comments

@OliverJAsh
Copy link

Currently I am using P.str like so:

  const queryMatch = P.str('query').imap(
    ({ query }) => ({ query: decodeUrlSlugParam(query) }),
    ({ query }) => ({ query: encodeUrlSlugParam(query) }),
  );

I need to use imap to run my decode/encode functions, however to do this I am forced to work with the object type ({ query: string }) rather than just the string. Ideally I could just imap(decodeUrlSlugParam, encodeUrlSlugParam):

  const queryMatch = typeWithoutKey(t.string)
    .imap(decodeUrlSlugParam, encodeUrlSlugParam)
    .imap(
      (query) => ({ query }),
      ({ query }) => query,
    );

This would be possible with something like the existing type function but without the object wrapping. This can be done manually like in my example above.

export function typeWithoutKey<A>(type: t.Type<A, string>): P.Match<A> {
  return new P.Match(
    new P.Parser((r) => {
      if (r.parts.length === 0) {
        return O.none;
      } else {
        const head = r.parts[0];
        const tail = r.parts.slice(1);
        return O.option.map(O.fromEither(type.decode(head)), (a) =>
          tuple(a, new P.Route(tail, r.query)),
        );
      }
    }),
    new P.Formatter((r, a) => new P.Route(r.parts.concat(type.encode(a)), r.query)),
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant