Implement GraphQL & Flutter - dart

Is there a way to implement GraphQL in flutter?
I was trying making the API call with the query and variables objects in a JSON object.
type '_InternalLinkedHashMap' is not a subtype of type 'String' in type cast

I have been using graphql_flutter package for a few weeks now and it seems to work well enough. Here is an example:
import 'package:graphql_flutter/graphql_flutter.dart' show Client, InMemoryCache;
...
Future<dynamic> post(
String body, {
Map<String, dynamic> variables,
}) async {
final Client client = Client(
endPoint: endpoint,
cache: new InMemoryCache(),
);
final Future<Map<String, dynamic>> result =
client.query(query: body, variables: variables);
return result;
}
To use just give it the graphql and any variables. i.e. a delete mutation may look like
String deleteMutation =
'''mutation deleteItem(\$itemId: ID!) {
deleteItem(input: { itemId: \$itemId}) {
itemId
}
}'''.replaceAll('\n', ' ');
await post(deleteMutation , variables: <String, dynamic>{'itemId': itemId});

This is updated and working solution of #aqwert
import 'package:graphql_flutter/graphql_flutter.dart';
...
HttpLink link = HttpLink(uri: /*your url here*/); // you can also use headers for authorization etc.
GraphQLClient client = GraphQLClient(link: link as Link, cache: InMemoryCache());
QueryOptions query = QueryOptions(
document:
r'''
mutation deleteItem($id: String!) {
deleteItem(callId: $id)
}
''',
variables: {'id' : id}
);
var result = await client.query(query);

Related

createdAt updatedAt aqueduct

In mongoose, there's the timestamp: true option to a schema, which auto-populates a createdAt and updatedAt for any model item added.
Is there something similar in Aqueduct?
If not, how do I manually do so?
I currently tried this, which is failing, as usual:
#Operation.post()
Future<Response> createICD(#Bind.body() ICD body) async {
body.createdAt = DateTime.now();
final query = Query<ICD>(context)..values = body;
final insertICD = await query.insert();
return Response.ok({'state': true, 'data': insertICD});
}
Error from the above approach is:
Converting object to an encodable object failed: Instance of 'ICD'
It's failing when you send the response; you need to call asMap() on insertICD. The response body object you are providing is a standard Dart map - it doesn't have any special encoding behavior, so it doesn't know how to encode a complex type like ManagedObject. Invoke asMap() on the managed object to convert it to a standard Dart map:
#Operation.post()
Future<Response> createICD(#Bind.body() ICD body) async {
body.createdAt = DateTime.now();
final query = Query<ICD>(context)..values = body;
final insertICD = await query.insert();
return Response.ok({'state': true, 'data': insertICD.asMap()});
}
Also, see http://aqueduct.io/docs/db/validations/#update-and-insert-callbacks for setting timestamps at create/update events.

Push objects into array in Dart

List returnMovies = [];
Future<List> _getData() async {
final response = await http.get("https:../getTodayMovies",
headers: {HttpHeaders.AUTHORIZATION: Acess_Token.access_token});
if (response.body != null) {
returnMovies = json.decode(response.body);
.....
setState(() {});
} else {
final responseUpcoming = await http.get("/upcoming",
headers: {HttpHeaders.AUTHORIZATION: Acess_Token.access_token});
returnMovies = json.decode(responseUpcoming.body);
}
The response.body looks like:
[{"id":394470548,"host_group_name":"heyab redda","movie_image":"..png","type":"horror","code":"X123","name":"Lovely","start_time":1554364800,"end_time":1554393600,"}]
The responseUpcoming.body looks like:
{"id":394470545,"host_group_name":"foo redda","movie_image":".png","type":"horror","code":"X123","name":"Lovely","start_time":1554364800,"end_time":1554393600,"}, {"id":394470548,"host_group_name":"foo1 redda","movie_image":"..png","type":"comic","code":"X125","name":"Lovely1","start_time":1554364800,"end_time":1554393600,"}
The error I get is: String, dynamic is not a subtype of type List<dynamic>.
In the first API call that I am doing I normally get in return an array of objects, however, when this is empty, the second API call returns a list of objects that I want to push into the array called returnMovies, how can I achieve this?? Is there any way to .push these objects in the array?? So then I want to use this array to build dynamically a Listview.builder.
Also is it correct the way I am declaring it? I am quite new on Dart. Thank you
Sounds like you are looking for addAll
returnMovies.addAll(json.decode(returnUpcoming.body))
I will suggest to use
returnMovies.addAll({your object here})
When you do this json.decode(response.body) you are getting a List of Map you should use List<dynamic> movieListData and get the items like this:
movieListData = json.decode(response.body);
returnMovies = movieListData.map((dynamic movieData) {
String id = movieData['_id'];
String host_group_name = movieData['host_group_name'];
String duration = movieData['duration'];
return new Movie(id,title, duration);
}).toList();

Why toList() creates a List<dynamic> in Dart?

I have this method, which compiles with no problems in Dart 2. However at run-time I get the following error
type 'List<dynamic>' is not a subtype of type 'List<ExchangeRate>'
As you see in the code I create and return new ExchangeRate objects within .map() and then after that I return a rateEntries.toList() which I expect to be of type List<ExchangeRate>, however it seems to be inferred as type List<dynamic>!!!
#override
Future<List<ExchangeRate>> getExchangeRatesAt(DateTime time, Currency baseCurrency) async {
final http.Client client = http.Client();
final String uri = "some uri ...";
return await client
.get(uri)
.then((response) {
var jsonEntries = json.decode(response.body) as Map<String, dynamic>;
var rateJsonEntries = jsonEntries["rates"].entries.toList();
var rateEntries = rateJsonEntries.map((x) {
return new ExchangeRate(x.value.toDouble());
});
return rateEntries.toList(); // WHY IS IT RETURNING A List<dynamic> here?
})
.catchError((e) => print(e))
.whenComplete(() => client.close());
}
However if I cast it specifically to ExchangeRate it would be fine.
return rateEntries.toList().cast<ExchangeRate>();
This casting at the end seems redundant to me, why should I need it?
Well, it seems that the cast is necessary to fully define the type.
But, you can avoid the cast if you add any of the following snippets:
Give the correct type to the rateJsonEntries variable
List<dynamic> rateJsonEntries = jsonEntries["rates"].entries.toList();
For whatever reason this works in my case.
Add the parameter type to the map() method
var rateEntries = rateJsonEntries.map<ExchangeRate>((x) {
return new ExchangeRate(x.value.toDouble());
});

Testing a Dart API wrapper

I am currently writing an API wrapper for wit.ai. I'd like to add tests to this wrapper but I am unsure how I'd do that given that I'm using the http library to send HTTP requests.
The code would look something like this:
Future message(String q) {
Map<String, String> headers = {
'Accept': 'application/vnd.wit.${apiVersion}+json',
'Authorization': 'Bearer ${token}'
};
return http
.get('https://api.wit.ai/message?q=${q}', headers: headers)
.then((response) {
return JSON.decode(response.body);
}).catchError((e, stackTrace) {
return JSON.decode(e);
});
}
Given this code, how would I write a test that does not actually send a HTTP request?
This is traditionally solved by dependency injection. Your API wrapper class could have a constructor like:
class MyWrapper {
final http.BaseClient _httpClient;
MyWrapper({BaseClient httpClient: new http.Client()})
: _httpClient = httpClient;
// ...
}
Using a named argument with a default value means normal users won't need to worry about creating the Client.
In your method, you use the Client instead of using the static methods of the http library:
Future message(String q) {
Map<String, String> headers = {
'Accept': 'application/vnd.wit.${apiVersion}+json',
'Authorization': 'Bearer ${token}'
};
return _httpClient
.get('https://api.wit.ai/message?q=${q}', headers: headers)
.then((response) {
return JSON.decode(response.body);
}).catchError((e, stackTrace) {
return JSON.decode(e);
});
}
Keep in mind, though, that clients need to be closed. If you don't have a close method on your API wrapper, you may want to a) add it, or b) put the dependency injection on the message() method instead of on the constructor.
When testing, set up a MockClient. Pass it like so:
var wrapper = new MyWrapper(httpClient: myMockClient);
No need for running a local server, and way faster.

How do I get query parameters in the URL

In Dart I am working on a web game. In this I would need a function where I can get data from the URL, in the same way that you would get it in PHP. How would I do this?
Say I, for example, append the following to my URL when I load my web game: ?id=15&randomNumber=3.14. How can I get them in Dart either as a raw string (preferred) or in some other format?
You can use the Uri class from dart:core
https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.Uri
ie:
main() {
print(Uri.base.toString()); // http://localhost:8082/game.html?id=15&randomNumber=3.14
print(Uri.base.query); // id=15&randomNumber=3.14
print(Uri.base.queryParameters['randomNumber']); // 3.14
}
import 'dart:html';
void doWork(){
var uri = Uri.dataFromString(window.location.href); //converts string to a uri
Map<String, String> params = uri.queryParameters; // query parameters automatically populated
var param1 = params['param1']; // return value of parameter "param1" from uri
var param2 = params['param2'];
print(jsonEncode(params)); //can use returned parameters to encode as json
}
Import 'dart:html' then you can use window.location...

Resources