platform/packages/shelf/lib/src/embed_shelf.dart

36 lines
1.3 KiB
Dart
Raw Normal View History

2017-06-12 23:53:08 +00:00
import 'package:angel_framework/angel_framework.dart';
import 'package:shelf/shelf.dart' as shelf;
import 'convert.dart';
/// Simply passes an incoming request to a `shelf` handler.
///
/// If the handler does not return a [shelf.Response], then the
/// result will be passed down the Angel middleware pipeline, like with
/// any other request handler.
///
/// If [throwOnNullResponse] is `true` (default: `false`), then a 500 error will be thrown
/// if the [handler] returns `null`.
RequestHandler embedShelf(shelf.Handler handler,
{String handlerPath,
Map<String, Object> context,
2019-10-14 15:28:50 +00:00
bool throwOnNullResponse = false}) {
2017-06-12 23:53:08 +00:00
return (RequestContext req, ResponseContext res) async {
2018-11-11 17:35:37 +00:00
var shelfRequest = await convertRequest(req, res,
handlerPath: handlerPath, context: context);
2017-06-12 23:53:08 +00:00
try {
var result = await handler(shelfRequest);
if (result is! shelf.Response && result != null) return result;
2019-10-14 15:28:50 +00:00
if (result == null && throwOnNullResponse == true) {
throw AngelHttpException('Internal Server Error');
}
2017-06-12 23:53:08 +00:00
await mergeShelfResponse(result, res);
return false;
} on shelf.HijackException {
2018-11-11 17:35:37 +00:00
// On hijack, do nothing, because the hijack handlers already call res.detach();
2019-10-14 15:28:50 +00:00
return null;
2017-06-12 23:53:08 +00:00
} catch (e) {
rethrow;
}
};
}