refactor user repo with helpers. better api validation etc.
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
extension Let<T> on T? {
|
||||
R? let<R>(R Function(T it) action) {
|
||||
if (this != null) {
|
||||
return action(this!);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:core';
|
||||
|
||||
import 'package:backend_dart/domain/errors/app_error.dart';
|
||||
import 'package:backend_dart/domain/interface/error.dart';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:shelf/shelf.dart';
|
||||
|
||||
TaskEither<IError, Map<String, dynamic>> requestToJson(Request request) {
|
||||
return TaskEither.tryCatch(
|
||||
() async {
|
||||
final body = await request.readAsString();
|
||||
return jsonDecode(body);
|
||||
},
|
||||
(error, stack) => AppError.inputError(
|
||||
message: 'Failed to decode JSON: ${error.toString()}',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
TaskEither<IError, T> decodeJson<T>(
|
||||
Map<String, dynamic> json, T Function(Map<String, dynamic>) fromJson) {
|
||||
return TaskEither.tryCatch(
|
||||
() async {
|
||||
return fromJson(json);
|
||||
},
|
||||
(error, stack) => AppError.inputError(
|
||||
message: 'Failed to decode JSON: ${error.toString()}',
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
String generateSecureHash(String input) {
|
||||
final bytes = utf8.encode(input);
|
||||
final hash = sha256.convert(bytes);
|
||||
print(hash);
|
||||
return hash.toString();
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import 'package:backend_dart/domain/errors/app_error.dart';
|
||||
import 'package:backend_dart/domain/interface/error.dart';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
TaskEither<IError, Map<String, dynamic>> validateJsonKeys(
|
||||
Map<String, dynamic> json, List<String> requiredKeys) {
|
||||
return TaskEither.tryCatch(
|
||||
() async {
|
||||
final missingKeys =
|
||||
requiredKeys.where((key) => !json.containsKey(key)).toList();
|
||||
|
||||
if (missingKeys.isNotEmpty) {
|
||||
throw Exception('Missing required keys: ${missingKeys.join(', ')}');
|
||||
}
|
||||
|
||||
return json;
|
||||
},
|
||||
(error, _) => AppError.validationError(
|
||||
message: 'Failed to validate JSON keys: ${error.toString()}',
|
||||
),
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user