• Stars
    star
    204
  • Rank 192,063 (Top 4 %)
  • Language
    Dart
  • License
    MIT License
  • Created over 5 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Connect your Flutter/Dart apps to Hasura simply.

Hasura Connect - Connect your Flutter/Dart apps to Hasura simply.


Logo

The hasura_connect is designed to facilitate Hasura's integration with Flutter applications.


Report Bug Β· Request Feature


License Pub Points Contributors Forks

Pub Publisher Flutterando Youtube


Table of Contents
  1. About The Project
  2. Getting Started
  3. Contributing
  4. License
  5. Contact

About The Project



The hasura_connect is designed to facilitate Hasura's integration with Flutter applications, leveraging the full power of Graphql.

(back to top)

Sponsors

Logo

(back to top)


Getting Started

To install Hasura Connect in your project you can follow the instructions below:

a) Add in your pubspec.yaml:

dependencies:
hasura_connect: <last-version>

b) or use slidy:

slidy install hasura_connect

(back to top)

How To Use

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.

  //get query
var r = await hasuraConnect.query(docQuery);

//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 = await hasuraConnect.subscription(docSubscription);
  snapshot.listen((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 = await hasuraConnect.subscription(docSubscription, variables: {"limit": 10});

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

INTERCEPTORS

This is a good strategy to control the flow of requests. With that we can create interceptors for logs or cache for example. The community has already provided some interceptors for caching. Interceptors are highly customizable.

View Hasura's official Authorization documentation.

class TokenInterceptor extends Interceptor {
 final FirebaseAuth auth;
 TokenInterceptor(this.auth);

 @override
 Future<void> onConnected(HasuraConnect connect) {}

 @override
 Future<void> onDisconnected() {}

 @override
 Future onError(HasuraError request) async {
   return request;
 }

 @override
 Future<Request> onRequest(Request request) async {
   var user = await auth.currentUser();
   var token = await user.getIdToken(refresh: true);
   if (token != null) {
     try {
       request.headers["Authorization"] = "Bearer ${token.token}";
       return request;
     } catch (e) {
       return null;
     }
   } else {
     Modular.to.pushReplacementNamed("/login");
   }
 }

 @override
 Future onResponse(Response data) async {
   return data;
 }

 @override
 Future<void> onSubscription(Request request, Snapshot snapshot) {}

 @override
 Future<void> onTryAgain(HasuraConnect connect) {}
}

Or:

class TokenInterceptor extends InterceptorBase {
  final FirebaseAuth auth;
  TokenInterceptor(this.auth);

  @override
  Future<Request> onRequest(Request request) async {
    var user = await auth.currentUser();
    var token = await user.getIdToken(refresh: true);
    if (token != null) {
      try {
        request.headers["Authorization"] = "Bearer ${token.token}";
        return request;
      } catch (e) {
        return null;
      }
    } else {
      Modular.to.pushReplacementNamed("/login");
    }
  }
}

INTERCEPTOR

Now you can intercept all requests, erros, subscritions.... all states of your hasura_connect connection.

  • onConnected
  • onDisconnected
  • onError
  • onRequest
  • onResponse
  • onSubscription
  • onTryAgain

CACHE OFFLINE

Now you will need to create a Interceptor or use a Cache Interceptor Package made to help you like: InMemory, Hive or SharedPreference

//In Memory
import 'package:hasura_cache_interceptor/hasura_hive_cache_interceptor.dart';

final storage = MemoryStorageService();
final cacheInterceptor = CacheInterceptor(storage);
final hasura = HasuraConnect(
  "<your hasura url>",
  interceptors: [cacheInterceptor],
  httpClient: httpClient,
)
//Hive
import 'package:hasura_connect/hasura_connect.dart';
import 'package:hasura_hive_cache_interceptor/hasura_hive_cache_interceptor.dart';

final cacheInterceptor = HiveCacheInterceptor("<your box name> (optional)");
final hasura = HasuraConnect(
  "<your hasura url>",
  interceptors: [cacheInterceptor],
  httpClient: httpClient,
)
//Shared Preference
import 'package:hasura_connect/hasura_connect.dart';
import 'package:shared_preferences_cache_interceptor/shared_preferences_cache_interceptor.dart';

final cacheInterceptor = SharedPreferencesCacheInterceptor();
final hasura = HasuraConnect(
  "<your hasura url>",
  interceptors: [cacheInterceptor],
  httpClient: httpClient,
)

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;

_For more examples, please refer to the 🚧 Documentation - Currently being updated 🚧 .

(back to top)

Common Errors

  • Query data returned not decoded to utf-8.

Fix:

import 'dart:convert';

extension Utf8convert on String {
  String  _utf8convert() {
    List<int> bytes = this.toString().codeUnits;
    return utf8.decode(bytes);
  }
  String get utf8convert => _utf8convert();
}

Features

  • βœ… Queries
  • βœ… Mutations
  • βœ… Subscriptions
  • βœ… Change Variable in Subscriptions
  • βœ… Auto-Reconnect
  • βœ… Dynamic JWT Token
  • βœ… bloc_pattern Integration
  • βœ… Provider Integration
  • βœ… Variables
  • βœ… Cache Subscription
  • βœ… Cache Mutation
  • βœ… Cache Query

Right now this package has concluded all his intended features. If you have any suggestions or find something to report, see below how to contribute to it.

(back to top)

Contributing

🚧 Contributing Guidelines - Currently being updated 🚧

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the appropriate tag. Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Remember to include a tag, and to follow Conventional Commits and Semantic Versioning when uploading your commit and/or creating the issue.

(back to top)

License

Distributed under the MIT License. See LICENSE.txt for more information.

(back to top)

Contact

Flutterando Community

(back to top)

Contributors

(back to top)

Maintaned by



Built and maintained by Flutterando.

More Repositories

1

modular

A smart project structure
Dart
1,295
star
2

roadmap

Flutter roadmap pt-BR
1,215
star
3

Clean-Dart

Proposta de Arquitetura Limpa para o Dart/Flutter
1,147
star
4

slidy

CLI package manager and template for Flutter
Dart
804
star
5

forum

Organizando as discussΓ΅es feitas no Telegram, Discord e Facebook no Github em formato de Issues.
173
star
6

triple_pattern

Segmented State Pattern for Reactive Property
Dart
156
star
7

yuno

Minimal Open-source Retrogame Frontend
Dart
113
star
8

asuka

Show Snackbars, dialogs, ModalSheets in a single provider. Simple and Clean.
Dart
83
star
9

uno

Future based HTTP client for the Dart and Flutter
Dart
77
star
10

dart_backend

Roadmap para aprender como utilizar Dart no backend
73
star
11

teddy_todo

Dart
65
star
12

calamidade

Dart
64
star
13

dartion

Json Server RESTful, Up your backend in 5 Seconds!
Dart
58
star
14

routefly

Folder-based route manager inspired by NextJS and created by the Flutterando community.
Dart
53
star
15

clean-dart-search-bloc

Github Search using "Clean Dart", BLoC and Modular.
C++
52
star
16

auto_injector

Dependency injection system. But without build_runner :)
Dart
52
star
17

rx_notifier

Extension to ValueNotifier by transparently applying functional reactive programming (TFRP)
Dart
42
star
18

asp

ASP (Atomic State Pattern) offers a simplified and modularized approach to state management for Flutter.
C++
40
star
19

minicore

Flutter/Dart Architecture proposal inspired by Clean Architecture.
40
star
20

semana-do-flutter-arc

Semana do Flutter de Maio de 2020
C++
36
star
21

music_player_app

A challenge made by Flutterando using Flutter Desktop
Dart
33
star
22

flutter_mobx_extension

TypeScript
32
star
23

result_dart

Result for dart. It is an implementation based on Kotlin Result and Swift Result.
Dart
32
star
24

nubank_layout

Desafio criado com os membros da Flutterando
Dart
32
star
25

flutter-coverage

VSCeode Extension for view the code coverage per folder/file in the test view
TypeScript
31
star
26

github_search

Github Search - Flutter Modular example
Dart
23
star
27

shelf_swagger_ui

Swagger UI plugin for Shelf
Dart
22
star
28

dson_adapter

Convert JSON to Dart Class withless code generate(build_runner)
Dart
20
star
29

architecture

Dart
20
star
30

di-example

Dart
20
star
31

flutter_calculator

Sample project using project structure generated by Slidy and TDD
Dart
20
star
32

calamidade-backend

TypeScript
19
star
33

FunctionalDart

Código e anotaçáes da série de estudos "Dart Funcional"
Dart
19
star
34

queue_management

Todas as quintas as 17 contamos esse app
Dart
18
star
35

dart_pub

Private pub.dev for packages Flutter Dart
Dart
15
star
36

flutterando_metrics

Dart
15
star
37

flutter_web_site

Flutterando's site built in Flutter Web
Dart
14
star
38

Desafios

Desafios propostos pela equipe do canal
14
star
39

animated-toolbar

Dart
12
star
40

Flutter-SOLID-Hasura-Firestore

Dart
12
star
41

website

Flutterando website
Dart
12
star
42

flutter_mobx_helpers

Widgets and Utils for increment mobx
Dart
8
star
43

carrinho_compras

Aplicativo para modelo de projeto com Repository Pattern e BLoC
C++
8
star
44

auth-service

Go
8
star
45

flutterando_bricks

Dart
8
star
46

shelf_graphql

Graphql server for shelf
Dart
7
star
47

todo_mobx

Dart
7
star
48

full_coverage

A package script for allowing coverage test tool to see all Dart files
Dart
7
star
49

flutterando_analysis

Lint rules for Dart and Flutter used internally at Flutterando
C++
7
star
50

iugu

Dart
6
star
51

via_cep_search

C++
6
star
52

slidy-vscode

snippets for slidy
TypeScript
6
star
53

semana-do-flutter-rx-notifier

Dart
6
star
54

crud_completo

CRUD Completo
C++
6
star
55

dart-backend

Dart
6
star
56

asp_arch

C++
6
star
57

unity_test_study

Dart
6
star
58

fteam_authentication

Dart
5
star
59

builders

Use Consumer, Select and BlocConsumer in any System Injector
Dart
5
star
60

dialog_launcher

A Dart package to facilitate the creation and handling of dialog boxes in command line interfaces across different operating systems (Windows, Linux, and macOS).
Dart
5
star
61

clean_dart_search_getit_cubit

Dart
4
star
62

shelf_hasura_actions

Shelf Middleware for Hasura Action.
Dart
4
star
63

hook_state

`hook_state` is a Flutter package inspired by React hooks and the `flutter_hooks` package. It offers a similar hooks experience but without the need for additional widgets, allowing you to use just `StatefulWidget` to manage complex states declaratively and reactively.
Dart
4
star
64

value_listenable_test

Assists in testing ValueListenable objects (ex: ValueNotifier).
Dart
4
star
65

value_selectable

A Flutter package that provides computed values for `ValueNotifier`, inspired by the Selectors from Recoil.
C++
4
star
66

slidy_extension

TypeScript
3
star
67

hasura_cache_interceptor

Package to implements cache in Hasura package
Dart
3
star
68

passport

Dart
3
star
69

flutter-latam-conf-2020-site

A site for Flutter LATAM Conf 2020
Dart
3
star
70

value_notifier_plus

ValueNotifierPlus Γ© um pacote que expande as funcionalidades de ValueNotifier do Flutter.
C++
2
star
71

hive_cache_interceptor

Package to implements cache using hive in hasura_connect package
Dart
2
star
72

.github

2
star
73

hasura-webhook-auth

Dart
2
star
74

flutterolx

Dart
2
star
75

keyframe

Improve the animation experience in Flutter by transforming Tweens into Timeline with Keyframe like a video editor, but using programming language
C++
2
star
76

hasura_core-Deprecated-

Dart
1
star
77

flutter-latam-conf-2020-challenge

A challenge for Flutter LATAM Conf 2020
1
star
78

hasura_firebase_performance

Hasura connect Interceptor implementation that sends querys metric data to Firebase.
Dart
1
star
79

flutterando_workflows

Reusable GitHub Workflows used at Flutterando
1
star
80

precache_image_builder

Dart
1
star
81

shared_preferences_cache_interceptor

Package to implements cache using shared preferences to hasura_connect package
Dart
1
star
82

matchmaker_lol

Dart
1
star
83

signals

Dart
1
star
84

coopartilhar-api-mock

JavaScript
1
star