Graphql-flutter: Async ContextLink

Created on 4 Oct 2019  路  3Comments  路  Source: zino-app/graphql-flutter

I'd like to be able to set context headers in my Link asynchronously, similar to apollo.

This should be pretty easy. I'd be happy to take a stab at a ContextLink, based on the existing AuthLink.

I'm wondering, however, if this should simply replace AuthLink to simplify the API. Rather than using an AuthLink and returning a token, you'd simply use a ContextLink and return a context map that includes "Authorization": token.

link

Most helpful comment

Here's my implementation of ContextLink:

typedef GetContext = FutureOr<Map<String, dynamic>> Function();

class ContextLink extends Link {
  ContextLink({
    this.getContext,
  }) : super(
          request: (Operation operation, [NextLink forward]) {
            StreamController<FetchResult> controller;

            Future<void> onListen() async {
              try {
                final context = await getContext();

                operation.setContext(context);
              } catch (error) {
                controller.addError(error);
              }

              await controller.addStream(forward(operation));
              await controller.close();
            }

            controller = StreamController<FetchResult>(onListen: onListen);

            return controller.stream;
          },
        );

  GetContext getContext;
}

Happy to drop this into a PR.

All 3 comments

Here's my implementation of ContextLink:

typedef GetContext = FutureOr<Map<String, dynamic>> Function();

class ContextLink extends Link {
  ContextLink({
    this.getContext,
  }) : super(
          request: (Operation operation, [NextLink forward]) {
            StreamController<FetchResult> controller;

            Future<void> onListen() async {
              try {
                final context = await getContext();

                operation.setContext(context);
              } catch (error) {
                controller.addError(error);
              }

              await controller.addStream(forward(operation));
              await controller.close();
            }

            controller = StreamController<FetchResult>(onListen: onListen);

            return controller.stream;
          },
        );

  GetContext getContext;
}

Happy to drop this into a PR.

Is this solved by the migration to using gql_link in v4?

Yes, thanks

Was this page helpful?
0 / 5 - 0 ratings