Skip to content

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

@mtwichel

Description

@mtwichel

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

Metadata

Metadata

Assignees

Labels

won't fixThis will not be worked on

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions