Skip to content

Commit

Permalink
chore: Improvements (#22)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
codekeyz authored Apr 17, 2024
1 parent a86c6b8 commit 2bfe61b
Show file tree
Hide file tree
Showing 29 changed files with 265 additions and 199 deletions.
Binary file modified .DS_Store
Binary file not shown.
9 changes: 7 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
{
"dart.lineLength": 120
}
"dart.lineLength": 120,
"[dart]": {
"editor.rulers": [
120
],
}
}
1 change: 0 additions & 1 deletion analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
13 changes: 7 additions & 6 deletions bin/tools/migrator.dart
Original file line number Diff line number Diff line change
@@ -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<String> args) async {
initializeReflectable();
Query.addTypeDef<User>(userTypeData);
Query.addTypeDef<Article>(articleTypeData);

await OrmCLIRunner.start(args, orm.config);
}
2 changes: 1 addition & 1 deletion database/config.dart
Original file line number Diff line number Diff line change
@@ -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';
Expand Down
22 changes: 4 additions & 18 deletions database/migrations/create_articles_table.dart
Original file line number Diff line number Diff line change
@@ -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<Schema> schemas) {
final articleSchema = Schema.create('articles', (table) {
return table
..id()
..string('title')
..string('description')
..string('imageUrl', nullable: true)
..integer('ownerId')
..foreign<Article, User>(
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));
}
}
16 changes: 4 additions & 12 deletions database/migrations/create_users_table.dart
Original file line number Diff line number Diff line change
@@ -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));
}
}
9 changes: 5 additions & 4 deletions lib/app/middlewares/api_auth_middleware.dart
Original file line number Diff line number Diff line change
@@ -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);
Expand Down
2 changes: 0 additions & 2 deletions lib/app/providers/provide_blog_services.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import 'package:yaroo/http/http.dart';
class BlogServiceProvider extends ServiceProvider {
@override
void register() {
app.singleton<UserService>(UserService());

app.singleton<ArticleService>(ArticleService());
}
}
13 changes: 2 additions & 11 deletions lib/backend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
7 changes: 4 additions & 3 deletions lib/src/controllers/article_controller.dart
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -38,7 +39,7 @@ class ArticleController extends HTTPController {
}

Future<Response> delete(@param int articleId) async {
await _articleService.deleteArticle(user.id!, articleId);
await _articleService.deleteArticle(user.id, articleId);
return response.json({'message': 'Article deleted'});
}

Expand Down
25 changes: 14 additions & 11 deletions lib/src/controllers/auth_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<Response> login(@body LoginUserDTO data) async {
final user = await DB.query<User>().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);
Expand All @@ -28,13 +28,16 @@ class AuthController extends HTTPController {
}

Future<Response> register(@body CreateUserDTO data) async {
final existing = await DB.query<User>().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));
}
Expand Down
13 changes: 5 additions & 8 deletions lib/src/controllers/user_controller.dart
Original file line number Diff line number Diff line change
@@ -1,26 +1,23 @@
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<Response> currentUser() async {
final user = request.auth as User;
return jsonResponse({'user': user.toJson()});
}

Future<Response> index() async {
final result = await DB.query<User>().all();
final result = await UserQuery.findMany();
return jsonResponse(result);
}

Future<Response> 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()});
}
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
24 changes: 0 additions & 24 deletions lib/src/models/article.dart

This file was deleted.

57 changes: 57 additions & 0 deletions lib/src/models/article/article.dart
Original file line number Diff line number Diff line change
@@ -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<Article> {
@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<Article, User> get owner => belongsTo<User>();

Map<String, dynamic> toJson() => <String, dynamic>{
'id': id,
'createdAt': createdAt.toIso8601String(),
'updatedAt': updatedAt.toIso8601String(),
'title': title,
'description': description,
'imageUrl': imageUrl,
'ownerId': ownerId,
};

factory Article.fromJson(Map<String, dynamic> 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),
);
}
2 changes: 0 additions & 2 deletions lib/src/models/models.dart

This file was deleted.

21 changes: 0 additions & 21 deletions lib/src/models/user.dart

This file was deleted.

Loading

0 comments on commit 2bfe61b

Please sign in to comment.