made use of first class citizen objects as json validator functions
This commit is contained in:
@@ -28,4 +28,4 @@ TaskEither<IError, T> decodeJson<T>(
|
||||
message: 'Failed to decode JSON: ${error.toString()}',
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,24 @@
|
||||
import 'dart:convert';
|
||||
import 'package:backend_dart/domain/errors/error_code.dart';
|
||||
import 'package:backend_dart/domain/interface/error.dart';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:shelf/shelf.dart';
|
||||
|
||||
extension TaskEitherResponseExtensions
|
||||
on TaskEither<IError, Map<String, dynamic>> {
|
||||
Task<Response> toResponse() => match(
|
||||
(left) => ResponseHelpers.fromError(left),
|
||||
(right) => ResponseHelpers.jsonOk(right),
|
||||
);
|
||||
}
|
||||
|
||||
extension TaskEitherResponseExtensionsFromString on TaskEither<IError, String> {
|
||||
Task<Response> toResponse() => match(
|
||||
(left) => ResponseHelpers.fromError(left),
|
||||
(right) => Response.ok(right),
|
||||
);
|
||||
}
|
||||
|
||||
class ResponseHelpers {
|
||||
/// Sendet eine JSON-Antwort mit einem 200-Statuscode
|
||||
static Response jsonOk(Map<String, dynamic> data) {
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
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();
|
||||
TaskEither<AppError, Map<String, dynamic>> Function(Map<String, dynamic>)
|
||||
validateJsonKeys(List<String> requiredKeys) {
|
||||
return (json) {
|
||||
final missingKeys =
|
||||
requiredKeys.where((key) => !json.containsKey(key)).toList();
|
||||
|
||||
if (missingKeys.isNotEmpty) {
|
||||
throw Exception('Missing required keys: ${missingKeys.join(', ')}');
|
||||
}
|
||||
if (missingKeys.isNotEmpty) {
|
||||
return TaskEither.left(AppError.validationError(
|
||||
message: 'Missing required keys: ${missingKeys.join(', ')}',
|
||||
));
|
||||
}
|
||||
|
||||
return json;
|
||||
},
|
||||
(error, _) => AppError.validationError(
|
||||
message: 'Failed to validate JSON keys: ${error.toString()}',
|
||||
),
|
||||
);
|
||||
return TaskEither.right(json);
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user