hasura_connect 0.1.2

Hasura Connect Package #

Connect your Flutter/Dart apps to Hasura simply.

Install #

Add dependency in your pubspec.yaml file:

dependencies:
  hasura_connect:

or use Slidy:

slidy install hasura_connect

Usage #

A simple usage example:


//import
import 'package:hasura_connect/hasura_connect.dart';

String url = 'http://localhost:8080/v1/graphql';
HasuraConnect hasuraConnect = HasuraConnect(url);

You can encapsulate this instance into a BLoC class or directly into a Provider.

Create a document with Query:

//document
String docQuery = """
  query {
    authors {
        id
        email
        name
      }
  }
""";

Now just add the document to the "query" method of the HasuraConnect instance.

var r = await hasuraConnect.query(docQuery);
print(r);

//OR USE MUTATION
var r = await hasuraConnect.mutation(docQuery);

Subscriptions #

Subscriptions will notify you each time you have a change to the searched items. Use the "hasuraConnect.subscription" method to receive a stream.

Snapshot snapshot = hasuraConnect.subscription(docSubscription);
  snapshot.stream.listen((data) {
    print(data);
  }).onError((err) {
    print(err);
  });

Mutation + Subscriptions #

You can to use mutation directly from the subscription snapshot. This will allow you to update your local list even before it has been notified by Hasura.

Snapshot snapshot = hasuraConnect.subscription(docSubscription);
...
snapshot.mutation(docMutation, onNotify: (data) {
   return data..insert(a, {"name": "next offline item" });
}

Mapped Subscription #

Use the Map operator to convert json data to a Dart object;

Snapshot<PostModel> snapshot = hasuraConnect.subscription(docSubscription)
                                            .map((data) => PostModel.fromJson(data) );

snapshot.stream.listen((PostModel data) {
   print(data);
 }).onError((err) {
   print(err);
 });

Mapped Subscription with List of results #

Use the Map operator to convert list of results in json data to a List of Dart object;

Snapshot<List<PostModel>> snapshot = hasuraConnect.subscription(docSubscription)
                               .map((data) => 
                               data.map((post) => PostModel.fromJson(post)).toList());

snapshot.stream.listen(List<PostModel> data) {
   print(data);
 }).onError((err) {
   print(err);
 });

Using variables #

Variables maintain the integrity of Querys, see an example:


String docSubscription = """
  subscription algumaCoisa($limit:Int!){
    users(limit: $limit, order_by: {user_id: desc}) {
      id
      email
      name
    }
  }
""";

Snapshot snapshot = hasuraConnect.subscription(docSubscription, variables: {"limit": 10});

//change values of variables for PAGINATIONS
snapshot.changeVariable({"limit": 20});

Authorization (JWT Token) #

View Hasura's official Authorization documentation.


  String url = 'http://localhost:8080/v1/graphql';
HasuraConnect hasuraConnect = HasuraConnect(url, token: () async {
  //sharedPreferences or other storage logic
  return "Bearer YOUR-JWT-TOKEN";
});

Dispose #

HasuraConnect provides a dispose () method for use in Provider or BlocProvider. Subscription will start only when someone is listening, and when all listeners are closed HasuraConnect automatically disconnects.

Therefore, we only connect to Hasura when we are actually using it;

Roadmap #

This is currently our roadmap, please feel free to request additions/changes.

FeatureProgress
Queries
Mutations
Subscriptions
Change Variable in Subscriptions
Auto-Reconnect
Dynamic JWT Token
bloc_pattern Integration
Provider Integration
Variables
Cache Intercept🔜

Features and bugs #

Please send feature requests and bugs at the [issue tracker][tracker]. [tracker]: http://example.com/issues/replaceme

Created from templates made available by Stagehand under a BSD-style license.

0.1.2 #

  • fix start stream with value

0.1.0 #

  • Mapped Subscriptions
  • Mutation in Snapshot

0.0.8 #

  • Flutter web Support.

0.0.7+1 #

  • Apply Health suggestions.

0.0.7 #

  • Add and Remove Headers

0.0.6 #

  • Added variables.
  • Change Variables in subscriptions (for Reactive Pagination)
  • Mutations links

0.0.3 #

  • Add variable;
  • Add mutation;

0.0.2 #

  • Query return param data;

0.0.1 #

  • Initial version, created by Stagehand

example/hasura_connect_example.dart

import 'package:hasura_connect/hasura_connect.dart';

import 'model_data.dart';

main() async {
  HasuraConnect conn =
      HasuraConnect('https://mvp-rtc-project.herokuapp.com/v1/graphql');

  // var r = await conn.query(docQuery);
  // print(r);

  var snap = conn.subscription(docSubscription).map((data) =>
      (data["data"]["users"] as List)
          .map((d) => ModelData.fromJson(d))
          .toList());

  snap.stream.listen((data) {
    print(data);
    print("==================");
  }).onError((err) {
    print(err);
  });

  await Future.delayed(Duration(seconds: 4));
  print("--- Add again --- ");

  await snap.mutation(docMutation,
      variables: {"email": "jjj@gmail.com", "pass": "123456"},
      onNotify: (data) {
    return data..insert(0, ModelData(userEmail: "jjj@gmail.com"));
  });
}

String docSubscription = """
  subscription {
  users(order_by: {user_id: desc}) {
    user_id
    user_email
    user_password
  }
}
""";

String docMutation = """
  mutation Add(\$email: String!, \$pass: String!){
    insert_users(objects: {user_email: \$email, user_password: \$pass}) {
      affected_rows
    }
  }
""";

String docQuery = """
  query {
    users {
        user_id
        user_email
        user_password
      }
  }
""";

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  hasura_connect: ^0.1.2

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:hasura_connect/hasura_connect.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
74
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
87
Learn more about scoring.

We analyzed this package on Aug 23, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.4.0
  • pana: 0.12.19

Platforms

Detected platforms: Flutter, web, other

No platform restriction found in primary library package:hasura_connect/hasura_connect.dart.

Health issues and suggestions

Document public APIs. (-0.25 points)

38 out of 39 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.4.0 <3.0.0
http ^0.12.0+2 0.12.0+2
websocket ^0.0.5 0.0.5
Transitive dependencies
async 2.3.0
charcode 1.1.2
collection 1.14.12
http_parser 3.1.3
meta 1.1.7
path 1.6.4
pedantic 1.8.0+1
source_span 1.5.5
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6