Skip to content

Commit

Permalink
Merge branch 'javad-zobeidi-dev' into dev
Browse files Browse the repository at this point in the history
  • Loading branch information
javad-zobeidi committed Jun 28, 2024
2 parents 2cd6945 + 34f48c4 commit 8387e70
Show file tree
Hide file tree
Showing 13 changed files with 177 additions and 27 deletions.
2 changes: 1 addition & 1 deletion lib/src/cache/file_cache_driver.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class FileCacheDriver implements CacheDriver {

@override
Future<bool> has(String key) async {
dynamic data = get(key);
dynamic data = await get(key);

if (data == null) {
return Future.value(false);
Expand Down
1 change: 0 additions & 1 deletion lib/src/database/database_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ class DatabaseClient {
database = await MysqlDriver().init();
database?.connection.reconnectIfMissingConnection();
break;
case 'postgressql':
case 'postgresql':
case 'pgsql':
database = await PostgreSQLDriver().init();
Expand Down
7 changes: 7 additions & 0 deletions lib/src/database/migration.dart
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,12 @@ class Migration {
Future<void> dropIfExists(String name) async {
try {
String query = 'DROP TABLE IF EXISTS `$name`;';

if (MigrationConnection().database?.driver == 'Postgresql') {
query = _mysqlToPosgresqlMapper(query.toString());
} else {
query =
'SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;${query}SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;';
}

await MigrationConnection().dbConnection?.execute(query.toString());
Expand All @@ -199,6 +203,9 @@ class Migration {

if (MigrationConnection().database?.driver == 'Postgresql') {
query = _mysqlToPosgresqlMapper(query.toString());
} else {
query =
'SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;${query}SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;';
}

await MigrationConnection().dbConnection?.execute(query.toString());
Expand Down
7 changes: 7 additions & 0 deletions lib/src/database/model.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:io';

import 'package:eloquent/eloquent.dart';
import 'package:vania/vania.dart';

Expand Down Expand Up @@ -25,6 +27,11 @@ class Model {
Logger.log(e.cause.toString(), type: Logger.ERROR);
abort(500, e.cause.toString());
rethrow;
} on QueryException catch (e) {
throw HttpResponseException(
message: e.sql,
code: HttpStatus.internalServerError,
);
}
}
}
28 changes: 28 additions & 0 deletions lib/src/extensions/database_helper.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import 'dart:io';

import 'package:eloquent/eloquent.dart';
import 'package:vania/src/exception/http_exception.dart';

extension DatabaseHelper on QueryBuilder {
// Create and return inserted data
Future<Map<String, dynamic>> create(Map<String, dynamic> data) async {
final insertId = await insertGetId(data);
final record = await where('id', '=', insertId).first();
return record ?? {};
}

// Insert many data in the table
Future<bool> insertMany(List<Map<String, dynamic>> data) async {
for (Map<String, dynamic> row in data) {
try {
await insert(row);
} on QueryException catch (e) {
throw HttpResponseException(
message: e.sql,
code: HttpStatus.internalServerError,
);
}
}
return true;
}
}
20 changes: 15 additions & 5 deletions lib/src/http/request/request.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,9 @@ class Request {

Map<String, dynamic> get _query => uri.queryParameters;

Map<String, dynamic> body = <String, dynamic>{};
List<Cookie> get cookies => request.cookies;

bool isMethod(String method) {
return route?.method.toLowerCase() == method.toLowerCase();
}
Map<String, dynamic> body = <String, dynamic>{};

Future<Request> extractBody() async {
final whereMethod = ['post', 'patch', 'put']
Expand All @@ -59,6 +57,10 @@ class Request {
return vParams;
}

bool isMethod(String method) {
return route?.method.toLowerCase() == method.toLowerCase();
}

Map<String, dynamic> only(List<String> keys) {
Map<String, dynamic> ret = <String, dynamic>{};
for (String key in keys) {
Expand Down Expand Up @@ -129,7 +131,7 @@ class Request {
}

if (_all[key] != null) {
return _all[key];
return int.tryParse(_all[key].toString()) ?? _all[key];
}

if (defaultVal != null) {
Expand Down Expand Up @@ -168,6 +170,14 @@ class Request {
return _all[key].toString();
}

int? integer(String key) {
return int.tryParse(_all[key].toString());
}

double? asDouble(String key) {
return double.tryParse(_all[key].toString());
}

bool boolean(String key) {
try {
return bool.parse(_all[key].toString());
Expand Down
10 changes: 8 additions & 2 deletions lib/src/http/request/request_body.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ import 'dart:io';

import 'package:vania/src/http/request/request_form_data.dart';

String _fixJsonString(String jsonString) {
return jsonString.replaceAllMapped(RegExp(r'("\w+": )(\d+)([\s,}])'),
(Match match) => '${match[1]}"${match[2]}"${match[3]}');
}

class RequestBody {
const RequestBody();

Expand All @@ -11,7 +16,7 @@ class RequestBody {
if (isJson(request.headers.contentType)) {
String bodyString = await utf8.decoder.bind(request).join();
try {
return jsonDecode(bodyString);
return jsonDecode(_fixJsonString(bodyString));
} catch (err) {
return <String, dynamic>{};
}
Expand Down Expand Up @@ -41,7 +46,8 @@ class RequestBody {
for (String pair in keyValuePairs) {
List<String> keyValue = pair.split('=');
if (keyValue.length == 2) {
resultMap[keyValue[0]] = keyValue[1];
resultMap[keyValue[0]] =
int.tryParse(keyValue[1].toString()) ?? keyValue[1];
}
}

Expand Down
5 changes: 3 additions & 2 deletions lib/src/http/request/request_form_data.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ class RequestFormData {

if (inputName != null) {
if (data['filename'] == null || data['filename']!.isEmpty) {
String value = String.fromCharCodes(await formItem.first);
inputs[inputName] = value;
var value = String.fromCharCodes(await formItem.first);
inputs[inputName] =
int.tryParse(value.toString()) ?? value.toString();
} else {
RequestFile file = RequestFile(
filename: data['filename'].toString(),
Expand Down
76 changes: 61 additions & 15 deletions lib/src/http/response/response.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:meta/meta.dart';
import 'package:vania/src/http/response/stream_file.dart';

enum ResponseType {
Expand All @@ -12,17 +13,29 @@ enum ResponseType {
}

class Response {
@protected
final ResponseType responseType;
@protected
final dynamic data;
@protected
final int httpStatusCode;
const Response([
@protected
final Map<String, String> headers;

Response({
this.data,
this.responseType = ResponseType.none,
this.httpStatusCode = HttpStatus.ok,
]);
this.headers = const {},
});

void makeResponse(HttpResponse res) async {
res.statusCode = httpStatusCode;
if (headers.isNotEmpty) {
headers.forEach((key, value) {
res.headers.add(key, value);
});
}
switch (responseType) {
case ResponseType.json:
res.headers.contentType = ContentType.json;
Expand Down Expand Up @@ -75,30 +88,63 @@ class Response {
}
}

static json(dynamic jsonData, [int statusCode = HttpStatus.ok]) => Response(
jsonData,
ResponseType.json,
statusCode,
static json(
dynamic jsonData, [
int statusCode = HttpStatus.ok,
]) =>
Response(
data: jsonData,
responseType: ResponseType.json,
httpStatusCode: statusCode,
);

static jsonWithHeader(
dynamic jsonData, {
int statusCode = HttpStatus.ok,
Map<String, String> headers = const {},
}) =>
Response(
data: jsonData,
responseType: ResponseType.json,
httpStatusCode: statusCode,
headers: headers,
);

static html(dynamic htmlData) => Response(
htmlData,
ResponseType.html,
static html(
dynamic htmlData, {
Map<String, String> headers = const {},
}) =>
Response(
data: htmlData,
responseType: ResponseType.html,
headers: headers,
);

static file(String fileName, Uint8List bytes) => Response(
{
static file(
String fileName,
Uint8List bytes, {
Map<String, String> headers = const {},
}) =>
Response(
data: {
"fileName": fileName,
"bytes": bytes,
},
ResponseType.streamFile,
responseType: ResponseType.streamFile,
headers: headers,
);

static download(String fileName, Uint8List bytes) => Response(
{
static download(
String fileName,
Uint8List bytes, {
Map<String, String> headers = const {},
}) =>
Response(
data: {
"fileName": fileName,
"bytes": bytes,
},
ResponseType.download,
responseType: ResponseType.download,
headers: headers,
);
}
21 changes: 20 additions & 1 deletion lib/src/utils/helper.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import 'package:eloquent/eloquent.dart';
import 'dart:io';
import 'package:vania/vania.dart';

String storagePath(String file) => 'storage/$file';
Expand All @@ -15,4 +15,23 @@ abort(int code, String message) {
throw HttpResponseException(message: message, code: code);
}

// Databse Helper
Connection? get connection => DatabaseClient().database?.connection;

// DB Transaction
void dbTransaction(
Future<void> Function(Connection connection) callback, [
int? timeoutInSeconds,
]) {
connection?.transaction(
(con) async {
callback(con);
},
timeoutInSeconds,
).onError((e, _) {
throw HttpResponseException(
message: "DbTransaction error: ${e.toString()}",
code: HttpStatus.internalServerError,
);
});
}
2 changes: 2 additions & 0 deletions lib/vania.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ export 'src/database/seeder/seeder.dart';
export 'src/enum/column_index.dart';
export 'src/extensions/pagination_extension.dart';
export 'src/extensions/simple_paginate_extension.dart';
export 'src/extensions/database_helper.dart';
export 'package:eloquent/src/query/query_builder.dart';
export 'package:eloquent/eloquent.dart' show QueryException, Connection;

export 'src/authentication/authentication.dart';
export 'src/authentication/authenticate.dart';
Expand Down
1 change: 1 addition & 0 deletions test/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
APP_KEY='kQ1spu2E1r452fLa7cSihi7p1pdBR7040H8-UxtXNXg8='
24 changes: 24 additions & 0 deletions test/unit/hash_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import 'dart:io';

import 'package:test/test.dart';
import 'package:vania/vania.dart';

void main() {
group('Hash class test', () {
setUp(() {
Env().load(file: File('test/.env'));
});

test('Make/Verify correct paswword', () {
String password = "123456789";
String hash = Hash().make(password);
expect(Hash().verify(password, hash), true);
});

test('Make/Verify wrong password', () {
String password = "123456789";
String hash = Hash().make(password);
expect(Hash().verify("12345678", hash), false);
});
});
}

0 comments on commit 8387e70

Please sign in to comment.