Coder Social home page Coder Social logo

hudsonafonso / hasura_connect Goto Github PK

View Code? Open in Web Editor NEW

This project forked from flutterando/hasura_connect

0.0 1.0 0.0 1.15 MB

Connect your Flutter/Dart apps to Hasura simply.

Home Page: https://pub.dev/packages/hasura_connect

License: MIT License

Dart 97.92% Kotlin 0.09% Swift 0.85% Objective-C 0.03% HTML 1.11%

hasura_connect's Introduction

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.

hasura_connect's People

Contributors

bwolfs2 avatar jacobaraujo7 avatar roxyroses avatar alvarovasconcelos avatar davidsdearaujo avatar ben-xx avatar nosovk avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.