GithubHelp home page GithubHelp logo

flutterando / hasura_connect Goto Github PK

View Code? Open in Web Editor NEW
204.0 17.0 64.0 1.99 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

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

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hasura_connect's Issues

Mongodb

Will this work with Mondgodb atlas as well?

On app startup the cached query fails

In my app the first screen after the splash, loaded is where I am running the graphql query.
However each time that happens the following error is returned. Navigating to different screen then back and the error doesn't happen.
`
════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder(dirty, state: _FutureBuilderState#e5b97):
The getter 'value' was called on null.
Receiver: null
Tried calling: value

The relevant error-causing widget was
FutureBuilder (file:///C:/Users/Gloria/Desktop/FLUTTER-PROJ/moh_connect/lib/pages/homePage.dart:78:15)
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 _HomePageState.build. (package:moh_connect/pages/homePage.dart: 100:37)
#2 _FutureBuilderState.build
package:flutter/…/widgets/async.dart:732
#3 StatefulElement.build
package:flutter/…/widgets/framework.dart:4619
`
Even offline this is surprisingly the case.

A link to the gist is here, please advise what I might not be doing right.

Subscription - using variables - wrong result

I also have this problem as other persons reported.
In my case I have 2 modules: employees and employee.
In the employees list when I click on an item, I pass the id as an argument and push the employee module to show his data (in a form) with this subscription:

  @override
  Stream<EmployeeModel> getEmployee(int id) {
    return connect.subscription(employeeQuery, variables: {"id": id}).map((json) {
      return EmployeeModel.fromJson(json['data']['employees'][0]);
    });
  }

When I pop and click on a new item, the new id as passed but the same employee data is showed.
I don't know if there's a problem with the dispose, or with the caching, if you do a little demo you can see this problem happening.

If it's related with the package I think that's important to solve, because it's a feature that is used in various modules by everyone that works with subscriptions.

ezgif-3-1e32652acf9b

Thanks,
Artur

Pull more data and cache

Love the package and so simple to use compared to others.

One question though, if I grab some data with a limit/offset is there any way to concatenate the data from one result set to the next in the cache.

If possible I'd love to avoid needing a backing database if I can use just the cache in the mobile app, but with long lists. Is there something similar to this https://pub.dev/packages/graphql_flutter#fetch-more-pagination

Impossível criar testes unitários usando hasura_connect

Olá,

Estou tentando escrever meus testes unitários dos meus repositórios, mas toda vez que eu faço uma query usando o hasura_connect é lançado a excessão abaixo:

FormatException: Unexpected end of input (at character 1)
  
  ^
  
  dart:convert                                                     jsonDecode
  package:hasura_connect/src/core/hasura_connect_base.dart 327:18  HasuraConnectBase._sendPost

Minha classe de testes é bem simples:

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

void main() {

  TestWidgetsFlutterBinding.ensureInitialized();

  test('Should return a collection of user models', () async {
    SharedPreferences.setMockInitialValues({});
    HasuraConnect connect = HasuraConnect('https://********/v1/graphql', headers: {'x-hasura-admin-secret': '*********'});
    dynamic result = await connect.query('query getAllUsers { user { id, name, email} }');
    print(result);
    expect(1, 1);
  });
  
}

O problema só acontece rodando testes unitários através de flutter test. Se rodar o mesmo bloco de código dentro da aplicação funciona PERFEITAMENTE.

Alguma luz?

Connection Refuse

Hi,
I try using this plugin with a Docker container on localhost, but when I try connect to Hasura I receive an error message like this:

I/flutter ( 3258): SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 37136

This occur when I execute:

HasuraConnect('http://localhost:8080/v1/graphql');

The Hasura console is running on localhost port 8080 but I cant connect in it,[

Anybody know how fix this?

Thanks

Falta melhorar o aviso de erros de conexão.

Para ficar mais pratico ainda, coloque para alertar os erros de conexão que ocorrem, tive q colocar 1 print dentro do catcherror, pois não era possivel visualizar no catcherror do future;

Semantic version

I could not understand how the process of defining a new version works.

Are you using semantic version? Where are the changes that have occurred between versions documented?

The way this lib is being maintained is confusing. Aren't you creating tags for each version that is released?

[Mutation]How to prevent update from server when we already updated in cache ?

import 'dart:async';

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

final connect = HasuraConnect(
'https://hasura-qlwk.onrender.com/v1/graphql',
);
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@OverRide
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Home());
}
}

class Home extends StatefulWidget {
const Home({Key key}) : super(key: key);

@OverRide
_HomeState createState() => _HomeState();
}

class _HomeState extends State {
List items = [];
StreamSubscription _streamSubscription;
Snapshot snapshot;
String readRepositories = """
subscription MySubscription($limit: Int, $offset: Int) {
user(order_by: {username: asc}, limit: $limit, offset: $offset) {
username
id
email
online
}
}
""";
var update = """
mutation MyMutation($_set: user_set_input , $where: user_bool_exp!) {
update_user(where: $where, _set: $_set) {
returning {
id
}
}
}
""";
var delete = """
mutation MyMutation($where: user_bool_exp!) {
delete_user(where: $where) {
returning {
id
}
}
}
""";
@OverRide
void initState() {
super.initState();
_load();
}

@OverRide
void dispose() {
_streamSubscription?.cancel();
super.dispose();
}

void _load() {
snapshot = connect
.subscription(readRepositories, variables: {"offset": 0, "limit": 2});
_streamSubscription = snapshot.listen((event) {
setState(() {
items = event["data"]["user"];
});
});
}

Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Hasura Graphql"),
),
body: Column(
children: [
Flexible(
child: ListView.builder(
itemCount: items.length,
itemBuilder: (_, index) {
Map<String, dynamic> item = items[index];
return ListTile(
leading: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
connect.mutation(delete, variables: {
"where": {
"id": {"_eq": items[index]["id"]}
},
});
},
),
title: Text(item["username"] ?? ""),
subtitle: Text(item["email"] ?? ""),
trailing: Checkbox(
value: item["online"] ?? false,
onChanged: (value) async {
var newItem = Map<String, dynamic>.from(item);
newItem["online"] = value;
var index = items.indexOf(item);
items.remove(item);
items.insert(index, newItem);
snapshot.add({
"data": {"user": items}
});
connect.mutation(update, variables: {
"where": {
"id": {"_eq": items[index]["id"]}
},
"_set": newItem
});
},
),
);
},
),
),
],
),
);
}
}

I have a problema when my filter like have an accentuation

When i put a filter with accentuation in connect.subscription(getAllQuery) just doesn't respond and keeps trying and trying to loop

subscription getAllProduto {
produto(where: {descricao: {_ilike: "%feijão%"}}, order_by: {descricao: asc}) {
id
descricao
}
}

And when i put only _ilike: "%feij%" it´s work perfectly. Do you know what´s de problem?

Keep getting "Try again..." in logs after token expires

I'm using firebase which uses tokens that expire after 1 hour.
In my code when going to make a call to hasura before making the call I check the expiry time of the token and will refresh it if it's about to expire.

That's all working fine.
My issue is that if I've got some subscriptions going and leave the app for an hour, I start getting "Try again..." repeated in the logs every 2 seconds.

Is this because the websockets fail once the token expires even though I've not made any direct calls to any new queries/mutations etc?

Can you think of a way to stop this happening?

Unhanbled Exception: Bad state: Cannot add new events after calling close

Bom tarde, estou utilizando hasura_connect para estabelecer uma subscription ao Hasura.

Configurei o HasuraConnect para ser injetado nas dependências do app.module.

Criei também um Repository que recebe o HasuraService (criado por mim que só armazena uma instância do HasuraConnect) onde eu recupero a instância do HasuraConnect.

app.module (dependências)
Captura de Tela_selecionar área_20191119144514

HasuraService
Captura de Tela_selecionar área_20191119144629

Chamando o subscription no repository
Captura de Tela_selecionar área_20191119144933

A chamada no bloc
Captura de Tela_selecionar área_20191119145100

Implementei as minas páginas para ficar ouvindo as subscription via bloc somente quando a mesma estivesse ativa (o bloc da um close no snapshot ativo para aquela conexão), mas quando a página é fechada e aberta novamente ocorre uma exceção que pode ser visto na imagem.

Captura de Tela_selecionar área_20191119144159

Debug query

Hi guys, i'm trying to debug what kind of error hasura is returning in my query, but the hasura only returns "HasuraError: connection error" in my query, how can i see whats wrong with the query?

Connection utilization

Hello,

I wanna have total control of the connections of hasura, but I don't understand how to connections works.

If I make a query in my server of hasura, this makes 2 or 4 connections, but I don't understand why.

Someone know what is it? How I can control these connections? I wanna only open a connection, make a query, and close it immediately. There run out of the purpose of the GraphQL hasura?

I very worry about free connections limitation of hasura. Someone have some experince about this here and wanna share here?

thank you!

'stream' isn't defined for the class 'Snapshot'.

Hi,
I has a project with HasuraConnect 0.2.0 and when I try update to 1.0.0 it give and error:

    Snapshot snapshot = connection.subscription(query, variables: {"id": id});
    return snapshot.stream.map(
      (jsonList) => Order.fromJsonList(jsonList["data"]["orders"]),
    );

The getter 'stream' isn't defined for the class 'Snapshot'.
Try importing the library that defines 'stream', correcting the name to the name of an existing getter, or defining a getter or field named 'stream'.

How can fix this?
Thanks,

Subscription returning wrong (cached) result.

I have a subscription that takes in an ID. The first time this subscription is made, the correct information is returned. Every subsequent time the subscription is made, it returns data matching the initial subscription, regardless if the ID has changed.

Erro apenas importando a package

Criei um projeto do zero sem mudar uma linha....
flutter create nome_projeto
slidy start
rodei o build la para gerar os .G
inclui o hasura_connect
quando apenas declaro a importação do package do hasura ja da erro

Compiler message:
/D:/src/flutter/.pub-cache/hosted/pub.dartlang.org/hasura_connect-1.2.0/lib/src/utils/hydrated.dart:6:7: Error: The non-abstract class 'HydratedSubject' is missing implementations for these members:

  • Subject.createForwardingController
    Try to either
  • provide an implementation,
  • inherit an implementation from a superclass or mixin,
  • mark the class as abstract, or
  • provide a 'noSuchMethod' implementation.

class HydratedSubject extends Subject implements ValueStream {
^^^^^^^^^^^^^^^
/D:/src/flutter/.pub-cache/hosted/pub.dartlang.org/rxdart-0.24.0/lib/src/subjects/subject.dart:162:23: Context: 'Subject.createForwardingController' is defined here.
StreamController createForwardingController({
^^^^^^^^^^^^^^^^^^^^^^^^^^

Capturar
Capturar2

Suporte a Web

Estava testando o plugin com um projeto web porem ao utilizar:

HasuraConnect hasuraConnect = HasuraConnect...

Recebo este erro:

Unable to find modules for some sources, this is usually the result of either a
bad import, a missing dependency in a package (or possibly a dev_dependency
needs to move to a real dependency), or a build failure (if importing a
generated file).

Please check the following imports:

import 'package:hasura_connect/hasura_connect.dart'; from .../app/services/config/clientConfig.dart at 3:1

Failed after 112ms
Failed to build application for the Web.
Exited (sigterm)

*obs: utilizando o slidy para instalação.

Throttle e Debounce

In Angular I used to use debounce time to wait before send a new request to the server. There is some sort of way to prevent the user to send multiple requests simultaneous?
I apreciate your help. Thank you

Subscription - working with variables

Hi all,

I cant put to work the subscriptions with variables.

I created the follow subscription, that its working on Graphiql:

graphiql

And write this flutter code:

String docSubscription = """
      subscription netideias_tasks($limit:Int!){
        netideias_tasks(limit: $limit) {
          id,
          title,
          estimated_minutes
        }
      }
    """;
hasuraConnect = HasuraConnect(url, headers: {'x-hasura-admin-secret': '...'});
Snapshot snapshot = hasuraConnect.subscription(docSubscription, variables: {"limit": 10});

And i'm getting the following error:

HasuraError: not a valid graphql query

{type: complete, id: c3Vic2NyaXB0aW9ubmV0aWRlaWFzdGFza3MxMEludG5ldGlkZWlhc3Rhc2tzbGltaXQxMGlkdGl0bGVlc3RpbWF0ZWRtaW51dGVz}

If i remove the limit variable everything works great!

What i'm doing wrong?

Abraços!

Method addHeader() is not working

Hi, I would like to report that hasura_connect on version 1.0.5, the method addHeader() is not working properly.

Steps to Reproduce:

  1. Create a flutter new project
  2. Add hasura_connect to dependencies on pubspec.yaml
  3. Do the following in the _incrementCounter() method of _MyHomePageState:
String query = "query MyQuery {company {name}}";
HasuraConnect connect = HasuraConnect('http://localhost:8080/v1/graphql');
connect.addHeader('x-hasura-admin-secret', 'secret');
connect.query(query).then((results) {
  print(results);
});
  1. Then try to run the application on emulator/device.
  2. Click on the FAB to increment the counter.
  3. The error is thrown

════════ Exception caught by gesture >═══════════════════════════════════════════
The following NoSuchMethodError was thrown while handling a gesture:
The method '[]=' was called on null.
Receiver: null
Tried calling: []=("x-hasura-admin-secret", "secret")

When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 HasuraConnectBase.addHeader
package:hasura_connect/…/core/hasura_connect_base.dart:49
#2 _MyHomePageState._incrementCounter
package:hasura_connect_test/main.dart:60
#3 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:706
#4 _InkResponseState.build.
package:flutter/…/material/ink_well.dart:789
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#1e9ea
debugOwner: GestureDetector
state: ready
won arena
finalPosition: Offset(372.0, 849.0)
finalLocalPosition: Offset(30.0, 25.0)
button: 1
sent tap down
═════════════════════════════════════════════════════════════>═══════════════════

Important: If I use the HasuraConnect constructor and include the headers parameter, it works perfectly, but using the previous method doesn't.

I'll be using this approach for now:

String query = "query MyQuery {company {name}}";
HasuraConnect connect = HasuraConnect('http://localhost:8080/v1/graphql' headers: {
      'x-hasura-admin-secret': 'secret'
});
connect.query(query).then((results) {
  print(results);
});

Maybe initializing this propery (i.e: headers = {}) at this following line should fix the problem:

final Map<String, String> headers;

Erro Hive nova versão

Hello guys , segue erro que esta acontecendo.

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: 'package:hive/src/binary/frame.dart': Failed assertion: line 20 pos 13: '(key is int && key >= 0 && key < 4294967295) ||
E/flutter ( 1624): (key is String && key.length <= 255)': Unsupported key
E/flutter ( 1624): #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:40:39)
E/flutter ( 1624): #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
E/flutter ( 1624): #2 new Frame (package:hive/src/binary/frame.dart:20:13)
E/flutter ( 1624): #3 BoxImpl.putAll (package:hive/src/box/box_impl.dart:51:18)
E/flutter ( 1624): #4 BoxBase.put (package:hive/src/box/box_base.dart:92:45)
E/flutter ( 1624): #5 LocalStorageHasura.put (package:hasura_connect/src/services/local_storage_hasura.dart:65:15)
E/flutter ( 1624):
E/flutter ( 1624): #6 HydratedSubject._persistValue (package:hasura_connect/src/utils/hydrated.dart:125:25)
E/flutter ( 1624):
E/flutter ( 1624): #7 HydratedSubject.onAdd (package:hasura_connect/src/utils/hydrated.dart:78:5)
E/flutter ( 1624): #8 Subject._add (package:rxdart/src/subjects/subject.dart:135:5)
E/flutter ( 1624): #9 Subject.add (package:rxdart/src/subjects/subject.dart:131:5)
E/flutter ( 1624): #10 new SnapshotData. (package:hasura_connect/src/snapshot/snapshot_data.dart:52:21)

How to prevent multiple entry?

I am doing a mutation and data is being inserted more than once.
I have used tryAgain: false. Yet the problem persists.

Can anyone guide me here?

Separate the package in two Projects

1 - hasura_core || GraphQLCore
This need to work with Pure Dart
2 - hasura_connect
This will work on Flutter, today is not working cuz have the dependency of Foundation for @required and some places have dependency of Material

The idea is to have as few breakchanges as possible.

Cache

Hi,

Have you got a documentation or information about the cache?
I would like to setup the timeout.

Cheers

Alain

Cannot create queries and mutations with fragment

If creating a query using fragment, this condition will make graphql unfeasible

if (doc.trimLeft().split(" ")[0] != "query") {

Gql example:

fragment articleFields on articles {
  id
  title
}
query getArticles {
  articles {
    ...articleFields
  }
  topTwoArticles: articles(
    order_by: {rating: desc},
    limit: 2
  ) {
    ...articleFields
  }
}

The same will happen with a mutation:

if (doc.trim().split(" ")[0] != "mutation") {

Is JsonB column supported?

Hello thanks for this great library.

When using a Subscription with a JsonB column, it throws error

field (name) not found in type (table name)

Is JsonB column supported in hasura_connect? The same subscription query worked in GraphiQL console.

Thanks!

Changing Bearer token

I'm currently ok when I've got a new user, but if I logout and then log in as a different user I need to change the Bearer token.

I'd thought I might be able to disconnect the HasuraConnect object and start another to set the new token, but can't see a way to do that. I'm sure I'm just missing something pretty obvious

Desktop flutter support

I really like the simplicity of this package, however, recently with the change from hive to shared preferences my app that has a management part that needs to run on the desktop has stopped working, because the plugin does not support it. Are there plans to re-offer desktop support?

Give this package another name

Give this package another name since it is not an Hasure specific GraphQL client, or if it is, split the generic part into another package and keep the Hasura specification on this.

Improve error messages on posts

Hi,
I'm having a problem when execute a mutation code, it always returns the message: HasuraError: connection error, but when I went to check I realized that the error was caused by a wrongly named variable that I passed in the function call. but instead of telling me what the problem was, the plugin only says that there was a connection error which was not really.
If you can fix this I appreciate it.

Thanks

error handling

cannot get the error message in flutter app. only "HasuraError: connection error" is returned. Need to get the error message returned from hasura

Outdated usage of hive package

As per https://github.com/hivedb/hive/blob/7e6471fd55abdd2f0e9278d30816c1b54ff0ef46/CHANGELOG.md Hive.openBoxFromBytes has been deprecated. However, I'm also not completely sure if I used the package incorrectly.

Here is the error message I get when I try to do flutter run -d all:

../../flutter/.pub-cache/hosted/pub.dartlang.org/hasura_connect-1.0.3/lib/src/services/local_storage_hasura.dart:37:24: Error: The method 'openBoxFromBytes' isn't defined for the class 'HiveInterface'.
 - 'HiveInterface' is from 'package:hive/hive.dart' ('../../flutter/.pub-cache/hosted/pub.dartlang.org/hive-1.2.0/lib/hive.dart').
Try correcting the name to the name of an existing method, or defining a method named 'openBoxFromBytes'.
      box = await Hive.openBoxFromBytes(boxName, Uint8List(0));
                       ^^^^^^^^^^^^^^^^
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null

Here is my Dart code:

import 'package:hasura_connect/hasura_connect.dart';

String url = "my_url";
String query = "my query";

authenticateUser(userEmail, userPassword) async {
  HasuraConnect hasuraConnect = HasuraConnect(url);
  var res = await hasuraConnect.query(query);
  print(res);

}

Output from flutter doctor -v

[✓] Flutter (Channel stable, v1.12.13+hotfix.5, on Mac OS X 10.15.1 19B88, locale en-US)
    • Flutter version 1.12.13+hotfix.5 at /Users/agnesjang/dev/flutter
    • Framework revision 27321ebbad (3 weeks ago), 2019-12-10 18:15:01 -0800
    • Engine revision 2994f7e1e6
    • Dart version 2.7.0

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /Users/agnesjang/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.3, Build version 11C29
    • CocoaPods version 1.8.4

Any help would be much appreciated. Thanks so much!

Converter retorno de Query em List<Model>

Olá pessoal.

Estou tendo um problema para converter o retorno de uma Query, em uma lista de objetos.
Meu método responsável pela conversão está dessa forma:
image

E estou tendo o seguinte erro:
image

O erro só ocorre quando tento a conversão usando o Json retornado na query (sem aspas).

{
id: 1,
uf: PR,
estado: Paraná
}

Tentando a conversão com o Json retornado na interface do Hasura (com aspas), o erro não ocorre.

{
"id": 1,
"uf": "PR",
"estado": "Paraná"
}

Existe alguma outra solução que eu possa utilizar para fazer essa conversão, mesmo que o Json retorne sem as aspas?

Application first offline

First of all, we would like to thank you for the excellent package that makes integration with hasura easy.

In my case I want to develop an application first offline. Is it possible to achieve this with this package?

It is expected that offline mutations can persist so that they can be executed when the device is back online, and also to perform queries with the data I have stored in cache. In conclusion, achieve the offline functionality that has cloud firestore.

Looking forward to your response, thank you very much.

Ability to cache and pool for query

I have been using this package and its of great use

Can you add pooling and cacheing support if so then it will be ultimate

Any plans for them

Criar Testes Unitários

Precisamos criar teste unitários para poder automatizar atraves de CI/CD os deploys com segurança.

  • Criar testes para o hasura_connect_base.dart
  • Testes para o local_storage
  • Teste snapshot.dart
  • Teste de rotina com atualização de Token

Hive package issue

Hi,

I have an issue with Hive package so I can't send GraphQl data anymore.
Have you heard about this issue?

isar/hive#94

Regards

Alain

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.