Compare commits

..
Author SHA1 Message Date
hugo 2a4e29f38c chore(release): publish packages
- wyatt_architecture@0.1.0
 - wyatt_authentication_bloc@0.4.0+2
 - wyatt_crud_bloc@0.1.0+1
 - wyatt_form_bloc@0.2.0+1
2022-12-03 20:40:23 -05:00
hugo ca70f2eb1d feat(authentication)!: add repo in callback usecases (close #55) 2022-12-03 18:53:20 -05:00
hugo f123e537ae fix(authentication): allow email/password validators customization (closes #57) 2022-12-03 18:41:04 -05:00
AN12345 c3315d968c refactor(bloc_helper)!: update onWrap label (close #46) 2022-11-24 18:16:20 -05:00
AN12345 45312473d1 feat: add gen-class-models in melos scripts 2022-11-24 17:55:07 -05:00
AN12345 17e7bce9e6 refactor(architecture): update naming methodes (close #47) 2022-11-24 17:25:44 -05:00
hugo 3886ef080e fix(crud)!: use FutureOrResult extension (close #42) 2022-11-24 15:24:59 -05:00
hugo 626d951443 fix(authentication)!: use FutureOrResult extension (close #41) 2022-11-24 11:18:16 -05:00
hugo f36e0b51e0 feat(type): add Result extension on FutureOr type (close #40) 2022-11-23 19:13:04 -05:00
AN12345 80ce7aff91 fix(architecture): fix execute method on error handler. (#38) 2022-11-23 23:11:04 +00:00
AN12345 a9121b6862 refactor(architecture): update example. (close #38) 2022-11-23 23:11:04 +00:00
AN12345 54f92e8042 docs(architecture): generate class model. (#38) 2022-11-23 23:11:04 +00:00
AN12345 00393a6ba7 docs(architecture): update Readme. (#38) 2022-11-23 23:11:04 +00:00
AN12345 136e0e8c98 chore(architecture)!: update exports. (#38) 2022-11-23 23:11:04 +00:00
AN12345 500a6ae51d feat(architecture): update usecase en add & sepcific case. (#38) 2022-11-23 23:11:04 +00:00
AN12345 79fdde25fc feat(architecture): add obsevers for alternative usecase scenarions (#38) 2022-11-23 23:11:04 +00:00
Malo Léon 742bf1d614 Merge pull request 'config/update_project_management' (#32) from config/update_project_management into master
Reviewed-on: #32
Reviewed-by: Hugo Pointcheval <hugo@noreply@wyatt-studio.fr>
2022-11-22 02:33:48 +00:00
AN12345 0dbde68d7d typo: fix readme typo error 2022-11-21 21:32:36 -05:00
AN12345 cd881da072 doc: update readme 2022-11-21 21:20:25 -05:00
AN12345 5918a5cf1f doc: add simple workflow diagramm 2022-11-21 21:20:01 -05:00
AN12345 775d766d14 build: update melos configuration and update targets 2022-11-21 20:59:36 -05:00
AN12345 383098b147 build: add mason configuration files 2022-11-21 20:59:02 -05:00
AN12345 4d51e2b786 build: add coverage script 2022-11-21 20:58:18 -05:00
AN12345 32cc1f55d9 chore: update gitignore 2022-11-21 20:57:52 -05:00
AN12345 6ee101bf36 doc: update readme 2022-11-21 20:54:57 -05:00
hugo f0ed08bd49 feat(auth): add reloadCache method in AuthenticationCubit 2022-11-16 19:52:24 -05:00
hugo 390fb81b1e fix(auth): fix stream account, now including correctly extra data 2022-11-16 19:51:45 -05:00
hugo 279d451cd8 fix(auth): fix mock isNewUser 2022-11-16 19:48:03 -05:00
63 changed files with 1130 additions and 217 deletions
+4 -1
View File
@@ -197,4 +197,7 @@ $RECYCLE.BIN/
.idea/
*.iml
google-services.json
pubspec_overrides.yaml
pubspec_overrides.yaml
# Mason
.mason/
+38
View File
@@ -3,6 +3,44 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## 2022-12-03
### Changes
---
Packages with breaking changes:
- [`wyatt_architecture` - `v0.1.0`](#wyatt_architecture---v010)
Packages with other changes:
- [`wyatt_authentication_bloc` - `v0.4.0+2`](#wyatt_authentication_bloc---v0402)
- [`wyatt_crud_bloc` - `v0.1.0+1`](#wyatt_crud_bloc---v0101)
- [`wyatt_form_bloc` - `v0.2.0+1`](#wyatt_form_bloc---v0201)
Packages with dependency updates only:
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
- `wyatt_authentication_bloc` - `v0.4.0+2`
- `wyatt_crud_bloc` - `v0.1.0+1`
- `wyatt_form_bloc` - `v0.2.0+1`
---
#### `wyatt_architecture` - `v0.1.0`
- **REFACTOR**: update naming methodes (close #47).
- **REFACTOR**: update example. (close #38).
- **FIX**: fix execute method on error handler. (#38).
- **FEAT**: update usecase en add & sepcific case. (#38).
- **FEAT**: add obsevers for alternative usecase scenarions (#38).
- **DOCS**: generate class model. (#38).
- **DOCS**: update Readme. (#38).
- **BREAKING** **CHORE**: update exports. (#38).
## 2022-11-16
### Changes
+131 -23
View File
@@ -1,17 +1,17 @@
<!--
* Copyright (C) 2022 WYATT GROUP
* Please see the AUTHORS file for details.
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
-->
@@ -51,39 +51,54 @@ and open source.
---
## Development
## Contribution
Clone this repo.
You have to install [melos](https://github.com/invertase/melos).
```shell
git clone ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-packages.git
```
### Prerequisite
- [Flutter](https://github.com/flutter/flutter).
- [Melos](https://github.com/invertase/melos). Used to manage Dart projects with multiple packages.
```shell
dart pub global activate melos
```
Then bootstrap with `melos bs`.
- [Mason](https://github.com/felangel/mason). Used for code generation.
```shell
dart pub global activate mason_cli
```
- [Lcov](https://github.com/linux-test-project/lcov). Used to generate coverage data.
```shell
# on macos
brew install lcov
```
- genhtml. Used to convert coverage data into html pages.
After installing all these packages, bootstrap with `melos bs`.
### Create a new package
Create a new package in `packages/` folder.
```shell
dart create -t package-simple wyatt_<name>
```
Remove any `example/` subfolder. Then create a new sample project.
```shell
flutter create --platforms android --project-name <name>_example example
mason make wyatt_package --package_name wyatt_<name> --description A new Wyatt package --flutter_only false
```
Then bootstrap project with `melos bs` command.
### Convention
#### Naming
In the previous instructions `<name>` variable is important.
In the previous instructions `<name>` variable is important.
It have to be clear and intelligible.
You **MUST** use underscores.
@@ -93,15 +108,44 @@ You **MUST** use `wyatt` prefix for package.
You **MUST** name example with specific name.
For example, if name is CRUD BLOC
- name will be crud_bloc
- so the package will be: `wyatt_crud_bloc`
- and the example will be: `crud_bloc_example`
#### Commits
### Create issues
Add the issues directly related to what you want to develop and label them correctly.
```
Type(scope): issue.
```
For example, on notification bloc package :
- `Feature(notification_bloc): add firebase messaging data source.`
- `Test(notification_bloc): add test for pushwoosh datasource.`
### Branches
Master is protected. You can't push on it. Please develop your feature on another branch. The name of your branch has to match with the issue opened.
`type(scope):issue`
Example :
Issue :
- `Feature(notification_bloc): add firebase messaging data source.`
Branch related to this issue :
- `feature(notification_bloc)/add_firebase_messaging_data_source`
### Commits
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
tl;dr : `type(scope): description`.
tl;dr : `type(scope): description #issue`.
Here allowed <type> values:
- **feat** for a new feature for the user, not a new feature for build script. Such commit will trigger a release bumping a MINOR version.
@@ -115,11 +159,68 @@ Here allowed <type> values:
Some examples :
- `feat(auth): add AWS support.` = add a feature in authentication_bloc package.
- `feat(auth): add AWS support. (#31)` = add a feature in authentication_bloc package, linked to the 31st issue.
- `docs: update readme.` = update **this** readme file.
- `fix(crud)!: fix bug in awesome() function.` = fix a bug, `!` is important and indicate `BREAKING CHANGES`.
- `fix(crud)!: fix bug in awesome() function. (#32)` = fix a bug, `!` is important and indicate `BREAKING CHANGES` linked with the 32nd issue.
Conventional commits are important for `melos version` command !
When you have finished developing, and are ready to close the issue, close it via your commit :
`feat(auth): add AWS support. (close #31)`
Note that your issue will be close after merging on master.
Before closing the issue, please check tests and update coverage. You might run :
```shell
melos run test
melos run gen_coverage
```
#### Merge your work
After closing your issue, some work may have been done on master in the meantime. To keep a clean git history, please rebase before opening a change request.
Two situations :
- You have not yet created your branch and have committed locally :
```shell
git pull --rebase
```
- You are already working on your branch :
```shell
git rebase -i master
```
If possible, please use `--fixup` on your commit in interactive rebase.
Then, opend your PR, get the necessary approval and merge your work. Then you're done ✅.
#### Update version.
Once your work is on the master, you can update your package version. Please filter packages to update only your package. `--scope` is used to do it.
For example, after merging changes on `wyatt_otification_bloc` package, you might run :
```shell
melos version --scope="*wyatt_notification_bloc*"
```
In fact, melos will filter all packages that match the `wyatt_notification_block` pattern.
You can update check all packages tests by running :
```shell
melos run test
```
#### Publish your package
If package is ready for procution, publish it runnig :
```shell
melos publish --scope"*package*"
```
#### Badging
@@ -130,7 +231,8 @@ In the package `readme.md` file, please specify the supported SDK:
```markdown
![SDK: Dart & Flutter](https://img.shields.io/badge/SDK-Dart%20%7C%20Flutter-blue?style=flat-square)
```
or
or
![SDK: Dart](https://img.shields.io/badge/SDK-Dart-blue?style=flat-square)
@@ -161,4 +263,10 @@ Here you can change `package name` and `package version`.
![Status: Experimental](https://img.shields.io/badge/Status-WIP-red?style=flat-square)
This repository is maintained by Wyatt Studio but work is in progress.
This repository is maintained by Wyatt Studio but work is in progress.
## Simple work flow diagramm
To sum up, here a simple work flow diagramm.
![Dev Wokflow](doc/workflow.svg)
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
escapedPath="$(echo `pwd` | sed 's/\//\\\//g')"
if grep flutter pubspec.yaml > /dev/null; then
if [ -d "coverage" ]; then
# combine line coverage info from package tests to a common file
if [ ! -d "$MELOS_ROOT_PATH/coverage" ]; then
mkdir "$MELOS_ROOT_PATH/coverage"
fi
sed "s/^SF:lib/SF:$escapedPath\/lib/g" coverage/lcov.info >> "$MELOS_ROOT_PATH/coverage/lcov.info"
rm -rf "coverage"
fi
fi
+15
View File
@@ -0,0 +1,15 @@
@startuml Simple Developpment Workflow
start
:Create an issue;
:Create branch related to the issue;
repeat :Commit related to the issue;
repeat while (feature is done)
:Update coverage;
:Close issue via last commit;
:Rebase from `master`;
:Create pull request;
:Merge branches;
:Update version;
:Publish package;
stop
@enduml
+25
View File
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 7.5 KiB

+1
View File
@@ -0,0 +1 @@
{"bricks":{"wyatt_clean_code":{"git":{"url":"ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-bricks.git","path":"bricks/wyatt_clean_code","ref":"033baa65408ec6b68e6a2ef43e64c24708ef16a1"}},"wyatt_feature_brick":{"git":{"url":"ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-bricks.git","path":"bricks/wyatt_feature_brick","ref":"033baa65408ec6b68e6a2ef43e64c24708ef16a1"}},"wyatt_package":{"git":{"url":"ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-bricks.git","path":"bricks/wyatt_package","ref":"033baa65408ec6b68e6a2ef43e64c24708ef16a1"}}}}
+13
View File
@@ -0,0 +1,13 @@
bricks:
wyatt_clean_code:
git:
url: ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-bricks.git
path: bricks/wyatt_clean_code
wyatt_feature_brick:
git:
url: ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-bricks.git
path: bricks/wyatt_feature_brick
wyatt_package:
git:
url: ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-bricks.git
path: bricks/wyatt_package
+14
View File
@@ -36,6 +36,20 @@ scripts:
clean:deep:
run: git clean -x -d -f -q
description: Clean things very deeply with `git clean`.
test:selective_unit_test:
run: melos exec --dir-exists="test" -- flutter test --no-pub --coverage
description: Run Flutter tests for a specific package in this project.
select-package:
flutter: true
test:
run: melos run test:selective_unit_test --no-select
description: Run all Flutter tests in this project.
gen-coverage: melos exec -- sh "\$MELOS_ROOT_PATH/combine_coverage.sh" && genhtml coverage/lcov.info -o coverage/html
gen-class-models: melos exec --scope="*wyatt_*" -- dart pub global run dcdg -o models/class-models.puml
# Additional cleanup lifecycle script, executed when `melos clean` is run.
postclean: >
+13
View File
@@ -1,3 +1,16 @@
## 0.1.0
> Note: This release has breaking changes.
- **REFACTOR**: update naming methodes (close #47).
- **REFACTOR**: update example. (close #38).
- **FIX**: fix execute method on error handler. (#38).
- **FEAT**: update usecase en add & sepcific case. (#38).
- **FEAT**: add obsevers for alternative usecase scenarions (#38).
- **DOCS**: generate class model. (#38).
- **DOCS**: update Readme. (#38).
- **BREAKING** **CHORE**: update exports. (#38).
## 0.0.2
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
+63 -14
View File
@@ -7,7 +7,7 @@
* the Free Software Foundation, either version 3 of the License, or
* any later version.
* This program is distributed in the hope that it will be useful,
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
@@ -31,10 +31,10 @@ The Wyatt Architecture for Flutter.
## Features
* Usecase
* Repository
* DataSource
* Entity
- Usecase
- Repository
- DataSource
- Entity
## Usage
@@ -73,19 +73,20 @@ abstract class PhotoRepository extends BaseRepository {
}
```
> Here the repository is just a proxy of the data sources with result type (to have beautiful error handling).
> Here the repository is just a proxy of the data sources with result type (to have beautiful error handling).
And finaly create your different usecases by using `UseCase<Parameters, ReturnType>` :
And finaly create your different usecases :
Several use cases are supported :
- Classic usecase :
```dart
class RetrieveAllPhoto extends UseCase<QueryParameters, List<Photo>> {
final PhotoRepository _photoRepository;
RetrieveAllPhotos(this._photoRepository);
class Test extends AsyncUseCase<QueryParameters, List<Photo>>> {
@override
FutureResult<List<Photo>> call(QueryParameters params) {
final photos = _photoRepository.getAllPhotos(
FuturOrResult<List<Photo>>> call(QueryParameters? params) {
final photos = _photoRepository.getAllPhotos(
start: params.start,
limit: params.limit,
);
@@ -94,6 +95,54 @@ class RetrieveAllPhoto extends UseCase<QueryParameters, List<Photo>> {
}
```
You can add alternatve scenarios and check pre/post conditions using our extensions :
```dart
class SearchPhotos extends AsyncUseCase<QueryParameters, List<Photo>>> {
@override
FutureOrResult<List<Photo>>> call(QueryParameters? params) {
final photos = _photoRepository.getAllPhotos(
start: params.start,
limit: params.limit,
);
return photos;
}
@override
FutureOr<void> onStart(QueryParameters? params) {
if(params.start == null || params.limit == null){
throw ClientException('Préconndition non valides');
}
}
}
```
You can implement error scenarios overriding `onError`, or check postconditions by overriding `onComplete` .
- Stream usecase :
```dart
class SearchPhotos extends StreamUseCase<QueryParameters, List<Photo>>> {
@override
FutureOrResult<Stream<List<Photo>>>> call(QueryParameters? params) {
final photos = _photoRepository.getAllPhotos(
start: params.start,
limit: params.limit,
);
return photos;
}
}
```
On this case, observers allow you to add alternative scénarios when data changed, overriding `onData` or `onDone`.
Please note that to use handlers, call `call` method and not `execute`.
> In fact, here we need a new parameter object, so let's create it:
```dart
@@ -171,4 +220,4 @@ class PhotoRepositoryImpl extends PhotoRepository {
}
```
That's all.
That's all.
@@ -35,46 +35,47 @@ class PhotoRepositoryImpl extends PhotoRepository {
);
@override
FutureResult<void> addPhotoToFavorites(Photo photo) => Result.tryCatchAsync(
FutureOrResult<void> addPhotoToFavorites(Photo photo) => Result.tryCatchAsync(
() => _favoriteLocalDataSource.addPhotoToFavorites(photo),
(error) => ClientException('Cannot add photo to favorites.'),
);
@override
FutureResult<bool> checkIfPhotoIsInFavorites(int id) => Result.tryCatchAsync(
FutureOrResult<bool> checkIfPhotoIsInFavorites(int id) =>
Result.tryCatchAsync(
() => _favoriteLocalDataSource.checkIfPhotoIsInFavorites(id),
(error) =>
ClientException('Cannot check if photo `$id` is in favorites.'),
);
@override
FutureResult<void> deletePhotoFromFavorites(int id) => Result.tryCatchAsync(
FutureOrResult<void> deletePhotoFromFavorites(int id) => Result.tryCatchAsync(
() => _favoriteLocalDataSource.deletePhotoFromFavorites(id),
(error) => ClientException('Cannot delete photo `$id` from favorites.'),
);
@override
FutureResult<Album> getAlbum(int id) => Result.tryCatchAsync(
FutureOrResult<Album> getAlbum(int id) => Result.tryCatchAsync(
() => _albumRemoteDataSource.getAlbum(id),
(error) => ServerException('Cannot retrieve album $id.'),
);
@override
FutureResult<List<Album>> getAllAlbums({int? start, int? limit}) =>
FutureOrResult<List<Album>> getAllAlbums({int? start, int? limit}) =>
Result.tryCatchAsync(
() => _albumRemoteDataSource.getAllAlbums(start: start, limit: limit),
(error) => ServerException('Cannot retrieve all albums.'),
);
@override
FutureResult<List<Photo>> getAllPhotos({int? start, int? limit}) async =>
FutureOrResult<List<Photo>> getAllPhotos({int? start, int? limit}) async =>
Result.tryCatchAsync(
() => _photoRemoteDataSource.getAllPhotos(start: start, limit: limit),
(error) => ServerException('Cannot retrieve all photos.'),
);
@override
FutureResult<List<Photo>> getAllPhotosFromFavorites() async {
FutureOrResult<List<Photo>> getAllPhotosFromFavorites() async {
try {
final response = <Photo>[];
final favorites =
@@ -95,13 +96,13 @@ class PhotoRepositoryImpl extends PhotoRepository {
}
@override
FutureResult<Photo> getPhoto(int id) => Result.tryCatchAsync(
FutureOrResult<Photo> getPhoto(int id) => Result.tryCatchAsync(
() => _photoRemoteDataSource.getPhoto(id),
(error) => ServerException('Cannot retrieve photo $id.'),
);
@override
FutureResult<List<Photo>> getPhotosFromAlbum(
FutureOrResult<List<Photo>> getPhotosFromAlbum(
int albumId, {
int? start,
int? limit,
@@ -19,17 +19,17 @@ import 'package:architecture_example/domain/entities/photo.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
abstract class PhotoRepository extends BaseRepository {
FutureResult<Album> getAlbum(int id);
FutureResult<List<Album>> getAllAlbums({int? start, int? limit});
FutureResult<Photo> getPhoto(int id);
FutureResult<List<Photo>> getAllPhotos({int? start, int? limit});
FutureResult<List<Photo>> getPhotosFromAlbum(
FutureOrResult<Album> getAlbum(int id);
FutureOrResult<List<Album>> getAllAlbums({int? start, int? limit});
FutureOrResult<Photo> getPhoto(int id);
FutureOrResult<List<Photo>> getAllPhotos({int? start, int? limit});
FutureOrResult<List<Photo>> getPhotosFromAlbum(
int albumId, {
int? start,
int? limit,
});
FutureResult<void> addPhotoToFavorites(Photo photo);
FutureResult<void> deletePhotoFromFavorites(int id);
FutureResult<List<Photo>> getAllPhotosFromFavorites();
FutureResult<bool> checkIfPhotoIsInFavorites(int id);
FutureOrResult<void> addPhotoToFavorites(Photo photo);
FutureOrResult<void> deletePhotoFromFavorites(int id);
FutureOrResult<List<Photo>> getAllPhotosFromFavorites();
FutureOrResult<bool> checkIfPhotoIsInFavorites(int id);
}
@@ -1,31 +1,40 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:architecture_example/domain/entities/photo.dart';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class AddPhotoToFavorites extends UseCase<Photo, List<Photo>> {
class AddPhotoToFavorites extends AsyncUseCase<Photo, List<Photo>> {
final PhotoRepository _photoRepository;
AddPhotoToFavorites(this._photoRepository);
@override
FutureResult<List<Photo>> call(Photo params) async {
await _photoRepository.addPhotoToFavorites(params);
FutureOrResult<List<Photo>> execute(Photo? params) async {
await _photoRepository.addPhotoToFavorites(params!);
return _photoRepository.getAllPhotosFromFavorites();
}
@override
FutureOr<void> onStart(Photo? params) {
if (params == null) {
throw ClientException('Photo cannot be null');
}
}
}
@@ -14,15 +14,24 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class CheckIfPhotoIsInFavorites extends UseCase<int, bool> {
class CheckIfPhotoIsInFavorites extends AsyncUseCase<int, bool> {
final PhotoRepository _photoRepository;
CheckIfPhotoIsInFavorites(this._photoRepository);
@override
FutureResult<bool> call(int params) async =>
_photoRepository.checkIfPhotoIsInFavorites(params);
FutureOrResult<bool> execute(int? params) async =>
_photoRepository.checkIfPhotoIsInFavorites(params!);
@override
FutureOr<void> onStart(int? params) {
if (params == null) {
throw ClientException('id cannot be null');
}
}
}
@@ -1,16 +1,16 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
@@ -18,13 +18,13 @@ import 'package:architecture_example/domain/entities/photo.dart';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class DisplayFavorites extends UseCase<void, List<Photo>> {
class DisplayFavorites extends AsyncUseCase<NoParam, List<Photo>> {
final PhotoRepository _photoRepository;
DisplayFavorites(this._photoRepository);
@override
FutureResult<List<Photo>> call(void params) {
FutureOrResult<List<Photo>> execute(void params) {
final photos = _photoRepository.getAllPhotosFromFavorites();
return photos;
}
@@ -14,18 +14,27 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:architecture_example/domain/entities/photo.dart';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class DisplayPhoto extends UseCase<int, Photo> {
class DisplayPhoto extends AsyncUseCase<int, Photo> {
final PhotoRepository _photoRepository;
DisplayPhoto(this._photoRepository);
@override
FutureResult<Photo> call(int params) {
final photo = _photoRepository.getPhoto(params);
FutureOrResult<Photo> execute(int? params) {
final photo = _photoRepository.getPhoto(params!);
return photo;
}
@override
FutureOr<void> onStart(int? params) {
if (params == null) {
throw ClientException('id cannot be null');
}
}
}
@@ -14,24 +14,33 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:architecture_example/domain/entities/photo.dart';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:architecture_example/domain/usecases/photos/params/query_parameters.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class OpenAlbum extends UseCase<QueryParameters, List<Photo>> {
class OpenAlbum extends AsyncUseCase<QueryParameters, List<Photo>> {
final PhotoRepository _photoRepository;
OpenAlbum(this._photoRepository);
@override
FutureResult<List<Photo>> call(QueryParameters params) {
FutureOrResult<List<Photo>> execute(QueryParameters? params) {
final photos = _photoRepository.getPhotosFromAlbum(
params.albumId,
params!.albumId,
start: params.start,
limit: params.limit,
);
return photos;
}
@override
FutureOr<void> onStart(QueryParameters? params) {
if (params == null) {
throw ClientException('params cannot be null');
}
}
}
@@ -14,18 +14,27 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:architecture_example/domain/entities/photo.dart';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class RemovePhotoFromFavorites extends UseCase<int, List<Photo>> {
class RemovePhotoFromFavorites extends AsyncUseCase<int, List<Photo>> {
final PhotoRepository _photoRepository;
RemovePhotoFromFavorites(this._photoRepository);
@override
FutureResult<List<Photo>> call(int params) async {
await _photoRepository.deletePhotoFromFavorites(params);
FutureOrResult<List<Photo>> execute(int? params) async {
await _photoRepository.deletePhotoFromFavorites(params!);
return _photoRepository.getAllPhotosFromFavorites();
}
@override
FutureOr<void> onStart(int? params) {
if (params == null) {
throw ClientException('id cannot be null');
}
}
}
@@ -14,22 +14,31 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:architecture_example/domain/entities/album.dart';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:architecture_example/domain/usecases/photos/params/query_parameters.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class RetrieveAllAlbums extends UseCase<QueryParameters, List<Album>> {
class RetrieveAllAlbums extends AsyncUseCase<QueryParameters, List<Album>> {
final PhotoRepository _photoRepository;
RetrieveAllAlbums(this._photoRepository);
@override
FutureResult<List<Album>> call(QueryParameters params) {
FutureOrResult<List<Album>> execute(QueryParameters? params) {
final albums = _photoRepository.getAllAlbums(
start: params.start,
start: params!.start,
limit: params.limit,
);
return albums;
}
@override
FutureOr<void> onStart(QueryParameters? params) {
if (params == null) {
throw ClientException('params cannot be null');
}
}
}
@@ -0,0 +1,44 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:wyatt_architecture/wyatt_architecture.dart';
/// Usecase observers
mixin Observer<Parameters, ReturnType> {
/// Called before usecase is runned.
/// Usefull to check the preconditions
FutureOr<void> onStart(Parameters? params) {}
/// Called when error occures during main scenario
/// Usefull to run alternative scenario
FutureOr<void> onError(AppException? error) {}
}
/// Specific observer for classic usecase
mixin AsyncObserver<ReturnType> {
FutureOr<void> onComplete(ReturnType? data) {}
}
/// Specific observer for stream case usecase
mixin StreamObserver<ReturnType> {
/// Replaces the data event handler of this subscription.
void onDone() {}
/// Replaces the done event handler of this subscription.
void onData(ReturnType? data) {}
}
@@ -1,27 +1,80 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:wyatt_architecture/src/core/exceptions/exceptions.dart';
import 'package:wyatt_architecture/src/domain/usecases/observers.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';
typedef FutureResult<T> = Future<Result<T, AppException>>;
typedef FutureOrResult<T> = FutureOr<Result<T, AppException>>;
typedef StreamResult<T> = Stream<Result<T, AppException>>;
typedef Res<T> = Result<T, AppException>;
// ignore: one_member_abstracts
abstract class UseCase<Parameters, ReturnType> {
FutureResult<ReturnType> call(Parameters params);
/// Abstract class of a use case
abstract class BaseUseCase<Parameters, ReturnType> {
/// Run use case scenarios
ReturnType call(Parameters parameters);
/// Private function to implement main scenario
/// of your usecase.
ReturnType execute(Parameters params);
}
/// Abstract class of a use case that deals specifically
/// with the response and its state.
abstract class UseCase<Parameters, ReturnType>
extends BaseUseCase<Parameters?, FutureOrResult<ReturnType>>
with Observer<Parameters, ReturnType> {
FutureOr<void> _onSuccess(ReturnType data);
/// Supports the result of the main scenario and integrates
/// some alternative scenarios if necessary.
@override
FutureOrResult<ReturnType> call(Parameters? parameters) async {
try {
await onStart(parameters);
final response = await execute(parameters);
if (response.isErr) {
await onError(response.err);
} else if (response.isOk && response.ok != null) {
await _onSuccess(response.ok as ReturnType);
}
return response;
} catch (e) {
return Err(ClientException(e.toString()));
}
}
}
/// Abtstract classic usecase.
abstract class AsyncUseCase<Parameters, ReturnType>
extends UseCase<Parameters?, ReturnType> with AsyncObserver<ReturnType> {
@override
FutureOr<void> _onSuccess(ReturnType data) => onComplete(data);
}
/// Abstract specific usecase bases on streams
abstract class StreamUseCase<Parameters, ReturnType>
extends UseCase<Parameters?, Stream<ReturnType>>
with StreamObserver<ReturnType> {
@override
FutureOr<void> _onSuccess(Stream<ReturnType> data) {
data.listen(
onData,
onDone: onDone,
);
}
}
@@ -15,4 +15,5 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
export 'no_param.dart';
export 'observers.dart';
export 'usecase.dart';
Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

@@ -0,0 +1,86 @@
@startuml
set namespaceSeparator ::
abstract class "wyatt_architecture::src::core::exceptions::exceptions.dart::AppException" {
+String? message
+String toString()
}
"dart::core::Exception" <|-- "wyatt_architecture::src::core::exceptions::exceptions.dart::AppException"
class "wyatt_architecture::src::core::exceptions::exceptions.dart::ClientException" {
}
"wyatt_architecture::src::core::exceptions::exceptions.dart::AppException" <|-- "wyatt_architecture::src::core::exceptions::exceptions.dart::ClientException"
class "wyatt_architecture::src::core::exceptions::exceptions.dart::ServerException" {
}
"wyatt_architecture::src::core::exceptions::exceptions.dart::AppException" <|-- "wyatt_architecture::src::core::exceptions::exceptions.dart::ServerException"
abstract class "wyatt_architecture::src::domain::repositories::base_repository.dart::BaseRepository" {
}
abstract class "wyatt_architecture::src::domain::data_sources::local::base_local_data_source.dart::BaseLocalDataSource" {
}
"wyatt_architecture::src::domain::data_sources::base_data_source.dart::BaseDataSource" <|-- "wyatt_architecture::src::domain::data_sources::local::base_local_data_source.dart::BaseLocalDataSource"
abstract class "wyatt_architecture::src::domain::data_sources::base_data_source.dart::BaseDataSource" {
}
abstract class "wyatt_architecture::src::domain::data_sources::remote::base_remote_data_source.dart::BaseRemoteDataSource" {
}
"wyatt_architecture::src::domain::data_sources::base_data_source.dart::BaseDataSource" <|-- "wyatt_architecture::src::domain::data_sources::remote::base_remote_data_source.dart::BaseRemoteDataSource"
class "wyatt_architecture::src::domain::usecases::no_param.dart::NoParam" {
}
"wyatt_architecture::src::domain::entities::entity.dart::Entity" <|-- "wyatt_architecture::src::domain::usecases::no_param.dart::NoParam"
abstract class "wyatt_architecture::src::domain::usecases::observers.dart::Observer" {
+FutureOr<void> onStart()
+FutureOr<void> onError()
}
abstract class "wyatt_architecture::src::domain::usecases::observers.dart::AsyncObserver" {
+FutureOr<void> onComplete()
}
abstract class "wyatt_architecture::src::domain::usecases::observers.dart::StreamObserver" {
+void onDone()
+void onData()
}
abstract class "wyatt_architecture::src::domain::usecases::usecase.dart::BaseUseCase" {
+ReturnType execute()
+ReturnType call()
}
abstract class "wyatt_architecture::src::domain::usecases::usecase.dart::UseCase" {
-FutureOr<void> _onSuccess()
+FutureOr<Result<ReturnType, AppException>> execute()
}
"wyatt_architecture::src::domain::usecases::usecase.dart::BaseUseCase" <|-- "wyatt_architecture::src::domain::usecases::usecase.dart::UseCase"
"wyatt_architecture::src::domain::usecases::observers.dart::Observer" <|-- "wyatt_architecture::src::domain::usecases::usecase.dart::UseCase"
abstract class "wyatt_architecture::src::domain::usecases::usecase.dart::AsyncUseCase" {
-FutureOr<void> _onSuccess()
}
"wyatt_architecture::src::domain::usecases::usecase.dart::UseCase" <|-- "wyatt_architecture::src::domain::usecases::usecase.dart::AsyncUseCase"
"wyatt_architecture::src::domain::usecases::observers.dart::AsyncObserver" <|-- "wyatt_architecture::src::domain::usecases::usecase.dart::AsyncUseCase"
abstract class "wyatt_architecture::src::domain::usecases::usecase.dart::StreamUseCase" {
-FutureOr<void> _onSuccess()
}
"wyatt_architecture::src::domain::usecases::usecase.dart::UseCase" <|-- "wyatt_architecture::src::domain::usecases::usecase.dart::StreamUseCase"
"wyatt_architecture::src::domain::usecases::observers.dart::StreamObserver" <|-- "wyatt_architecture::src::domain::usecases::usecase.dart::StreamUseCase"
abstract class "wyatt_architecture::src::domain::entities::entity.dart::Entity" {
}
@enduml
+1 -1
View File
@@ -1,7 +1,7 @@
name: wyatt_architecture
description: A new Wyatt package
repository: https://git.wyatt-studio.fr/Wyatt-FOSS/wyatt-packages/src/branch/master/packages/wyatt_architecture
version: 0.0.2
version: 0.1.0
publish_to: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub
@@ -1,3 +1,7 @@
## 0.4.0+2
- Update a dependency to the latest release.
## 0.4.0+1
- **FIX**: add sort of mutex on onAuthChanges callback trigger.
@@ -0,0 +1,30 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
class CustomPassword extends RegexValidator<ValidationStandardError> {
const CustomPassword.pure([super.value]) : super.pure();
const CustomPassword.dirty([super.value]) : super.dirty();
@override
ValidationStandardError get onEmpty => ValidationStandardError.empty;
@override
ValidationStandardError get onError => ValidationStandardError.invalid;
@override
RegExp get regex => RegExp(r'^(?=.*[A-Za-z\w\s])(?=.*\d).{6,}$');
}
@@ -3,7 +3,7 @@
// -----
// File: app.dart
// Created Date: 19/08/2022 12:05:38
// Last Modified: Thu Nov 10 2022
// Last Modified: Sat Dec 03 2022
// -----
// Copyright (c) 2022
@@ -13,6 +13,7 @@ import 'dart:math';
import 'package:example_router/core/constants/form_field.dart';
import 'package:example_router/core/dependency_injection/get_it.dart';
import 'package:example_router/core/routes/router.dart';
import 'package:example_router/core/utils/custom_password.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
@@ -21,7 +22,8 @@ import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
FutureResult<int?> onSignUpSuccess(
FutureOrResult<int?> onSignUpSuccess(
AuthenticationRepository<int> repo,
Account? account,
WyattForm form,
) async {
@@ -34,9 +36,15 @@ FutureResult<int?> onSignUpSuccess(
return const Ok<int, AppException>(id);
}
FutureResult<int?> onAccountChanges(Account? account) async {
FutureOrResult<int?> onAccountChanges(
AuthenticationRepository<int> repo,
Account? account,
) async {
final id = Random().nextInt(1000);
debugPrint('onAccountChanges: $account, generatedId: $id');
final token =
await repo.getIdentityToken().fold((value) => value, (error) => 'null');
debugPrint('onAccountChanges: $account, token: $token, generatedId: $id');
return Ok<int, AppException>(id);
}
@@ -47,6 +55,7 @@ class App extends StatelessWidget {
authenticationRemoteDataSource: getIt<AuthenticationRemoteDataSource>(),
onSignUpSuccess: onSignUpSuccess,
onAuthChange: onAccountChanges,
customPasswordValidator: const CustomPassword.pure(),
extraSignUpInputs: [
FormInput(
AppFormField.confirmedPassword,
@@ -3,10 +3,11 @@
// -----
// File: sign_in_form.dart
// Created Date: 19/08/2022 15:24:37
// Last Modified: Wed Nov 16 2022
// Last Modified: Sat Dec 03 2022
// -----
// Copyright (c) 2022
import 'package:example_router/core/utils/custom_password.dart';
import 'package:flutter/material.dart';
import 'package:wyatt_authentication_bloc/wyatt_authentication_bloc.dart';
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
@@ -38,7 +39,8 @@ class _PasswordInput extends StatelessWidget {
field: AuthFormField.password,
builder: ((context, cubit, state, field, input) {
return TextField(
onChanged: (pwd) => cubit.passwordChanged(pwd),
onChanged: (pwd) => cubit
.passwordCustomChanged<CustomPassword>(CustomPassword.dirty(pwd)),
obscureText: true,
decoration: InputDecoration(
labelText: 'Password',
@@ -59,7 +61,9 @@ class _SignInButton extends StatelessWidget {
return status.isSubmissionInProgress
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: status.isValidated ? () => cubit.signInWithEmailAndPassword() : null,
onPressed: status.isValidated
? () => cubit.signInWithEmailAndPassword()
: null,
child: const Text('Sign in with credentials'),
);
}),
@@ -3,11 +3,12 @@
// -----
// File: sign_up_form.dart
// Created Date: 19/08/2022 14:41:08
// Last Modified: Wed Nov 16 2022
// Last Modified: Sat Dec 03 2022
// -----
// Copyright (c) 2022
import 'package:example_router/core/constants/form_field.dart';
import 'package:example_router/core/utils/custom_password.dart';
import 'package:flutter/material.dart' hide FormField;
import 'package:wyatt_authentication_bloc/wyatt_authentication_bloc.dart';
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
@@ -40,7 +41,8 @@ class _PasswordInput extends StatelessWidget {
builder: ((context, cubit, state, field, input) {
return TextField(
onChanged: (pwd) {
cubit.passwordChanged(pwd);
cubit.passwordCustomChanged<CustomPassword>(
CustomPassword.dirty(pwd));
cubit.dataChanged(
AppFormField.confirmedPassword,
ConfirmedPassword.dirty(
@@ -40,11 +40,11 @@ dependencies:
wyatt_form_bloc:
hosted: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub/
version: 0.2.0
version: 0.2.0+1
wyatt_architecture:
hosted: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub/
version: 0.0.2
version: 0.1.0
wyatt_type_utils:
hosted: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub/
@@ -114,6 +114,7 @@ class AuthenticationMockDataSourceImpl extends AuthenticationRemoteDataSource {
providerId: 'wyatt',
creationTime: creation,
lastSignInTime: creation,
isNewUser: creation == creation,
);
_streamAccount.add(mock);
_connectedMock = _connectedMock?.copyWith(left: mock);
@@ -188,6 +189,7 @@ class AuthenticationMockDataSourceImpl extends AuthenticationRemoteDataSource {
email: email,
creationTime: creation,
lastSignInTime: creation,
isNewUser: creation == creation,
);
_streamAccount.add(mock);
_registeredMock = Pair(mock, password);
@@ -14,6 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:rxdart/rxdart.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
import 'package:wyatt_authentication_bloc/src/core/constants/form_field.dart';
import 'package:wyatt_authentication_bloc/src/core/constants/form_name.dart';
@@ -26,12 +29,16 @@ import 'package:wyatt_authentication_bloc/src/domain/repositories/authentication
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';
typedef OnSignUpSuccess<T> = FutureResult<T?> Function(
typedef OnSignUpSuccess<T> = FutureOrResult<T?> Function(
AuthenticationRepository<T> repo,
Account? account,
WyattForm form,
);
typedef OnAuthChange<T> = FutureResult<T?> Function(Account? account);
typedef OnAuthChange<T> = FutureOrResult<T?> Function(
AuthenticationRepository<T> repo,
Account? account,
);
class AuthenticationRepositoryImpl<T extends Object>
extends AuthenticationRepository<T> {
@@ -43,6 +50,8 @@ class AuthenticationRepositoryImpl<T extends Object>
final OnSignUpSuccess<T>? _onSignUpSuccess;
final OnAuthChange<T>? _onAccountChanges;
final StreamController<FutureOrResult<AccountWrapper<T>>> _signUpStream =
StreamController();
bool _pause = false; // Semaphore
@@ -52,6 +61,8 @@ class AuthenticationRepositoryImpl<T extends Object>
FormRepository? formRepository,
// ignore: strict_raw_type
List<FormInput>? extraSignUpInputs,
FormInputValidator<String?, ValidationError>? customEmailValidator,
FormInputValidator<String?, ValidationError>? customPasswordValidator,
OnSignUpSuccess<T>? onSignUpSuccess,
OnAuthChange<T>? onAuthChange,
}) : _authenticationLocalDataSource = authenticationCacheDataSource,
@@ -66,8 +77,14 @@ class AuthenticationRepositoryImpl<T extends Object>
..registerForm(
WyattFormImpl(
[
FormInput(AuthFormField.email, const Email.pure()),
FormInput(AuthFormField.password, const Password.pure())
FormInput(
AuthFormField.email,
customEmailValidator ?? const Email.pure(),
),
FormInput(
AuthFormField.password,
customPasswordValidator ?? const Password.pure(),
)
],
name: AuthFormName.signInForm,
),
@@ -75,8 +92,14 @@ class AuthenticationRepositoryImpl<T extends Object>
..registerForm(
WyattFormImpl(
[
FormInput(AuthFormField.email, const Email.pure()),
FormInput(AuthFormField.password, const Password.pure()),
FormInput(
AuthFormField.email,
customEmailValidator ?? const Email.pure(),
),
FormInput(
AuthFormField.password,
customPasswordValidator ?? const Password.pure(),
),
...extraSignUpInputs ?? []
],
name: AuthFormName.signUpForm,
@@ -88,7 +111,7 @@ class AuthenticationRepositoryImpl<T extends Object>
FormRepository get formRepository => _formRepository;
@override
FutureResult<Account> signInWithEmailAndPassword({
FutureOrResult<Account> signInWithEmailAndPassword({
required String email,
required String password,
}) =>
@@ -106,7 +129,7 @@ class AuthenticationRepositoryImpl<T extends Object>
);
@override
FutureResult<void> signOut() =>
FutureOrResult<void> signOut() =>
Result.tryCatchAsync<void, AppException, AppException>(
() async {
await _authenticationRemoteDataSource.signOut();
@@ -116,7 +139,7 @@ class AuthenticationRepositoryImpl<T extends Object>
);
@override
FutureResult<Account> signUp({
FutureOrResult<Account> signUp({
required String email,
required String password,
}) =>
@@ -130,11 +153,16 @@ class AuthenticationRepositoryImpl<T extends Object>
await _authenticationLocalDataSource.storeAccount(account);
if (_onSignUpSuccess.isNotNull) {
final dataResult = await _onSignUpSuccess!.call(
this,
account,
_formRepository.accessForm(AuthFormName.signUpForm).clone(),
);
await dataResult.foldAsync(
_authenticationLocalDataSource.storeData,
(data) async {
await _authenticationLocalDataSource.storeData(data);
_signUpStream
.add(Future.value(Ok(AccountWrapperModel(account, data))));
},
(error) async => error,
);
}
@@ -148,28 +176,28 @@ class AuthenticationRepositoryImpl<T extends Object>
);
@override
FutureResult<void> destroyCache() =>
FutureOrResult<void> destroyCache() =>
Result.tryCatchAsync<void, AppException, AppException>(
_authenticationLocalDataSource.destroy,
(error) => error,
);
@override
FutureResult<AccountWrapper<T>> getCache() =>
FutureOrResult<AccountWrapper<T>> getCache() =>
Result.tryCatchAsync<AccountWrapper<T>, AppException, AppException>(
_authenticationLocalDataSource.load,
(error) => error,
);
@override
FutureResult<Account> getAccount() =>
FutureOrResult<Account> getAccount() =>
Result.tryCatchAsync<Account, AppException, AppException>(
_authenticationLocalDataSource.loadAccount,
(error) => error,
);
@override
FutureResult<void> setAccount(
FutureOrResult<void> setAccount(
Account account,
) =>
Result.tryCatchAsync<void, AppException, AppException>(
@@ -180,14 +208,14 @@ class AuthenticationRepositoryImpl<T extends Object>
);
@override
FutureResult<T> getData() =>
FutureOrResult<T> getData() =>
Result.tryCatchAsync<T, AppException, AppException>(
_authenticationLocalDataSource.loadData,
(error) => error,
);
@override
FutureResult<void> setData(
FutureOrResult<void> setData(
T? data,
) =>
Result.tryCatchAsync<void, AppException, AppException>(
@@ -198,26 +226,31 @@ class AuthenticationRepositoryImpl<T extends Object>
);
@override
FutureResult<String> getIdentityToken() =>
FutureOrResult<String> getIdentityToken() =>
Result.tryCatchAsync<String, AppException, AppException>(
_authenticationRemoteDataSource.getIdentityToken,
(error) => error,
);
@override
Stream<FutureResult<AccountWrapper<T>>> streamAccount() =>
_authenticationRemoteDataSource.streamAccount().map((account) async {
if (_onAccountChanges.isNotNull && !_pause) {
final dataResult = await _onAccountChanges!.call(account);
return dataResult.map((data) => AccountWrapperModel(account, data));
}
return Ok<AccountWrapperModel<T>, AppException>(
AccountWrapperModel<T>(account, null),
);
});
Stream<FutureOrResult<AccountWrapper<T>>> streamAccount() => MergeStream([
_signUpStream.stream.asBroadcastStream(),
_authenticationRemoteDataSource.streamAccount().map((account) async {
if (_onAccountChanges.isNotNull && !_pause) {
final dataResult = await _onAccountChanges!.call(this, account);
return dataResult.map((data) {
_authenticationLocalDataSource.storeData(data);
return AccountWrapperModel(account, data);
});
}
return Ok<AccountWrapperModel<T>, AppException>(
AccountWrapperModel<T>(account, null),
);
})
]);
@override
FutureResult<void> confirmPasswordReset({
FutureOrResult<void> confirmPasswordReset({
required String code,
required String newPassword,
}) =>
@@ -232,7 +265,7 @@ class AuthenticationRepositoryImpl<T extends Object>
);
@override
FutureResult<void> sendEmailVerification() =>
FutureOrResult<void> sendEmailVerification() =>
Result.tryCatchAsync<void, AppException, AppException>(
() async {
await _authenticationRemoteDataSource.sendEmailVerification();
@@ -241,7 +274,7 @@ class AuthenticationRepositoryImpl<T extends Object>
);
@override
FutureResult<void> sendPasswordResetEmail({required String email}) =>
FutureOrResult<void> sendPasswordResetEmail({required String email}) =>
Result.tryCatchAsync<void, AppException, AppException>(
() async {
await _authenticationRemoteDataSource.sendPasswordResetEmail(
@@ -252,7 +285,7 @@ class AuthenticationRepositoryImpl<T extends Object>
);
@override
FutureResult<Account> signInAnonymously() =>
FutureOrResult<Account> signInAnonymously() =>
Result.tryCatchAsync<Account, AppException, AppException>(
() async {
final account =
@@ -263,7 +296,7 @@ class AuthenticationRepositoryImpl<T extends Object>
);
@override
FutureResult<bool> verifyPasswordResetCode({required String code}) =>
FutureOrResult<bool> verifyPasswordResetCode({required String code}) =>
Result.tryCatchAsync<bool, AppException, AppException>(
() async {
final response = await _authenticationRemoteDataSource
@@ -274,7 +307,7 @@ class AuthenticationRepositoryImpl<T extends Object>
);
@override
FutureResult<void> refresh() =>
FutureOrResult<void> refresh() =>
Result.tryCatchAsync<void, AppException, AppException>(
() async {
await _authenticationRemoteDataSource.refresh();
@@ -30,7 +30,7 @@ abstract class AuthenticationRepository<T> extends BaseRepository {
/// Throws a SignUpWithEmailAndPasswordFailureInterface if
/// an exception occurs.
/// {@endtemplate}
FutureResult<Account> signUp({
FutureOrResult<Account> signUp({
required String email,
required String password,
});
@@ -40,21 +40,21 @@ abstract class AuthenticationRepository<T> extends BaseRepository {
///
/// Throws a SendEmailVerificationFailureInterface if an exception occurs.
/// {@endtemplate}
FutureResult<void> sendEmailVerification();
FutureOrResult<void> sendEmailVerification();
/// {@template send_password_reset_email}
/// Sends a password reset email to the provided [email].
///
/// Throws a SendPasswordResetEmailFailureInterface if an exception occurs.
/// {@endtemplate}
FutureResult<void> sendPasswordResetEmail({required String email});
FutureOrResult<void> sendPasswordResetEmail({required String email});
/// {@template confirm_password_reset}
/// Confirms the password reset with the provided [newPassword] and [code].
///
/// Throws a ConfirmPasswordResetFailureInterface if an exception occurs.
/// {@endtemplate}
FutureResult<void> confirmPasswordReset({
FutureOrResult<void> confirmPasswordReset({
required String code,
required String newPassword,
});
@@ -64,14 +64,14 @@ abstract class AuthenticationRepository<T> extends BaseRepository {
///
/// Throws a VerifyPasswordResetCodeFailureInterface if an exception occurs.
/// {@endtemplate}
FutureResult<bool> verifyPasswordResetCode({required String code});
FutureOrResult<bool> verifyPasswordResetCode({required String code});
/// {@template signin_anom}
/// Sign in anonymously.
///
/// Throws a SignInAnonymouslyFailureInterface if an exception occurs.
/// {@endtemplate}
FutureResult<Account> signInAnonymously();
FutureOrResult<Account> signInAnonymously();
/// {@template signin_pwd}
/// Signs in with the provided [email] and [password].
@@ -79,7 +79,7 @@ abstract class AuthenticationRepository<T> extends BaseRepository {
/// Throws a SignInWithEmailAndPasswordFailureInterface if
/// an exception occurs.
/// {@endtemplate}
FutureResult<Account> signInWithEmailAndPassword({
FutureOrResult<Account> signInWithEmailAndPassword({
required String email,
required String password,
});
@@ -88,9 +88,9 @@ abstract class AuthenticationRepository<T> extends BaseRepository {
/// Signs out the current user.
/// It also clears the cache and the associated data.
/// {@endtemplate}
FutureResult<void> signOut();
FutureOrResult<void> signOut();
FutureResult<void> refresh();
FutureOrResult<void> refresh();
/// {@template stream_account}
/// Stream of [AccountWrapper] which will emit the current account when
@@ -99,16 +99,16 @@ abstract class AuthenticationRepository<T> extends BaseRepository {
/// Emits [AccountWrapper] with null [Account] if the user is not
/// authenticated.
/// {@endtemplate}
Stream<FutureResult<AccountWrapper<T>>> streamAccount();
Stream<FutureOrResult<AccountWrapper<T>>> streamAccount();
FutureResult<String> getIdentityToken();
FutureOrResult<String> getIdentityToken();
FutureResult<Account> getAccount();
FutureResult<void> setAccount(Account account);
FutureOrResult<Account> getAccount();
FutureOrResult<void> setAccount(Account account);
FutureResult<T> getData();
FutureResult<void> setData(T? data);
FutureOrResult<T> getData();
FutureOrResult<void> setData(T? data);
FutureResult<AccountWrapper<T>> getCache();
FutureResult<void> destroyCache();
FutureOrResult<AccountWrapper<T>> getCache();
FutureOrResult<void> destroyCache();
}
@@ -56,6 +56,19 @@ class AuthenticationCubit<Extra> extends Cubit<AuthenticationState<Extra>> {
});
}
/// If authenticated, re-emits state with data freshly loaded from cache.
FutureOr<void> reloadCache() async {
if (state.status == AuthenticationStatus.authenticated) {
final data = await _authenticationRepository.getCache();
emit(
data.fold(
AuthenticationState<Extra>.authenticated,
(error) => state,
),
);
}
}
FutureOr<void> signOut() {
// TODO(hpcl): maybe force unauthenticated by emitting an event
_authenticationRepository.signOut();
@@ -41,15 +41,52 @@ class SignInCubit<Extra> extends FormDataCubit<SignInState> {
String get formName => AuthFormName.signInForm;
void emailChanged(String value) {
final emailValidatorType = _formRepository
.accessForm(formName)
.validatorOf(AuthFormField.email)
.runtimeType;
assert(
emailValidatorType == Email,
'Use emailCustomChanged(...) with validator $emailValidatorType',
);
final Email email = Email.dirty(value);
dataChanged(AuthFormField.email, email);
}
void passwordChanged(String value) {
final passwordValidatorType = _formRepository
.accessForm(formName)
.validatorOf(AuthFormField.password)
.runtimeType;
assert(
passwordValidatorType == Password,
'Use passwordCustomChanged(...) with validator $passwordValidatorType',
);
final Password password = Password.dirty(value);
dataChanged(AuthFormField.password, password);
}
/// Same as [emailChanged] but with a custom [Validator].
///
/// Sort of short hand for [dataChanged].
void emailCustomChanged<
Validator extends FormInputValidator<String?, ValidationError>>(
Validator validator,
) {
dataChanged(AuthFormField.email, validator);
}
/// Same as [passwordChanged] but with a custom [Validator].
///
/// Sort of short hand for [dataChanged].
void passwordCustomChanged<
Validator extends FormInputValidator<String?, ValidationError>>(
Validator validator,
) {
dataChanged(AuthFormField.password, validator);
}
@override
FutureOr<void> dataChanged<Value>(
String key,
@@ -114,7 +151,7 @@ class SignInCubit<Extra> extends FormDataCubit<SignInState> {
if (state.status.isSubmissionInProgress) {
return;
}
if (!state.status.isValidated) {
return;
}
@@ -17,8 +17,10 @@
part of 'sign_in_cubit.dart';
class SignInState extends FormDataState {
Email get email => form.validatorOf(AuthFormField.email);
Password get password => form.validatorOf(AuthFormField.password);
FormInputValidator<String?, ValidationError> get email =>
form.validatorOf(AuthFormField.email);
FormInputValidator<String?, ValidationError> get password =>
form.validatorOf(AuthFormField.password);
const SignInState({
required super.form,
@@ -43,15 +43,52 @@ class SignUpCubit<Extra> extends FormDataCubit<SignUpState> {
String get formName => AuthFormName.signUpForm;
void emailChanged(String value) {
final emailValidatorType = _formRepository
.accessForm(formName)
.validatorOf(AuthFormField.email)
.runtimeType;
assert(
emailValidatorType == Email,
'Use emailCustomChanged(...) with validator $emailValidatorType',
);
final Email email = Email.dirty(value);
dataChanged(AuthFormField.email, email);
}
void passwordChanged(String value) {
final passwordValidatorType = _formRepository
.accessForm(formName)
.validatorOf(AuthFormField.password)
.runtimeType;
assert(
passwordValidatorType == Password,
'Use passwordCustomChanged(...) with validator $passwordValidatorType',
);
final Password password = Password.dirty(value);
dataChanged(AuthFormField.password, password);
}
/// Same as [emailChanged] but with a custom [Validator].
///
/// Sort of short hand for [dataChanged].
void emailCustomChanged<
Validator extends FormInputValidator<String?, ValidationError>>(
Validator validator,
) {
dataChanged(AuthFormField.email, validator);
}
/// Same as [passwordChanged] but with a custom [Validator].
///
/// Sort of short hand for [dataChanged].
void passwordCustomChanged<
Validator extends FormInputValidator<String?, ValidationError>>(
Validator validator,
) {
dataChanged(AuthFormField.password, validator);
}
@override
FutureOr<void> dataChanged<Value>(
String key,
@@ -17,8 +17,10 @@
part of 'sign_up_cubit.dart';
class SignUpState extends FormDataState {
Email get email => form.validatorOf(AuthFormField.email);
Password get password => form.validatorOf(AuthFormField.password);
FormInputValidator<String?, ValidationError> get email =>
form.validatorOf(AuthFormField.email);
FormInputValidator<String?, ValidationError> get password =>
form.validatorOf(AuthFormField.password);
const SignUpState({
required super.form,
@@ -1,7 +1,7 @@
name: wyatt_authentication_bloc
description: Authentication BLoC for Flutter
repository: https://git.wyatt-studio.fr/Wyatt-FOSS/wyatt-packages/src/branch/master/packages/wyatt_authentication_bloc
version: 0.4.0+1
version: 0.4.0+2
publish_to: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub
@@ -21,14 +21,15 @@ dependencies:
flutter_facebook_auth: ^4.3.0
sign_in_with_apple: ^3.3.0
twitter_login: ^4.2.3
rxdart: ^0.27.7
wyatt_form_bloc:
hosted: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub/
version: ^0.2.0
version: ^0.2.0+1
wyatt_architecture:
hosted: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub/
version: ^0.0.2
version: ^0.1.0
wyatt_type_utils:
hosted: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub/
+6 -6
View File
@@ -1,17 +1,17 @@
<!--
* Copyright (C) 2022 WYATT GROUP
* Please see the AUTHORS file for details.
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
-->
@@ -116,11 +116,11 @@ Widget onBuild(BuildContext context, CounterState state) {
}
```
If needed, you can wrap what depends on the state with the function `onWrap`.
If needed, you can wrap what depends on the state with the function `parent`.
```dart
@override
Widget onWrap(BuildContext context, Widget child) {
Widget parent(BuildContext context, Widget child) {
return Scaffold(
appBar: AppBar(
title: const Text('Title'),
@@ -171,4 +171,4 @@ Widget onBuild(BuildContext context, CounterState state) {
> Note: check **BlocProvider** and **BlocConsumer** documentation for more information.
You'll find a more examples in the `example/lib/counter/` directory.
You'll find a more examples in the `example/lib/counter/` directory.
+1 -1
View File
@@ -62,7 +62,7 @@ abstract class BlocProviderScreen<Bloc extends blocbase.Bloc<Event, State>,
/// [shouldListenWhen] and [shouldBuildWhen] are optional and if they
/// aren't implemented, they will default to `true`.
///
/// An optional [onWrap] can also be implemented. This build a wrapper arround
/// An optional [parent] can also be implemented. This build a wrapper arround
/// the built BlocConsumer that is **not** rebuild on each state.
/// {@endtemplate}
abstract class BlocConsumerScreen<Bloc extends blocbase.Bloc<Event, State>,
@@ -33,7 +33,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
/// [shouldListenWhen] and [shouldBuildWhen] are optional and if they
/// aren't implemented, they will default to `true`.
///
/// An optional [onWrap] can also be implemented. This build a wrapper arround
/// An optional [parent] can also be implemented. This build a wrapper arround
/// the built [BlocConsumer] that is **not** rebuild on each state.
/// {@endtemplate}
abstract class BlocBaseConsumerScreen<Bloc extends BlocBase<State>,
@@ -51,10 +51,10 @@ abstract class BlocBaseConsumerScreen<Bloc extends BlocBase<State>,
/// [onListen] with the current `state`.
bool shouldListenWhen(State previous, State current) => true;
/// The [onWrap] function which will be invoked on build.
/// The [onWrap] takes a `BuildContext` that **doesn't have** access
/// The [parent] function which will be invoked on build.
/// The [parent] takes a `BuildContext` that **doesn't have** access
/// to the [Bloc] or [Cubit].
Widget onWrap(BuildContext context, Widget child) => child;
Widget parent(BuildContext context, Widget child) => child;
/// The [onBuild] function which will be invoked on each widget build.
/// The [onBuild] takes the `BuildContext` and current `state` and
@@ -66,7 +66,7 @@ abstract class BlocBaseConsumerScreen<Bloc extends BlocBase<State>,
void onListen(BuildContext context, State state) {}
@override
Widget build(BuildContext context) => onWrap(
Widget build(BuildContext context) => parent(
context,
BlocConsumer<Bloc, State>(
listenWhen: shouldListenWhen,
@@ -58,7 +58,7 @@ abstract class CubitProviderScreen<Cubit extends blocbase.Cubit<State>,
/// [shouldListenWhen] and [shouldBuildWhen] are optional and if they
/// aren't implemented, they will default to `true`.
///
/// An optional [onWrap] can also be implemented. This build a wrapper arround
/// An optional [parent] can also be implemented. This build a wrapper arround
/// the built BlocConsumer that is **not** rebuild on each state.
/// {@endtemplate}
abstract class CubitConsumerScreen<Cubit extends blocbase.Cubit<State>,
+4
View File
@@ -1,3 +1,7 @@
## 0.1.0+1
- Update a dependency to the latest release.
## 0.1.0
> Note: This release has breaking changes.
@@ -30,7 +30,7 @@ class CrudRepositoryImpl<Model extends ObjectModel>
}) : _crudDataSource = crudDataSource;
@override
FutureResult<void> create(Model object, {String? id}) =>
FutureOrResult<void> create(Model object, {String? id}) =>
Result.tryCatchAsync<void, AppException, AppException>(
() async {
await _crudDataSource.create(object, id: id);
@@ -39,21 +39,21 @@ class CrudRepositoryImpl<Model extends ObjectModel>
);
@override
FutureResult<Model?> get(String id) =>
FutureOrResult<Model?> get(String id) =>
Result.tryCatchAsync<Model?, AppException, AppException>(
() async => _crudDataSource.get(id),
(error) => error,
);
@override
FutureResult<List<Model?>> getAll() =>
FutureOrResult<List<Model?>> getAll() =>
Result.tryCatchAsync<List<Model?>, AppException, AppException>(
() async => _crudDataSource.getAll(),
(error) => error,
);
@override
FutureResult<void> update(
FutureOrResult<void> update(
String id, {
Model? object,
Map<String, dynamic>? raw,
@@ -64,28 +64,28 @@ class CrudRepositoryImpl<Model extends ObjectModel>
);
@override
FutureResult<void> updateAll(Map<String, Object?> raw) =>
FutureOrResult<void> updateAll(Map<String, Object?> raw) =>
Result.tryCatchAsync<void, AppException, AppException>(
() async => _crudDataSource.updateAll(raw),
(error) => error,
);
@override
FutureResult<void> delete(String id) =>
FutureOrResult<void> delete(String id) =>
Result.tryCatchAsync<void, AppException, AppException>(
() async => _crudDataSource.delete(id),
(error) => error,
);
@override
FutureResult<void> deleteAll() =>
FutureOrResult<void> deleteAll() =>
Result.tryCatchAsync<void, AppException, AppException>(
() async => _crudDataSource.deleteAll(),
(error) => error,
);
@override
FutureResult<List<Model?>> query(List<QueryInterface> conditions) =>
FutureOrResult<List<Model?>> query(List<QueryInterface> conditions) =>
Result.tryCatchAsync<List<Model?>, AppException, AppException>(
() async => _crudDataSource.query(conditions),
(error) => error,
@@ -20,18 +20,18 @@ import 'package:wyatt_crud_bloc/src/domain/entities/query.dart';
abstract class CrudRepository<Model extends ObjectModel>
extends BaseRepository {
FutureResult<void> create(Model object, {String? id});
FutureResult<Model?> get(String id);
FutureResult<List<Model?>> getAll();
FutureResult<void> update(
FutureOrResult<void> create(Model object, {String? id});
FutureOrResult<Model?> get(String id);
FutureOrResult<List<Model?>> getAll();
FutureOrResult<void> update(
String id, {
Model? object,
Map<String, dynamic>? raw,
});
FutureResult<void> updateAll(Map<String, Object?> raw);
FutureResult<void> delete(String id);
FutureResult<void> deleteAll();
FutureResult<List<Model?>> query(List<QueryInterface> conditions);
FutureOrResult<void> updateAll(Map<String, Object?> raw);
FutureOrResult<void> delete(String id);
FutureOrResult<void> deleteAll();
FutureOrResult<List<Model?>> query(List<QueryInterface> conditions);
StreamResult<List<Model?>> stream({
String? id,
List<QueryInterface>? conditions,
@@ -15,15 +15,24 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:wyatt_architecture/wyatt_architecture.dart';
import 'package:wyatt_crud_bloc/src/domain/entities/object_model.dart';
import 'package:wyatt_crud_bloc/src/domain/repositories/crud_repository.dart';
class Create<Model extends ObjectModel> extends UseCase<Model, void> {
class Create<Model extends ObjectModel> extends AsyncUseCase<Model, void> {
final CrudRepository<Model> _crudRepository;
Create(this._crudRepository);
@override
FutureResult<void> call(Model params) => _crudRepository.create(params);
FutureOr<void> onStart(Model? params) {
if(params == null){
throw ClientException('$Model cannot be null.');
}
}
@override
FutureOrResult<void> call(Model? params) => _crudRepository.create(params!);
}
@@ -14,15 +14,24 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:wyatt_architecture/wyatt_architecture.dart';
import 'package:wyatt_crud_bloc/src/domain/entities/object_model.dart';
import 'package:wyatt_crud_bloc/src/domain/repositories/crud_repository.dart';
class Delete<Model extends ObjectModel> extends UseCase<String, void> {
class Delete<Model extends ObjectModel> extends AsyncUseCase<String, void> {
final CrudRepository<Model> _crudRepository;
Delete(this._crudRepository);
@override
FutureResult<void> call(String params) => _crudRepository.delete(params);
FutureOr<void> onStart(String? params) {
if(params == null){
throw ClientException('Id cannot be null.');
}
}
@override
FutureOrResult<void> call(String? params) => _crudRepository.delete(params!);
}
@@ -18,11 +18,11 @@ import 'package:wyatt_architecture/wyatt_architecture.dart';
import 'package:wyatt_crud_bloc/src/domain/entities/object_model.dart';
import 'package:wyatt_crud_bloc/src/domain/repositories/crud_repository.dart';
class DeleteAll<Model extends ObjectModel> extends UseCase<void, void> {
class DeleteAll<Model extends ObjectModel> extends AsyncUseCase<void, void> {
final CrudRepository<Model> _crudRepository;
DeleteAll(this._crudRepository);
@override
FutureResult<void> call(void params) => _crudRepository.deleteAll();
FutureOrResult<void> call(void params) => _crudRepository.deleteAll();
}
@@ -14,15 +14,24 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:wyatt_architecture/wyatt_architecture.dart';
import 'package:wyatt_crud_bloc/src/domain/entities/object_model.dart';
import 'package:wyatt_crud_bloc/src/domain/repositories/crud_repository.dart';
class Get<Model extends ObjectModel> extends UseCase<String, Model?> {
class Get<Model extends ObjectModel> extends AsyncUseCase<String, Model?> {
final CrudRepository<Model> _crudRepository;
Get(this._crudRepository);
@override
FutureResult<Model?> call(String params) => _crudRepository.get(params);
FutureOr<void> onStart(String? params) {
if(params == null){
throw ClientException('Id cannot be null.');
}
}
@override
FutureOrResult<Model?> call(String? params) => _crudRepository.get(params!);
}
@@ -18,11 +18,12 @@ import 'package:wyatt_architecture/wyatt_architecture.dart';
import 'package:wyatt_crud_bloc/src/domain/entities/object_model.dart';
import 'package:wyatt_crud_bloc/src/domain/repositories/crud_repository.dart';
class GetAll<Model extends ObjectModel> extends UseCase<void, List<Model?>> {
class GetAll<Model extends ObjectModel>
extends AsyncUseCase<void, List<Model?>> {
final CrudRepository<Model> _crudRepository;
GetAll(this._crudRepository);
@override
FutureResult<List<Model?>> call(void params) => _crudRepository.getAll();
FutureOrResult<List<Model?>> call(void params) => _crudRepository.getAll();
}
@@ -14,18 +14,27 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:wyatt_architecture/wyatt_architecture.dart';
import 'package:wyatt_crud_bloc/src/domain/entities/object_model.dart';
import 'package:wyatt_crud_bloc/src/domain/entities/query.dart';
import 'package:wyatt_crud_bloc/src/domain/repositories/crud_repository.dart';
class Query<Model extends ObjectModel>
extends UseCase<List<QueryInterface>, List<Model?>> {
extends AsyncUseCase<List<QueryInterface>, List<Model?>> {
final CrudRepository<Model> _crudRepository;
Query(this._crudRepository);
@override
FutureResult<List<Model?>> call(List<QueryInterface> params) =>
_crudRepository.query(params);
FutureOr<void> onStart(List<QueryInterface>? params) {
if(params == null){
throw ClientException('List of conditions cannot be null.');
}
}
@override
FutureOrResult<List<Model?>> call(List<QueryInterface>? params) =>
_crudRepository.query(params!);
}
@@ -14,11 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// TODO(hpcl): add streamed usecase in wyatt_architecture
// import 'package:wyatt_architecture/wyatt_architecture.dart';
// import 'package:wyatt_crud_bloc/src/domain/repositories/crud_repository.dart';
// import 'package:wyatt_crud_bloc/src/domain/usecases/params/stream_parameters.dart';
// class Stream<Model extends ObjectModel> extends UseCase<StreamParameters, List<Model?>> {
// final CrudRepository<Model> _crudRepository;
@@ -29,3 +25,20 @@
// StreamResult<List<Model?>> call(StreamParameters params) =>
// _crudRepository.stream(id: params.id, conditions: params.conditions);
// }
// class StreamQuery<Model extends ObjectModel>
// extends StreamUseCase<StreamParameters, List<Model?>> {
// final CrudRepository<Model> _crudRepository;
// StreamQuery(this._crudRepository);
// @override
// FutureOr<void> onStart(StreamParameters? params) {
// if(params == null){
// throw ClientException('Stream parameters cannot be null.');
// }
// }
// @override
// FutureOrResult<Stream<List<Model?>>> call(StreamParameters? params) => _crudRepository.stream();
// }
@@ -14,21 +14,30 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:wyatt_architecture/wyatt_architecture.dart';
import 'package:wyatt_crud_bloc/src/domain/entities/object_model.dart';
import 'package:wyatt_crud_bloc/src/domain/repositories/crud_repository.dart';
import 'package:wyatt_crud_bloc/src/domain/usecases/params/update_parameters.dart';
class Update<Model extends ObjectModel>
extends UseCase<UpdateParameters<Model>, void> {
extends AsyncUseCase<UpdateParameters<Model>, void> {
final CrudRepository<Model> _crudRepository;
Update(this._crudRepository);
@override
FutureResult<void> call(UpdateParameters<Model> params) =>
FutureOr<void> onStart(UpdateParameters<Model>? params) {
if(params == null){
throw ClientException('Update parameters cannot be null.');
}
}
@override
FutureOrResult<void> call(UpdateParameters<Model>? params) =>
_crudRepository.update(
params.id,
params!.id,
object: params.object,
raw: params.raw,
);
@@ -14,17 +14,26 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:wyatt_architecture/wyatt_architecture.dart';
import 'package:wyatt_crud_bloc/src/domain/entities/object_model.dart';
import 'package:wyatt_crud_bloc/src/domain/repositories/crud_repository.dart';
class UpdateAll<Model extends ObjectModel>
extends UseCase<Map<String, Object?>, void> {
extends AsyncUseCase<Map<String, Object?>, void> {
final CrudRepository<Model> _crudRepository;
UpdateAll(this._crudRepository);
@override
FutureResult<void> call(Map<String, Object?> params) =>
_crudRepository.updateAll(params);
FutureOr<void> onStart(Map<String, Object?>? params) {
if(params == null){
throw ClientException('Data cannot be null.');
}
}
@override
FutureOrResult<void> call(Map<String, Object?>? params) =>
_crudRepository.updateAll(params!);
}
@@ -21,6 +21,6 @@ export 'get.dart';
export 'get_all.dart';
export 'params/params.dart';
export 'query.dart';
export 'stream.dart';
export 'stream_query.dart';
export 'update.dart';
export 'update_all.dart';
+2 -2
View File
@@ -1,7 +1,7 @@
name: wyatt_crud_bloc
description: Create/Read/Update/Delete BLoC for Flutter
repository: https://git.wyatt-studio.fr/Wyatt-FOSS/wyatt-packages/src/branch/master/packages/wyatt_crud_bloc
version: 0.1.0
version: 0.1.0+1
publish_to: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub
@@ -19,7 +19,7 @@ dependencies:
wyatt_architecture:
hosted: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub/
version: 0.0.2
version: 0.1.0
wyatt_type_utils:
hosted: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub/
+4
View File
@@ -1,3 +1,7 @@
## 0.2.0+1
- Update a dependency to the latest release.
## 0.2.0
> Note: This release has breaking changes.
+2 -2
View File
@@ -1,7 +1,7 @@
name: wyatt_form_bloc
description: Manage forms in Dart & Flutter with Bloc
repository: https://git.wyatt-studio.fr/Wyatt-FOSS/wyatt-packages/src/branch/master/packages/wyatt_form_bloc
version: 0.2.0
version: 0.2.0+1
publish_to: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub
@@ -17,7 +17,7 @@ dependencies:
wyatt_architecture:
hosted: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub/
version: ^0.0.2
version: ^0.1.0
wyatt_type_utils:
hosted: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub/
@@ -16,7 +16,10 @@
// // ignore_for_file: avoid_positional_boolean_parameters
import 'dart:async';
part 'future_result.dart';
part 'future_or_result.dart';
part 'result.dart';
part 'option.dart';
@@ -0,0 +1,126 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
part of 'either_base.dart';
extension FutureOrResultExtension<T, E> on FutureOr<Result<T, E>> {
/// Represents the left side of [Result] class.
Future<bool> get isOk => Future.value(this).then((result) => result.isOk);
/// Represents the right side of [Result] class.
Future<bool> get isErr => Future.value(this).then((result) => result.isErr);
/// Get [U] value, may throw an exception.
Future<U> unwrap<U>() =>
Future.value(this).then((result) => result.unwrap<U>());
/// Get **async** [U] value, may throw an exception.
///
/// With nullable, `Future(Future(U)) == Future(U)`
Future<U> unwrapAsync<U>() =>
Future.value(this).then((result) => result.unwrapAsync<U>());
/// Fold [Ok] and [Err] into the value of one type
Future<U> fold<U>(
U Function(T value) valueTransformer,
U Function(E error) errorTransformer,
) =>
Future.value(this)
.then((result) => result.fold(valueTransformer, errorTransformer));
/// Fold [Ok] and [Err] **asynchronously** into the value of one type
Future<U> foldAsync<U>(
Future<U> Function(T value) valueTransformer,
Future<U> Function(E error) errorTransformer,
) =>
Future.value(this).then(
(result) => result.foldAsync(
valueTransformer,
errorTransformer,
),
);
/// Swap [Ok] and [Err]
Future<Result<E, T>> swap() =>
Future.value(this).then((result) => result.swap());
/// Returns [res] if the [Result] is [Ok], otherwise returns
/// the [Err] value of this.
Future<Result<U, E>> and<U>(Result<U, E> res) =>
Future.value(this).then((result) => result.and(res));
/// Returns [res] if the [Result] is [Err], otherwise returns
/// the [Ok] value of this.
Future<Result<T, F>> or<F>(Result<T, F> res) =>
Future.value(this).then((result) => result.or(res));
/// Returns true if the result is an [Ok] or [Err] value containing
/// the given value/error.
Future<bool> contains<U>(U x) =>
Future.value(this).then((result) => result.contains(x));
/// Returns the contained [Ok] value. Throw [ResultException] on [Err] with
/// its content.
Future<T> expect(String msg) =>
Future.value(this).then((result) => result.expect(msg));
/// Returns the contained [Err] value. Throw [ResultException] on [Ok] with
/// its content.
Future<E> expectErr(String msg) =>
Future.value(this).then((result) => result.expectErr(msg));
/// Maps a [Result<T, E>] to [Result<U, E>] by applying a function to a
/// contained [Ok] value, leaving an [Err] value untouched.
Future<Result<U, E>> map<U>(U Function(T value) mapper) =>
Future.value(this).then((result) => result.map(mapper));
/// Maps a [Result<T, E>] to [Result<U, E>] by applying an **async** function
/// to a contained [Ok] value, leaving an [Err] value untouched.
Future<Result<U, E>> mapAsync<U>(Future<U> Function(T value) mapper) =>
Future.value(this).then((result) => result.mapAsync(mapper));
/// Maps a [Result<T, E>] to [Result<T, F>] by applying a function to a
/// contained [Err] value, leaving an [Ok] value untouched.
Future<Result<T, F>> mapErr<F>(F Function(E error) mapper) =>
Future.value(this).then((result) => result.mapErr(mapper));
/// Maps a [Result<T, E>] to [Result<U, E>] by applying an **async** function
/// to a contained [Err] value, leaving an [Ok] value untouched.
Future<Result<T, F>> mapErrAsync<F>(Future<F> Function(E error) mapper) =>
Future.value(this).then((result) => result.mapErrAsync(mapper));
/// Transforms a [Result<T, E>] to [Result<U, F>] by applying functions to
/// contained [Ok] and [Err] values.
Future<Result<U, F>> either<U, F>(
U Function(T value) valueTransformer,
F Function(E error) errorTransformer,
) =>
Future.value(this)
.then((result) => result.either(valueTransformer, errorTransformer));
/// Transforms a [Result<T, E>] to [Result<U, F>] by applying **async**
/// functions to contained [Ok] and [Err] values.
Future<Result<U, F>> eitherAsync<U, F>(
Future<U> Function(T value) valueTransformer,
Future<F> Function(E error) errorTransformer,
) =>
Future.value(this).then(
(result) => result.eitherAsync(
valueTransformer,
errorTransformer,
),
);
}