platform/lib/server.dart

65 lines
1.7 KiB
Dart
Raw Normal View History

2016-12-25 21:26:55 +00:00
/// Support for using `angel_validate` with the Angel Framework.
library angel_validate.server;
import 'package:angel_framework/angel_framework.dart';
import 'angel_validate.dart';
export 'angel_validate.dart';
/// Validates the data in `req.body`, and sets the body to
/// filtered data before continuing the response.
2016-12-25 22:46:08 +00:00
RequestMiddleware validate(Validator validator,
{String errorMessage: 'Invalid data.'}) {
return (RequestContext req, res) async {
var result = validator.check(req.body);
2016-12-25 21:26:55 +00:00
2016-12-25 22:46:08 +00:00
if (result.errors.isNotEmpty) {
throw new AngelHttpException.BadRequest(
message: errorMessage, errors: result.errors);
}
req.body
..clear()
..addAll(result.data);
return true;
};
2016-12-25 21:26:55 +00:00
}
2016-12-25 22:46:08 +00:00
/// Validates the data in `req.query`, and sets the query to
2016-12-25 21:26:55 +00:00
/// filtered data before continuing the response.
2016-12-25 22:46:08 +00:00
RequestMiddleware validateQuery(Validator validator,
{String errorMessage: 'Invalid data.'}) {
return (RequestContext req, res) async {
var result = validator.check(req.query);
if (result.errors.isNotEmpty) {
throw new AngelHttpException.BadRequest(
message: errorMessage, errors: result.errors);
}
2016-12-25 21:26:55 +00:00
2016-12-25 22:46:08 +00:00
req.query
..clear()
..addAll(result.data);
return true;
};
2016-12-25 21:26:55 +00:00
}
/// Validates the data in `e.data`, and sets the data to
/// filtered data before continuing the service event.
2016-12-25 22:46:08 +00:00
HookedServiceEventListener validateEvent(Validator validator,
{String errorMessage: 'Invalid data.'}) {
return (HookedServiceEvent e) {
var result = validator.check(e.data);
2016-12-25 21:26:55 +00:00
2016-12-25 22:46:08 +00:00
if (result.errors.isNotEmpty) {
throw new AngelHttpException.BadRequest(
message: errorMessage, errors: result.errors);
}
2016-12-25 21:26:55 +00:00
2016-12-25 22:46:08 +00:00
e.data
..clear()
..addAll(result.data);
};
}