From 2bfe61b6a29ab70db6a167ef01ea85bb25ae2247 Mon Sep 17 00:00:00 2001 From: Chima Precious Date: Wed, 17 Apr 2024 22:35:07 +0000 Subject: [PATCH] chore: Improvements (#22) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * entity type analyzer: wip * misc * wip * little baby steps, we making progress 🔥 * use new orm structure * tiny fix * wip * use new improvements from orm * all tests passing * tiny fix * tiny fix * remove test code * restore db config switching --- .DS_Store | Bin 6148 -> 6148 bytes .vscode/settings.json | 9 ++- analysis_options.yaml | 1 - bin/tools/migrator.dart | 13 ++-- database/config.dart | 2 +- .../migrations/create_articles_table.dart | 22 ++----- database/migrations/create_users_table.dart | 16 ++--- lib/app/middlewares/api_auth_middleware.dart | 9 +-- lib/app/providers/provide_blog_services.dart | 2 - lib/backend.dart | 13 +--- lib/src/controllers/article_controller.dart | 7 +- lib/src/controllers/auth_controller.dart | 25 +++---- lib/src/controllers/user_controller.dart | 13 ++-- lib/src/{models => }/dto/article_dto.dart | 0 lib/src/{models => }/dto/dto.dart | 0 lib/src/{models => }/dto/user_dto.dart | 0 lib/src/models/article.dart | 24 ------- lib/src/models/article/article.dart | 57 ++++++++++++++++ lib/src/models/models.dart | 2 - lib/src/models/user.dart | 21 ------ lib/src/models/user/user.dart | 51 ++++++++++++++ lib/src/services/article_service.dart | 62 +++++++++++++----- lib/src/services/auth_service.dart | 5 +- lib/src/services/services.dart | 1 - lib/src/services/user_service.dart | 12 ---- lib/src/utils/utils.dart | 8 +++ pubspec.lock | 38 ++++++----- pubspec.yaml | 14 ++-- test/backend_test.dart | 37 ++++++----- 29 files changed, 265 insertions(+), 199 deletions(-) rename lib/src/{models => }/dto/article_dto.dart (100%) rename lib/src/{models => }/dto/dto.dart (100%) rename lib/src/{models => }/dto/user_dto.dart (100%) delete mode 100644 lib/src/models/article.dart create mode 100644 lib/src/models/article/article.dart delete mode 100644 lib/src/models/models.dart delete mode 100644 lib/src/models/user.dart create mode 100644 lib/src/models/user/user.dart delete mode 100644 lib/src/services/user_service.dart create mode 100644 lib/src/utils/utils.dart diff --git a/.DS_Store b/.DS_Store index d0dcf172a5b512d4e1e9241d3363dabef2557c24..f3721f5b034b2ba1dae85ff36329d3a0cdc5cc76 100644 GIT binary patch delta 78 zcmZoMXfc=|#>B)qu~2NHo+2ar#(>?7jO>$nSc)e{_ z5>e)u)Z&fVvww2S1y_ta#08I)d6G{#SST?wrXz%nF5F3-_(`-{e^|vm*^nw9O}Nan z*qY# dS`ul=s2Ti+w6DHZQmb2r0Ax1G^rZf(egRFUUZMa1 diff --git a/.vscode/settings.json b/.vscode/settings.json index f4607f2..14a5d44 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,8 @@ { - "dart.lineLength": 120 -} + "dart.lineLength": 120, + "[dart]": { + "editor.rulers": [ + 120 + ], + } +} \ No newline at end of file diff --git a/analysis_options.yaml b/analysis_options.yaml index c364757..02ab9fa 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -22,7 +22,6 @@ include: package:lints/recommended.yaml analyzer: exclude: - "**.reflectable.dart" - - "**.g.dart" # For more information about the core and recommended set of lints, see # https://dart.dev/go/core-lints diff --git a/bin/tools/migrator.dart b/bin/tools/migrator.dart index 73da399..7b5be99 100644 --- a/bin/tools/migrator.dart +++ b/bin/tools/migrator.dart @@ -1,12 +1,13 @@ -// ignore: depend_on_referenced_packages -import 'package:yaroo_cli/orm/orm.dart'; +import 'package:backend/src/models/article/article.dart'; +import 'package:backend/src/models/user/user.dart'; +import 'package:yaroo_cli/orm.dart'; +import 'package:yaroorm/yaroorm.dart'; import '../../database/config.dart' as orm; -import 'migrator.reflectable.dart'; - -export 'package:backend/src/models/models.dart'; void main(List args) async { - initializeReflectable(); + Query.addTypeDef(userTypeData); + Query.addTypeDef
(articleTypeData); + await OrmCLIRunner.start(args, orm.config); } diff --git a/database/config.dart b/database/config.dart index 408ae39..3c8cd1b 100644 --- a/database/config.dart +++ b/database/config.dart @@ -1,4 +1,4 @@ -import 'package:backend/backend.dart'; +import 'package:backend/src/utils/utils.dart'; import 'package:path/path.dart' as path; import 'package:yaroo/yaroo.dart'; import 'package:yaroorm/yaroorm.dart'; diff --git a/database/migrations/create_articles_table.dart b/database/migrations/create_articles_table.dart index 56bf16b..90a8eaa 100644 --- a/database/migrations/create_articles_table.dart +++ b/database/migrations/create_articles_table.dart @@ -1,28 +1,14 @@ -import 'package:backend/src/models/models.dart'; -import 'package:yaroorm/migration.dart'; +import 'package:backend/src/models/article/article.dart'; +import 'package:yaroorm/yaroorm.dart'; class CreateArticlesTable extends Migration { @override void up(List schemas) { - final articleSchema = Schema.create('articles', (table) { - return table - ..id() - ..string('title') - ..string('description') - ..string('imageUrl', nullable: true) - ..integer('ownerId') - ..foreign( - column: 'ownerId', - onKey: (fkey) => fkey.actions(onDelete: ForeignKeyAction.cascade, onUpdate: ForeignKeyAction.cascade), - ) - ..timestamps(); - }); - - schemas.add(articleSchema); + schemas.add(ArticleSchema); } @override void down(List actions) { - actions.add(Schema.dropIfExists('articles')); + actions.add(Schema.dropIfExists(ArticleSchema)); } } diff --git a/database/migrations/create_users_table.dart b/database/migrations/create_users_table.dart index 9f67ba6..af5cff9 100644 --- a/database/migrations/create_users_table.dart +++ b/database/migrations/create_users_table.dart @@ -1,22 +1,14 @@ -import 'package:yaroorm/migration.dart'; +import 'package:backend/src/models/user/user.dart'; +import 'package:yaroorm/yaroorm.dart'; class CreateUsersTable extends Migration { @override void up(List schemas) { - final userSchema = Schema.create('users', (table) { - return table - ..id() - ..string('name') - ..string('email') - ..string('password') - ..timestamps(); - }); - - schemas.add(userSchema); + schemas.add(UserSchema); } @override void down(List schemas) { - schemas.add(Schema.dropIfExists('users')); + schemas.add(Schema.dropIfExists(UserSchema)); } } diff --git a/lib/app/middlewares/api_auth_middleware.dart b/lib/app/middlewares/api_auth_middleware.dart index 1f3e8af..5f11a4d 100644 --- a/lib/app/middlewares/api_auth_middleware.dart +++ b/lib/app/middlewares/api_auth_middleware.dart @@ -1,18 +1,19 @@ -import 'package:backend/src/services/services.dart'; import 'package:yaroo/http/http.dart'; +import '../../src/models/user/user.dart'; +import '../../src/services/auth_service.dart'; + class ApiAuthMiddleware extends Middleware { final AuthService _authService; - final UserService _userService; - ApiAuthMiddleware(this._userService, this._authService); + ApiAuthMiddleware(this._authService); @override handle(Request req, Response res, NextFunction next) async { final userId = _authService.validateRequest(req); if (userId == null) return next(res.unauthorized()); - final user = await _userService.getUser(userId); + final user = await UserQuery.findById(userId); if (user == null) return next(res.unauthorized()); return next(req..auth = user); diff --git a/lib/app/providers/provide_blog_services.dart b/lib/app/providers/provide_blog_services.dart index 7e558d6..9d26da2 100644 --- a/lib/app/providers/provide_blog_services.dart +++ b/lib/app/providers/provide_blog_services.dart @@ -4,8 +4,6 @@ import 'package:yaroo/http/http.dart'; class BlogServiceProvider extends ServiceProvider { @override void register() { - app.singleton(UserService()); - app.singleton(ArticleService()); } } diff --git a/lib/backend.dart b/lib/backend.dart index a4ed083..886a54e 100644 --- a/lib/backend.dart +++ b/lib/backend.dart @@ -9,19 +9,10 @@ import 'package:yaroo/yaroo.dart'; import 'app/middlewares/core_middleware.dart'; import 'app/middlewares/api_auth_middleware.dart'; import 'app/providers/providers.dart'; +import 'src/utils/utils.dart'; export 'src/controllers/controllers.dart'; -export 'src/models/models.dart'; -export 'src/models/dto/dto.dart'; - -bool get isDebugMode { - var isDebug = false; - assert(() { - isDebug = true; - return true; - }()); - return isDebug; -} +export 'src/dto/dto.dart'; final blogApp = App(AppConfig( name: 'Dart Blog', diff --git a/lib/src/controllers/article_controller.dart b/lib/src/controllers/article_controller.dart index 28527a1..0be8850 100644 --- a/lib/src/controllers/article_controller.dart +++ b/lib/src/controllers/article_controller.dart @@ -1,9 +1,10 @@ -import 'package:backend/src/models/dto/article_dto.dart'; +import 'package:backend/src/dto/article_dto.dart'; import 'package:backend/src/services/services.dart'; import 'package:yaroo/http/http.dart'; import 'package:yaroo/http/meta.dart'; -import '../models/models.dart'; +import '../models/article/article.dart'; +import '../models/user/user.dart'; class ArticleController extends HTTPController { final ArticleService _articleService; @@ -38,7 +39,7 @@ class ArticleController extends HTTPController { } Future delete(@param int articleId) async { - await _articleService.deleteArticle(user.id!, articleId); + await _articleService.deleteArticle(user.id, articleId); return response.json({'message': 'Article deleted'}); } diff --git a/lib/src/controllers/auth_controller.dart b/lib/src/controllers/auth_controller.dart index 7634349..ee33574 100644 --- a/lib/src/controllers/auth_controller.dart +++ b/lib/src/controllers/auth_controller.dart @@ -2,20 +2,20 @@ import 'dart:io'; import 'package:yaroo/http/http.dart'; import 'package:yaroo/http/meta.dart'; -import 'package:yaroorm/yaroorm.dart'; -import 'package:backend/src/models/dto/dto.dart'; -import 'package:backend/src/models/models.dart'; -import 'package:backend/src/services/services.dart'; + import 'package:bcrypt/bcrypt.dart'; +import '../dto/dto.dart'; +import '../models/user/user.dart'; +import '../services/services.dart'; + class AuthController extends HTTPController { final AuthService _authService; - final UserService _userService; - AuthController(this._authService, this._userService); + AuthController(this._authService); Future login(@body LoginUserDTO data) async { - final user = await DB.query().whereEqual('email', data.email).findOne(); + final user = await UserQuery.findByEmail(data.email); if (user == null) return invalidLogin; final match = BCrypt.checkpw(data.password, user.password); @@ -28,13 +28,16 @@ class AuthController extends HTTPController { } Future register(@body CreateUserDTO data) async { - final existing = await DB.query().whereEqual('email', data.email).findOne(); - if (existing != null) { - return response.json(_makeError(['Email already taken']), statusCode: HttpStatus.badRequest); + final userExists = await UserQuery.where((user) => user.email(data.email)).exists(); + if (userExists) { + return response.json( + _makeError(['Email already taken']), + statusCode: HttpStatus.badRequest, + ); } final hashedPass = BCrypt.hashpw(data.password, BCrypt.gensalt()); - final newUser = await _userService.newUser(data.name, data.email, hashedPass); + final newUser = await UserQuery.create(name: data.name, email: data.email, password: hashedPass); return response.json(_userResponse(newUser)); } diff --git a/lib/src/controllers/user_controller.dart b/lib/src/controllers/user_controller.dart index ed5b53a..366bdda 100644 --- a/lib/src/controllers/user_controller.dart +++ b/lib/src/controllers/user_controller.dart @@ -1,13 +1,10 @@ -import 'package:backend/src/models/models.dart'; -import 'package:backend/src/services/services.dart'; import 'package:yaroo/http/http.dart'; import 'package:yaroo/http/meta.dart'; -import 'package:yaroorm/yaroorm.dart'; -class UserController extends HTTPController { - final UserService userSvc; +import '../models/user/user.dart'; - UserController(this.userSvc); +class UserController extends HTTPController { + UserController(); Future currentUser() async { final user = request.auth as User; @@ -15,12 +12,12 @@ class UserController extends HTTPController { } Future index() async { - final result = await DB.query().all(); + final result = await UserQuery.findMany(); return jsonResponse(result); } Future show(@param int userId) async { - final user = await userSvc.getUser(userId); + final user = await UserQuery.findById(userId); if (user == null) return notFound('User not found'); return jsonResponse({'user': user.toJson()}); } diff --git a/lib/src/models/dto/article_dto.dart b/lib/src/dto/article_dto.dart similarity index 100% rename from lib/src/models/dto/article_dto.dart rename to lib/src/dto/article_dto.dart diff --git a/lib/src/models/dto/dto.dart b/lib/src/dto/dto.dart similarity index 100% rename from lib/src/models/dto/dto.dart rename to lib/src/dto/dto.dart diff --git a/lib/src/models/dto/user_dto.dart b/lib/src/dto/user_dto.dart similarity index 100% rename from lib/src/models/dto/user_dto.dart rename to lib/src/dto/user_dto.dart diff --git a/lib/src/models/article.dart b/lib/src/models/article.dart deleted file mode 100644 index 193259a..0000000 --- a/lib/src/models/article.dart +++ /dev/null @@ -1,24 +0,0 @@ -import 'package:backend/src/models/models.dart'; -import 'package:json_annotation/json_annotation.dart'; -import 'package:yaroorm/yaroorm.dart'; - -part 'article.g.dart'; - -@JsonSerializable() -@EntityMeta(table: 'articles', timestamps: true) -class Article extends Entity { - String title; - String description; - - String? imageUrl; - - final int ownerId; - - Article(this.ownerId, this.title, this.description, {this.imageUrl}); - - Map toJson() => _$ArticleToJson(this); - - Future get owner => DB.query().get(ownerId); - - factory Article.fromJson(Map json) => _$ArticleFromJson(json); -} diff --git a/lib/src/models/article/article.dart b/lib/src/models/article/article.dart new file mode 100644 index 0000000..a4d496f --- /dev/null +++ b/lib/src/models/article/article.dart @@ -0,0 +1,57 @@ +import 'package:yaroorm/yaroorm.dart'; + +import '../user/user.dart'; + +part 'article.g.dart'; + +@Table('articles', converters: [dateTimeConverter, booleanConverter]) +class Article extends Entity
{ + @primaryKey + final int id; + + final String title; + final String description; + + final String? imageUrl; + + @reference(User, name: 'owner_id', onDelete: ForeignKeyAction.cascade) + final int ownerId; + + @createdAtCol + final DateTime createdAt; + + @updatedAtCol + final DateTime updatedAt; + + Article( + this.id, + this.title, + this.ownerId, + this.description, { + this.imageUrl, + required this.createdAt, + required this.updatedAt, + }); + + BelongsTo get owner => belongsTo(); + + Map toJson() => { + 'id': id, + 'createdAt': createdAt.toIso8601String(), + 'updatedAt': updatedAt.toIso8601String(), + 'title': title, + 'description': description, + 'imageUrl': imageUrl, + 'ownerId': ownerId, + }; + + factory Article.fromJson(Map json) => Article( + json['id'] as int, + json['title'] as String, + json['ownerId'] as int, + json['description'] as String, + imageUrl: json['imageUrl'] as String?, + createdAt: DateTime.parse(json['createdAt'] as String), + updatedAt: DateTime.parse(json['updatedAt'] as String), + ); +} diff --git a/lib/src/models/models.dart b/lib/src/models/models.dart deleted file mode 100644 index 0ccfdb7..0000000 --- a/lib/src/models/models.dart +++ /dev/null @@ -1,2 +0,0 @@ -export 'user.dart'; -export 'article.dart'; diff --git a/lib/src/models/user.dart b/lib/src/models/user.dart deleted file mode 100644 index 63c78aa..0000000 --- a/lib/src/models/user.dart +++ /dev/null @@ -1,21 +0,0 @@ -import 'package:json_annotation/json_annotation.dart'; -import 'package:yaroorm/yaroorm.dart'; - -part 'user.g.dart'; - -@JsonSerializable() -@EntityMeta(table: 'users', timestamps: true) -class User extends Entity { - final String name; - - final String email; - - @JsonKey(includeToJson: false, defaultValue: '') - final String password; - - User(this.name, this.email, {required this.password}); - - Map toJson() => _$UserToJson(this); - - factory User.fromJson(Map json) => _$UserFromJson(json); -} diff --git a/lib/src/models/user/user.dart b/lib/src/models/user/user.dart new file mode 100644 index 0000000..a6b5b1c --- /dev/null +++ b/lib/src/models/user/user.dart @@ -0,0 +1,51 @@ +import 'package:yaroorm/yaroorm.dart'; + +import '../article/article.dart'; + +part 'user.g.dart'; + +@Table('users') +class User extends Entity { + @primaryKey + final int id; + + final String name; + + final String email; + + final String password; + + @createdAtCol + final DateTime createdAt; + + @updatedAtCol + final DateTime updatedAt; + + User( + this.id, + this.name, + this.email, { + required this.password, + required this.createdAt, + required this.updatedAt, + }); + + HasMany get articles => hasMany
(); + + Map toJson() => { + 'id': id, + 'name': name, + 'email': email, + 'createdAt': createdAt.toIso8601String(), + 'updatedAt': updatedAt.toIso8601String(), + }; + + factory User.fromJson(Map json) => User( + json['id'] as int, + json['name'] as String, + json['email'] as String, + password: json['password'] as String? ?? '', + createdAt: DateTime.parse(json['createdAt'] as String), + updatedAt: DateTime.parse(json['updatedAt'] as String), + ); +} diff --git a/lib/src/services/article_service.dart b/lib/src/services/article_service.dart index a9d53c5..8a9f8fa 100644 --- a/lib/src/services/article_service.dart +++ b/lib/src/services/article_service.dart @@ -2,42 +2,68 @@ import 'dart:convert'; import 'dart:io'; import 'dart:isolate'; -import 'package:backend/src/models/dto/article_dto.dart'; -import 'package:backend/src/models/models.dart'; +import 'package:backend/src/dto/article_dto.dart'; +import 'package:backend/src/models/article/article.dart'; import 'package:yaroo/yaroo.dart'; import 'package:yaroorm/yaroorm.dart'; import 'package:http/http.dart' as http; +import '../models/user/user.dart'; + class ArticleService { - Future> getArticles({String? ownerId}) async { - final query = DB.query
().orderByDesc('updatedAt'); - if (ownerId == null) return query.all(); + Future> getArticles({int? ownerId}) async { + if (ownerId == null) { + return ArticleQuery.findMany( + orderBy: [ + OrderArticleBy.title(OrderDirection.asc), + OrderArticleBy.updatedAt(OrderDirection.desc), + ], + ); + } - return query.whereEqual('ownerId', ownerId).findMany(); + return ArticleQuery.where((article) => article.ownerId(ownerId)).findMany( + orderBy: [ + OrderArticleBy.updatedAt(OrderDirection.desc), + ], + ); } - Future getArticle(int articleId) => DB.query
().get(articleId); + Future getArticle(int articleId) => ArticleQuery.findById(articleId); Future
createArticle(User user, CreateArticleDTO data, {String? imageUrl}) async { imageUrl ??= await getRandomImage(data.title); - return Article(user.id!, data.title, data.description, imageUrl: imageUrl).save(); + + return await ArticleQuery.create( + title: data.title, + description: data.description, + ownerId: user.id, + imageUrl: imageUrl, + ); } Future updateArticle(User user, int articleId, CreateArticleDTO dto) async { - final userId = user.id!; - final query = DB.query
().whereEqual('id', articleId).whereEqual('ownerId', userId); - final article = await query.findOne(); - if (article == null) return null; + final query = ArticleQuery.where((article) => article.and([ + article.id(articleId), + article.ownerId(user.id), + ])); - article - ..title = dto.title - ..description = dto.description - ..imageUrl = dto.imageUrl; + if (!(await query.exists())) return null; - return await article.save(); + await query.update( + title: value(dto.title), + description: value(dto.description), + imageUrl: value(dto.imageUrl), + ); + + return query.findOne(); } - Future deleteArticle(int userId, int articleId) => DB.query
().whereEqual('id', articleId).delete(); + Future deleteArticle(int userId, int articleId) { + return ArticleQuery.where((article) => article.and([ + article.id(articleId), + article.ownerId(userId), + ])).delete(); + } Future getRandomImage(String searchText) async { try { diff --git a/lib/src/services/auth_service.dart b/lib/src/services/auth_service.dart index aa82be2..9fee3a5 100644 --- a/lib/src/services/auth_service.dart +++ b/lib/src/services/auth_service.dart @@ -1,10 +1,11 @@ import 'dart:io'; -import 'package:backend/src/models/models.dart'; import 'package:collection/collection.dart'; import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart'; import 'package:yaroo/http/http.dart'; +import '../models/user/user.dart'; + class AuthService { final String jwtKey; final String issuer; @@ -14,7 +15,7 @@ class AuthService { JWTKey get _jwtKey => SecretKey(jwtKey); String getAccessTokenForUser(User user) { - final jwt = JWT(user.toJson(), issuer: issuer, subject: user.id!.toString(), jwtId: 'access-token'); + final jwt = JWT(user.toJson(), issuer: issuer, subject: user.id.toString(), jwtId: 'access-token'); return jwt.sign(_jwtKey, algorithm: JWTAlgorithm.HS256, expiresIn: Duration(hours: 1)); } diff --git a/lib/src/services/services.dart b/lib/src/services/services.dart index aa73102..22bbc5c 100644 --- a/lib/src/services/services.dart +++ b/lib/src/services/services.dart @@ -1,5 +1,4 @@ library services; -export 'user_service.dart'; export 'auth_service.dart'; export 'article_service.dart'; diff --git a/lib/src/services/user_service.dart b/lib/src/services/user_service.dart deleted file mode 100644 index f77cb60..0000000 --- a/lib/src/services/user_service.dart +++ /dev/null @@ -1,12 +0,0 @@ -import 'package:yaroorm/yaroorm.dart'; -import 'package:backend/src/models/models.dart'; - -class UserService { - Future newUser(String name, String email, String password) async { - return User(name, email, password: password).save(); - } - - Future getUser(int userId) async { - return DB.query().get(userId); - } -} diff --git a/lib/src/utils/utils.dart b/lib/src/utils/utils.dart new file mode 100644 index 0000000..4a18a46 --- /dev/null +++ b/lib/src/utils/utils.dart @@ -0,0 +1,8 @@ +bool get isDebugMode { + var isDebug = false; + assert(() { + isDebug = true; + return true; + }()); + return isDebug; +} diff --git a/pubspec.lock b/pubspec.lock index 4ca2f09..da86f7a 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -106,7 +106,7 @@ packages: source: hosted version: "2.4.2" build_runner: - dependency: transitive + dependency: "direct dev" description: name: build_runner sha256: "581bacf68f89ec8792f5e5a0b2c4decd1c948e97ce659dc783688c8a88fbec21" @@ -245,10 +245,10 @@ packages: dependency: transitive description: name: dart_style - sha256: "1efa911ca7086affd35f463ca2fc1799584fb6aa89883cf0af8e3664d6a02d55" + sha256: "6d691edde054969f0e0f26abb1b30834b5138b963793e56f69d3a9a4435e6352" url: "https://pub.dev" source: hosted - version: "2.3.2" + version: "2.3.0" dotenv: dependency: transitive description: @@ -550,10 +550,10 @@ packages: dependency: transitive description: name: postgres - sha256: b743c8b1d4af6e2840fa1e2ce2d3376b829d097b6db7340a1154effac69cc738 + sha256: bd1df6d2f4ad71aef92dc59e867e3ba9ec22cf2212a81cf9d35aa061ce80b1ae url: "https://pub.dev" source: hosted - version: "3.1.1" + version: "3.2.0" process: dependency: transitive description: @@ -750,10 +750,10 @@ packages: dependency: transitive description: name: sqflite_common_ffi - sha256: "754927d82de369a6b9e760fb60640aa81da650f35ffd468d5a992814d6022908" + sha256: "35d2fce1e971707c227cc4775cc017d5eafe06c2654c3435ebd5c3ad6c170f5f" url: "https://pub.dev" source: hosted - version: "2.3.2+1" + version: "2.3.0+4" sqlite3: dependency: transitive description: @@ -964,21 +964,25 @@ packages: source: git version: "0.0.1" yaroo_cli: - dependency: "direct dev" + dependency: "direct overridden" description: - path: "packages/yaroo_cli" - ref: HEAD - resolved-ref: e91a7a1218a35c23b7634186a270ceb43337e78c - url: "https://github.com/codekeyz/yaroo.git" - source: git + path: "../yaroorm/packages/orm_cli" + relative: true + source: path version: "1.0.0" yaroorm: dependency: "direct main" description: - name: yaroorm - sha256: "652afef1db82631540de247eef89be554c93a01cc7dbaa96fc9c7a03aa7e54c5" - url: "https://pub.dev" - source: hosted + path: "../yaroorm/packages/orm" + relative: true + source: path version: "0.0.2" + yaroorm_builder: + dependency: "direct dev" + description: + path: "../yaroorm/packages/generator" + relative: true + source: path + version: "1.0.0" sdks: dart: ">=3.3.0 <4.0.0" diff --git a/pubspec.yaml b/pubspec.yaml index 06cbf3f..76bfd41 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -18,7 +18,8 @@ dependencies: git: url: https://github.com/codekeyz/yaroo.git path: packages/yaroo - yaroorm: ^0.0.2 + yaroorm: + path: ../yaroorm/packages/orm collection: ^1.18.0 logger: ^2.0.2+1 @@ -27,13 +28,16 @@ dependencies: dependency_overrides: reflectable: + yaroo_cli: + path: ../yaroorm/packages/orm_cli + yaroorm: + path: ../yaroorm/packages/orm dev_dependencies: lints: ^3.0.0 test: ^1.24.0 json_serializable: ^6.7.1 melos: ^3.2.0 - yaroo_cli: - git: - url: https://github.com/codekeyz/yaroo.git - path: packages/yaroo_cli + build_runner: + yaroorm_builder: + path: ../yaroorm/packages/generator diff --git a/test/backend_test.dart b/test/backend_test.dart index d2b01f3..1b4d205 100644 --- a/test/backend_test.dart +++ b/test/backend_test.dart @@ -2,6 +2,8 @@ import 'dart:convert'; import 'dart:io'; import 'package:backend/backend.dart'; +import 'package:backend/src/models/article/article.dart'; +import 'package:backend/src/models/user/user.dart'; import 'package:yaroo/yaroo.dart'; import 'package:yaroorm/yaroorm.dart'; import '../database/config.dart' as orm; @@ -13,6 +15,9 @@ void main() { DB.init(orm.config); + Query.addTypeDef(userTypeData); + Query.addTypeDef
(articleTypeData); + late Spookie testAgent; setUpAll(() async { @@ -92,7 +97,7 @@ void main() { }); test('should error on existing email', () async { - final randomUser = await DB.query().get(); + final randomUser = await UserQuery.findOne(); expect(randomUser, isA()); await testAgent @@ -125,7 +130,7 @@ void main() { }); test('should error on in-valid credentials', () async { - final randomUser = await DB.query().get(); + final randomUser = await UserQuery.findOne(); expect(randomUser, isA()); final email = randomUser!.email; @@ -148,7 +153,7 @@ void main() { }); test('should success on valid credentials', () async { - final randomUser = await DB.query().get(); + final randomUser = await UserQuery.findOne(); expect(randomUser, isA()); final baseTest = testAgent.post(path, { @@ -170,7 +175,7 @@ void main() { User? currentUser; setUpAll(() async { - currentUser = await DB.query().get(); + currentUser = await UserQuery.findOne(); expect(currentUser, isA()); final result = await testAgent.post('$baseAPIPath/auth/login', { @@ -181,7 +186,7 @@ void main() { authCookie = result.headers[HttpHeaders.setCookieHeader]; expect(authCookie, isNotNull); - await DB.query
().whereEqual('ownerId', currentUser!.id).delete(); + await currentUser!.articles.delete(); }); group('Users', () { @@ -201,21 +206,17 @@ void main() { .expectHeader(HttpHeaders.contentTypeHeader, 'application/json; charset=utf-8') .expectBodyCustom( (body) => User.fromJson(jsonDecode(body)['user']), - isA().having( - (user) => [user.id, user.createdAt, user.updatedAt].every((e) => e != null), - 'user with properties', - isTrue, - ), + isA(), ) .test(); }); test('should get user `/users/` without auth', () async { - final randomUser = await DB.query().get(); + final randomUser = await UserQuery.findOne(); expect(randomUser, isA()); await testAgent - .get('$usersApiPath/${randomUser!.id!}') + .get('$usersApiPath/${randomUser!.id}') .expectStatus(HttpStatus.ok) .expectHeader(HttpHeaders.contentTypeHeader, 'application/json; charset=utf-8') .expectBodyCustom((body) => jsonDecode(body)['user'], randomUser.toJson()) @@ -323,7 +324,7 @@ void main() { }); test('should update article', () async { - final article = await DB.query
().whereEqual('ownerId', currentUser!.id!).findOne(); + final article = await ArticleQuery.where((article) => article.ownerId(currentUser!.id)).findOne(); expect(article, isA
()); expect(article!.title, isNot('Honey')); @@ -356,7 +357,7 @@ void main() { .test(); const fakeId = 234239389239; - final article = await DB.query
().get(fakeId); + final article = await ArticleQuery.findById(fakeId); expect(article, isNull); await testAgent @@ -367,7 +368,7 @@ void main() { }); test('should delete article', () async { - final article = await DB.query
().whereEqual('ownerId', currentUser!.id!).findOne(); + final article = await ArticleQuery.findByOwnerId(currentUser!.id); expect(article, isA
()); await testAgent @@ -376,7 +377,7 @@ void main() { .expectJsonBody({'message': 'Article deleted'}) .test(); - expect(await DB.query
().get(article.id!), isNull); + expect(await ArticleQuery.findById(article.id), isNull); }); }); @@ -401,7 +402,7 @@ void main() { }); test('should show article without auth', () async { - final article = await DB.query
().whereEqual('ownerId', currentUser!.id!).findOne(); + final article = await ArticleQuery.findByOwnerId(currentUser!.id); expect(article, isA
()); await testAgent @@ -412,7 +413,7 @@ void main() { }); test('should get Articles without auth', () async { - final articles = await DB.query
().all(); + final articles = await ArticleQuery.findMany(); expect(articles, isNotEmpty); await testAgent