angel3_client 10.0.0
angel3_client: ^10.0.0 copied to clipboard
A browser, mobile and command line based client that supports querying Angel3 servers
Angel3 Client #
A browser, mobile and command line based client that supports querying Angel3 backend.
Installation #
In your pubspec.yaml:
dependencies:
angel3_client: ^10.0.0
Usage #
// Choose one or the other, depending on platform
import 'package:angel3_client/io.dart';
import 'package:angel3_client/browser.dart';
import 'package:angel3_client/flutter.dart';
void main() async {
var app = Rest('http://localhost:3000');
}
You can call service to receive an instance of Service, which acts as a client to a service on the server at the given path (say that five times fast!).
foo() async {
var todos = await app.service('todos').index();
print(todos.length);
}
To work with your own classes instead of Maps, pass a deserializer. With angel3_serialize, you can use the same model class on the client and the server.
@serializable
abstract class TodoEntity extends Model {
String? get text;
}
bar() async {
// `TodoSerializer` is generated by `angel3_serialize`.
var todos = app.service<String, Todo>(
'todos',
deserializer: (x) => TodoSerializer.fromMap(x as Map),
);
List<Todo> list = await todos.index();
print(list.length);
}
The client does not use dart:mirrors. Without a deserializer, a service returns the decoded JSON, such as a Map. Objects sent to the server are encoded with jsonEncode, which calls their toJson().
Just like on the server, services support index, read, create, modify, update and remove.
Authentication #
Local auth:
var auth = await app.authenticate(
type: 'local',
credentials: {'username': ..., 'password': ...},
);
print(auth.token);
print(auth.data); // User object
Revive an existing jwt:
var auth = await app.reviveJwt(jwt);
Via Popup:
app.authenticateViaPopup('/auth/google').listen((jwt) {
// Do something with the JWT
});
Resume a session from localStorage (browser only, with the Rest of package:angel3_client/browser.dart, whose type is optional):
// Automatically checks for JSON-encoded 'token' in localStorage,
// and tries to revive it
await app.authenticate();
Logout:
await app.logout();
Live Updates #
Oftentimes, you will want to update a collection based on updates from a service. Use ServiceList for this case:
Widget build(BuildContext context) {
var list = ServiceList(app.service('api/todos'));
return StreamBuilder(
stream: list.onChange,
builder: _yourBuildFunction,
);
}
Migrating from 9.x to 10.0.0 #
Typed services: pass a deserializer instead of type #
The type parameter of service() and the belatuk_json_serializer dependency are removed, because they needed dart:mirrors. Pass a deserializer that builds your class from the decoded JSON. With angel3_serialize, that is the generated fromMap:
// 9.x
var todos = app.service<String, Todo?>('todos', type: Todo);
// 10.0.0
var todos = app.service<String, Todo>(
'todos',
deserializer: (x) => TodoSerializer.fromMap(x as Map),
);
Without a deserializer, a service returns the decoded JSON, such as a Map. In 9.x, Rest.service() also ignored the deserializer it was given, so check any code that relied on getting raw Maps back while passing one.
Data no longer has to be nullable: service<String, Todo>() works, where 9.x needed Todo?.
Objects sent to the server are encoded with jsonEncode, which calls their toJson(). Classes generated by angel3_serialize already have one. Give your own classes a toJson(), or pass a Map.
Errors: catch AngelHttpException #
In 9.x, when a stream such as onRead had a listener, a failed request added the error to that stream and the method returned null. In 10.0.0, index, read, create, modify, update and remove always return Data and throw an AngelHttpException on an error. The error still goes to the stream's listeners too.
// 9.x
var todo = await todos.read('1');
if (todo == null) {
// The request failed
}
// 10.0.0
try {
var todo = await todos.read('1');
} on AngelHttpException catch (e) {
print(e.statusCode);
}
Data that cannot be encoded as JSON, such as an object without a toJson(), is thrown as an ArgumentError before the request is sent. An error thrown by a toJson(), and a failure to send the request, such as a ClientException, are thrown as they are. None of these is added to the stream, since they are not events of the service.
When the response is a success but cannot be read, for example because the deserializer throws, the AngelHttpException has status code 500 and the original error is in error:
try {
await todos.read('1');
} on AngelHttpException catch (e) {
print(e.statusCode); // 500
print(e.error); // The error thrown by the deserializer
}
Query params: lists are sent as repeated params #
A list param is sent as one param per value, and an empty list throws an ArgumentError, since leaving it out would drop the filter:
await todos.index({'tag': ['a', 'b']});
// 9.x: ?tag=%5Ba%2C+b%5D (the text "[a, b]")
// 10.0.0: ?tag=a&tag=b
If the server expects the old text, pass it yourself: {'tag': '[a, b]'}. The query of the client's base URL, such as ?key=x, is now kept when params are passed.
Streams: listen before the event happens #
The streams of the client (onAuthenticated), its services (onIndexed, onRead and the others) and ServiceList.onChange are broadcast streams. They accept more than one listener, but they do not keep events for later listeners. Listen before you call the method whose event you want:
// 9.x: the event was buffered until someone listened
await todos.create(todo);
todos.onCreated.listen(print);
// 10.0.0: listen first
todos.onCreated.listen(print);
await todos.create(todo);
close() now completes even when nothing listens to the streams; in 9.x it could wait forever.