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

feat: add tryRead<T> function to simplify reading values only if they exist instead #1651

Open
3 tasks
mtwichel opened this issue Dec 19, 2024 · 0 comments · May be fixed by #1652
Open
3 tasks

feat: add tryRead<T> function to simplify reading values only if they exist instead #1651

mtwichel opened this issue Dec 19, 2024 · 0 comments · May be fixed by #1652
Labels
feature A new feature or request

Comments

@mtwichel
Copy link
Contributor

mtwichel commented Dec 19, 2024

Description

I have a handy extension written in all my Dart Frog projects that I believe is a good candidate for the main framework.

extension on RequestContext {
  T? tryRead<T>( ) {
    try {
       return read<T>( );
    } on StateError catch (_) {
       return null;
    }
  }
}

As you can see, all this does is attempts reading the value, and returns null if it fails. This is extremely useful in building web sites with Dart Frog as many routes are accessible for both authenticated and unauthenticated users, they just render differently. This supports a much nicer flow to access that data.

final user = context.tryRead<User>();
if (user == null) {
  print('unauthenticated');
} else {
  print('authenticated');
}

Requirements

  • All CI/CD checks are passing.
  • There is no drop in the test coverage percentage.
  • Change is documented in the dependency injection docs

Additional Context

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature A new feature or request
Projects
Status: Needs Triage
Development

Successfully merging a pull request may close this issue.

1 participant