Browse Source

added documentation

master
TheNils 1 month ago
parent
commit
3eb7aada50
2 changed files with 76 additions and 70 deletions
  1. +0
    -59
      android/app/src/samples/async.dart
  2. +76
    -11
      lib/store/itemsController.dart

+ 0
- 59
android/app/src/samples/async.dart View File

@ -1,59 +0,0 @@
// demonstrate how to handle async and retry on error
import 'dart:convert';
// with try catch
Future<String> fetchUserOrder(bool isError) async {
String throwOrPass(bool isError2) {
if (isError2) {
throw Exception('Logout failed: user ID is invalid');
} else {
return 'blabla';
}
}
try {
var res =
await Future.delayed(Duration(seconds: 2), () => throwOrPass(isError));
return 'success';
} catch (err) {
return fetchUserOrder(false);
}
}
Future<void> main() async {
var t = fetchUserOrder(true);
print(t);
var after = await t;
print(after);
return t;
}
// with .then().catchError()
Future<Map<String, dynamic>> fetchUserOrder2(bool isError) async {
// Imagine that this function is fetching user info but encounters a bug
String throwOrPass(bool isError2) {
if (isError2) {
throw Exception('Logout failed: user ID is invalid');
} else {
return 'blabla';
}
}
return await Future.delayed(Duration(seconds: 2), () => throwOrPass(isError))
.then((res) {
return jsonDecode('{"message":"success"}');
}).catchError((err) {
return jsonDecode('{"message":"error"}');
});
}
Future<void> main2() async {
var t = fetchUserOrder2(false);
print(t);
var after = await t;
print('blabla ${after['message']}');
return t;
}

+ 76
- 11
lib/store/itemsController.dart View File

@ -9,6 +9,56 @@ import 'package:directus_starter/api/api.dart';
import 'package:localstorage/localstorage.dart';
// import 'package:directus_starter/globals.dart';
/// #### Base class for creating GetX Stores synced with a directus api
///
/// - **[collection]** must be the same as the directus collection name
/// - if **[storeLocallly]** is set to true data will be saved on device storage and loaded on next launch
/// - **[fields]** is a list of directus colelction fields. Relational fields can be included but create/patch/delete methods will mostly not work for them
/// - **[orderBy]** is placeholder and need to be implemented
///
/// ##### Usage example
///
/// lets say we have a collection named *car*:
/// ```
/// {
/// id: UUID,
/// color: String,
/// model: String,
/// brand: String,
/// }
/// ```
/// Create a new class that extends **ItemsController**
/// `@/store/carsController.dart`
/// ```
/// import 'package:directus_starter/store/itemsController.dart';
///
/// class CarsController extends ItemsController {
/// CarsController()
/// : super("car", fields: ['*']) {
/// return;
/// }
///}
/// ```
///
/// use it as a Getx Controller in the view :
/// ```
///
/// class CarDemo extends StatelessWidget{
/// final CarsController carsController = Get.put(carsController());
///
/// @override
/// Widget build(BuildContext context){
/// return Scaffold(
/// appBar: AppBar(...),
/// body: Center(
/// child: Obx( () => Text(carsController.items[0]["model"]) )
/// )
/// )
/// }
/// }
///
/// ```
class ItemsController extends GetxController {
final _api = Api();
var _localStorage;
@ -31,10 +81,10 @@ class ItemsController extends GetxController {
}
get items => _items();
set items(payload) {
_items(payload);
_localStorage.setItem(_collection, jsonEncode(items));
}
// set items(payload) {
// _items(payload);
// _localStorage.setItem(_collection, jsonEncode(items));
// }
get itemsMappedOnId =>
Map.fromIterable(items, key: (v) => v["id"], value: (v) => v);
@ -52,7 +102,7 @@ class ItemsController extends GetxController {
var localItems = await _localStorage.getItem(_collection);
if (localItems != null) {
items = jsonDecode(localItems);
_items.value = jsonDecode(localItems);
}
}
if (_items().length > 0) {
@ -66,11 +116,14 @@ class ItemsController extends GetxController {
super.onInit();
}
/// Fetch the collection items from a directus API.
///
/// may be used to refresh the entire state
Future<bool> fetch() async {
var res = await _api.get("/items/$_collection?fields=${_fields.join(",")}");
var isOk = handleResponse(res);
var isOk = _handleResponse(res);
if (isOk) {
items = res;
_items.value = res;
_items.refresh();
}
isFeeded(true);
@ -78,9 +131,13 @@ class ItemsController extends GetxController {
return isOk;
}
/// Create a new item that is added to [this.items]
///
/// [item] must be a single item with no id field
/// return [false], display a snackbar with the error message and do not updat the state if the API reject the request
Future<bool> create(Map<dynamic, dynamic> item) async {
var res = await _api.post("/items/$_collection", item);
var isOk = handleResponse(res);
var isOk = _handleResponse(res);
if (isOk) {
_items().add(res);
_items.refresh();
@ -88,9 +145,13 @@ class ItemsController extends GetxController {
return isOk;
}
/// Delete an item from [this.items]
///
/// [id] the id of the item to delete
/// return [false], display a snackbar with the error message and do not updat the state if the API reject the request
Future<bool> delete(dynamic id) async {
var res = await _api.delete("/items/$_collection/$id");
var isOk = handleResponse(res);
var isOk = _handleResponse(res);
if (isOk) {
_items().removeWhere((element) => element["id"] == id);
_items.refresh();
@ -98,12 +159,16 @@ class ItemsController extends GetxController {
return isOk;
}
/// Update an item from [this.items]
///
/// [item] the item to update, must contain an id field
/// return [false], display a snackbar with the error message and do not updat the state if the API reject the request
Future<bool> patch(Map<dynamic, dynamic> item) async {
var sanitized = {...item};
sanitized.remove("id");
var res = await _api.patch("/items/$_collection/${item["id"]}", sanitized);
var isOk = handleResponse(res);
var isOk = _handleResponse(res);
if (isOk) {
var itemIndex = _items().indexWhere((value) => value["id"] == item["id"]);
_items()[itemIndex] = {..._items()[itemIndex], ...item};
@ -113,7 +178,7 @@ class ItemsController extends GetxController {
return isOk;
}
bool handleResponse(res) {
bool _handleResponse(res) {
if (res is List) {
return true;
} else if (res is Map && res.containsKey("errors")) {


Loading…
Cancel
Save