1.1.4
This commit is contained in:
parent
ef5a28b956
commit
954e8141dd
38 changed files with 1315 additions and 1388 deletions
|
@ -519,6 +519,7 @@
|
|||
<root url="file://$USER_HOME$/.pub-cache/hosted/pub.dartlang.org/yaml-2.1.13/lib" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<LIBRARY_FILE />
|
||||
<SOURCES />
|
||||
</library>
|
||||
</component>
|
|
@ -21,6 +21,7 @@
|
|||
<root url="file:///usr/local/opt/dart/libexec/lib/web_sql" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<LIBRARY_FILE />
|
||||
<SOURCES />
|
||||
</library>
|
||||
</component>
|
|
@ -0,0 +1,8 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Match routes, even with query params in routing_test.dart" type="DartTestRunConfigurationType" factoryName="Dart Test" singleton="true" nameIsGenerated="true">
|
||||
<option name="filePath" value="$PROJECT_DIR$/test/routing_test.dart" />
|
||||
<option name="scope" value="GROUP_OR_TEST_BY_NAME" />
|
||||
<option name="testName" value="Match routes, even with query params" />
|
||||
<method />
|
||||
</configuration>
|
||||
</component>
|
|
@ -0,0 +1,9 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="can fetch data in services_test.dart" type="DartTestRunConfigurationType" factoryName="Dart Test" singleton="true" nameIsGenerated="true">
|
||||
<option name="filePath" value="$PROJECT_DIR$/test/services_test.dart" />
|
||||
<option name="scope" value="GROUP_OR_TEST_BY_NAME" />
|
||||
<option name="testName" value="can fetch data" />
|
||||
<option name="testRunnerOptions" value="-j 4" />
|
||||
<method />
|
||||
</configuration>
|
||||
</component>
|
1275
.idea/workspace.xml
1275
.idea/workspace.xml
File diff suppressed because it is too large
Load diff
|
@ -1,3 +1,8 @@
|
|||
# 1.1.4
|
||||
* Remove all usages of `async`/`await` in the core library.
|
||||
* `AngelConfigurer` now accepts `FutureOr`.
|
||||
* `AngelHttp` now has a `useZone` flag to disable custom zones.
|
||||
|
||||
# 1.1.3
|
||||
* `AngelHttp` now handles requests in a `Zone`.
|
||||
* Use `package:dart2_constant`.
|
||||
|
|
|
@ -1,2 +1,5 @@
|
|||
analyzer:
|
||||
strong-mode: true
|
||||
linter:
|
||||
rules:
|
||||
- avoid_slow_async_io
|
|
@ -1,5 +1,4 @@
|
|||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:isolate';
|
||||
import 'package:dart2_constant/convert.dart';
|
||||
import 'package:angel_framework/angel_framework.dart';
|
||||
|
@ -48,6 +47,6 @@ serverMain(_) async {
|
|||
print(e.stackTrace);
|
||||
};
|
||||
|
||||
var server = await http.startServer(InternetAddress.LOOPBACK_IP_V4, 3000);
|
||||
var server = await http.startServer('127.0.0.1', 3000);
|
||||
print('Listening at http://${server.address.address}:${server.port}');
|
||||
}
|
||||
|
|
|
@ -9,19 +9,19 @@ import 'angel_framework.dart';
|
|||
/// Sequentially runs a set of [listeners].
|
||||
HookedServiceEventListener chainListeners(
|
||||
Iterable<HookedServiceEventListener> listeners) {
|
||||
return (HookedServiceEvent e) async {
|
||||
for (HookedServiceEventListener listener in listeners) await listener(e);
|
||||
return (HookedServiceEvent e) {
|
||||
for (HookedServiceEventListener listener in listeners) listener(e);
|
||||
};
|
||||
}
|
||||
|
||||
/// Runs a [callback] on every service, and listens for future services to run it again.
|
||||
AngelConfigurer hookAllServices(callback(Service service)) {
|
||||
return (Angel app) async {
|
||||
return (Angel app) {
|
||||
List<Service> touched = [];
|
||||
|
||||
for (var service in app.services.values) {
|
||||
if (!touched.contains(service)) {
|
||||
await callback(service);
|
||||
callback(service);
|
||||
touched.add(service);
|
||||
}
|
||||
}
|
||||
|
@ -52,9 +52,9 @@ HookedServiceEventListener transform(transformer(obj), [condition]) {
|
|||
Iterable cond = condition is Iterable ? condition : [condition];
|
||||
if (condition == null) cond = [];
|
||||
|
||||
_condition(HookedServiceEvent e, condition) async {
|
||||
_condition(HookedServiceEvent e, condition) {
|
||||
if (condition is Function)
|
||||
return await condition(e);
|
||||
return condition(e);
|
||||
else if (condition == Providers)
|
||||
return true;
|
||||
else {
|
||||
|
@ -70,11 +70,11 @@ HookedServiceEventListener transform(transformer(obj), [condition]) {
|
|||
}
|
||||
}
|
||||
|
||||
normalize(HookedServiceEvent e, obj) async {
|
||||
normalize(HookedServiceEvent e, obj) {
|
||||
bool transform = true;
|
||||
|
||||
for (var c in cond) {
|
||||
var r = await _condition(e, c);
|
||||
var r = _condition(e, c);
|
||||
|
||||
if (r != true) {
|
||||
transform = false;
|
||||
|
@ -97,7 +97,7 @@ HookedServiceEventListener transform(transformer(obj), [condition]) {
|
|||
var r = [];
|
||||
|
||||
for (var o in obj) {
|
||||
r.add(await normalize(e, o));
|
||||
r.add(normalize(e, o));
|
||||
}
|
||||
|
||||
return r;
|
||||
|
@ -105,10 +105,10 @@ HookedServiceEventListener transform(transformer(obj), [condition]) {
|
|||
return transformer(obj);
|
||||
}
|
||||
|
||||
return (HookedServiceEvent e) async {
|
||||
return (HookedServiceEvent e) {
|
||||
if (e.isBefore) {
|
||||
e.data = await normalize(e, e.data);
|
||||
} else if (e.isAfter) e.result = await normalize(e, e.result);
|
||||
e.data = normalize(e, e.data);
|
||||
} else if (e.isAfter) e.result = normalize(e, e.result);
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -135,7 +135,7 @@ HookedServiceEventListener toType(Type type) {
|
|||
/// Only applies to the client-side.
|
||||
HookedServiceEventListener remove(key, [remover(key, obj)]) {
|
||||
return (HookedServiceEvent e) async {
|
||||
_remover(key, obj) {
|
||||
_remover(key, obj) async {
|
||||
if (remover != null)
|
||||
return remover(key, obj);
|
||||
else if (obj is List)
|
||||
|
@ -171,15 +171,15 @@ HookedServiceEventListener remove(key, [remover(key, obj)]) {
|
|||
if (obj is Iterable) {
|
||||
return await Future.wait(obj.map(_removeAll));
|
||||
} else
|
||||
return await _removeAll(obj);
|
||||
return _removeAll(obj);
|
||||
}
|
||||
}
|
||||
|
||||
if (e.params?.containsKey('provider') == true) {
|
||||
if (e.isBefore) {
|
||||
e.data = await normalize(e.data);
|
||||
e.data = normalize(e.data);
|
||||
} else if (e.isAfter) {
|
||||
e.result = await normalize(e.result);
|
||||
e.result = normalize(e.result);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
@ -193,12 +193,12 @@ HookedServiceEventListener remove(key, [remover(key, obj)]) {
|
|||
///
|
||||
/// If [provider] is `null`, then it will be disabled to all clients.
|
||||
HookedServiceEventListener disable([provider]) {
|
||||
return (HookedServiceEvent e) async {
|
||||
return (HookedServiceEvent e) {
|
||||
if (e.params.containsKey('provider')) {
|
||||
if (provider == null)
|
||||
throw new AngelHttpException.methodNotAllowed();
|
||||
else if (provider is Function) {
|
||||
var r = await provider(e);
|
||||
var r = provider(e);
|
||||
if (r != true) throw new AngelHttpException.methodNotAllowed();
|
||||
} else {
|
||||
_provide(p) => p is Providers ? p : new Providers(p.toString());
|
||||
|
@ -224,7 +224,7 @@ HookedServiceEventListener addCreatedAt(
|
|||
{assign(obj, now), String key, bool serialize: true}) {
|
||||
var name = key?.isNotEmpty == true ? key : 'createdAt';
|
||||
|
||||
return (HookedServiceEvent e) async {
|
||||
return (HookedServiceEvent e) {
|
||||
_assign(obj, now) {
|
||||
if (assign != null)
|
||||
return assign(obj, now);
|
||||
|
@ -242,17 +242,17 @@ HookedServiceEventListener addCreatedAt(
|
|||
var d = new DateTime.now().toUtc();
|
||||
var now = serialize == false ? d : d.toIso8601String();
|
||||
|
||||
normalize(obj) async {
|
||||
normalize(obj) {
|
||||
if (obj != null) {
|
||||
if (obj is Iterable) {
|
||||
obj.forEach(normalize);
|
||||
} else {
|
||||
await _assign(obj, now);
|
||||
_assign(obj, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await normalize(e.isBefore ? e.data : e.result);
|
||||
normalize(e.isBefore ? e.data : e.result);
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -265,7 +265,7 @@ HookedServiceEventListener addUpdatedAt(
|
|||
{assign(obj, now), String key, bool serialize: true}) {
|
||||
var name = key?.isNotEmpty == true ? key : 'updatedAt';
|
||||
|
||||
return (HookedServiceEvent e) async {
|
||||
return (HookedServiceEvent e) {
|
||||
_assign(obj, now) {
|
||||
if (assign != null)
|
||||
return assign(obj, now);
|
||||
|
@ -283,16 +283,16 @@ HookedServiceEventListener addUpdatedAt(
|
|||
var d = new DateTime.now().toUtc();
|
||||
var now = serialize == false ? d : d.toIso8601String();
|
||||
|
||||
normalize(obj) async {
|
||||
normalize(obj) {
|
||||
if (obj != null) {
|
||||
if (obj is Iterable) {
|
||||
obj.forEach(normalize);
|
||||
} else {
|
||||
await _assign(obj, now);
|
||||
_assign(obj, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await normalize(e.isBefore ? e.data : e.result);
|
||||
normalize(e.isBefore ? e.data : e.result);
|
||||
};
|
||||
}
|
||||
|
|
|
@ -9,9 +9,8 @@ typedef Future<String> ViewGenerator(String path, [Map data]);
|
|||
|
||||
/// Base class for Angel servers. Do not bother extending this.
|
||||
class AngelBase extends Routable {
|
||||
static ViewGenerator noViewEngineConfigured = (String view,
|
||||
[Map data]) async =>
|
||||
"No view engine has been configured yet.";
|
||||
static ViewGenerator noViewEngineConfigured = (String view, [Map data]) =>
|
||||
new Future<String>.value("No view engine has been configured yet.");
|
||||
|
||||
Container _container = new Container();
|
||||
|
||||
|
@ -35,9 +34,10 @@ class AngelBase extends Routable {
|
|||
ViewGenerator viewGenerator = noViewEngineConfigured;
|
||||
|
||||
/// Closes this instance, rendering it **COMPLETELY DEFUNCT**.
|
||||
Future close() async {
|
||||
await super.close();
|
||||
Future close() {
|
||||
super.close();
|
||||
_container = null;
|
||||
viewGenerator = noViewEngineConfigured;
|
||||
return new Future.value();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -67,7 +67,7 @@ class HookedService extends Service {
|
|||
|
||||
/// Closes any open [StreamController]s on this instance. **Internal use only**.
|
||||
@override
|
||||
Future close() async {
|
||||
Future close() {
|
||||
_ctrl.forEach((c) => c.close());
|
||||
beforeIndexed._close();
|
||||
beforeRead._close();
|
||||
|
@ -81,7 +81,8 @@ class HookedService extends Service {
|
|||
afterModified._close();
|
||||
afterUpdated._close();
|
||||
afterRemoved._close();
|
||||
await inner.close();
|
||||
inner.close();
|
||||
return new Future.value();
|
||||
}
|
||||
|
||||
/// Adds hooks to this instance.
|
||||
|
@ -120,149 +121,16 @@ class HookedService extends Service {
|
|||
applyListeners(inner.remove, afterRemoved, true);
|
||||
}
|
||||
|
||||
/// Adds routes to this instance.
|
||||
@override
|
||||
void addRoutes() {
|
||||
// Set up our routes. We still need to copy middleware from inner service
|
||||
Map restProvider = {'provider': Providers.rest};
|
||||
|
||||
// Add global middleware if declared on the instance itself
|
||||
Middleware before = getAnnotation(inner, Middleware);
|
||||
List handlers = [
|
||||
(RequestContext req, ResponseContext res) async {
|
||||
List get bootstrappers => new List.from(super.bootstrappers)
|
||||
..add((RequestContext req, ResponseContext res) {
|
||||
req.serviceParams
|
||||
..['__requestctx'] = req
|
||||
..['__responsectx'] = res;
|
||||
return true;
|
||||
}
|
||||
];
|
||||
});
|
||||
|
||||
if (before != null) handlers.addAll(before.handlers);
|
||||
|
||||
Middleware indexMiddleware = getAnnotation(inner.index, Middleware);
|
||||
get('/', (req, res) async {
|
||||
return await this.index(mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
]));
|
||||
},
|
||||
middleware: []
|
||||
..addAll(handlers)
|
||||
..addAll((indexMiddleware == null) ? [] : indexMiddleware.handlers));
|
||||
|
||||
Middleware createMiddleware = getAnnotation(inner.create, Middleware);
|
||||
|
||||
post('/', (req, res) async {
|
||||
var r = await this.create(
|
||||
await req.lazyBody(),
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
]));
|
||||
res.statusCode = 201;
|
||||
return r;
|
||||
},
|
||||
middleware: []
|
||||
..addAll(handlers)
|
||||
..addAll(
|
||||
(createMiddleware == null) ? [] : createMiddleware.handlers));
|
||||
|
||||
Middleware readMiddleware = getAnnotation(inner.read, Middleware);
|
||||
|
||||
get(
|
||||
'/:id',
|
||||
(req, res) async => await this.read(
|
||||
toId(req.params['id']),
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
])),
|
||||
middleware: []
|
||||
..addAll(handlers)
|
||||
..addAll((readMiddleware == null) ? [] : readMiddleware.handlers));
|
||||
|
||||
Middleware modifyMiddleware = getAnnotation(inner.modify, Middleware);
|
||||
patch(
|
||||
'/:id',
|
||||
(req, res) async => await this.modify(
|
||||
toId(req.params['id']),
|
||||
await req.lazyBody(),
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
])),
|
||||
middleware: []
|
||||
..addAll(handlers)
|
||||
..addAll(
|
||||
(modifyMiddleware == null) ? [] : modifyMiddleware.handlers));
|
||||
|
||||
Middleware updateMiddleware = getAnnotation(inner.update, Middleware);
|
||||
post(
|
||||
'/:id',
|
||||
(req, res) async => await this.update(
|
||||
toId(req.params['id']),
|
||||
await req.lazyBody(),
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
])),
|
||||
middleware: []
|
||||
..addAll(handlers)
|
||||
..addAll(
|
||||
(updateMiddleware == null) ? [] : updateMiddleware.handlers));
|
||||
put(
|
||||
'/:id',
|
||||
(req, res) async => await this.update(
|
||||
toId(req.params['id']),
|
||||
await req.lazyBody(),
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
])),
|
||||
middleware: []
|
||||
..addAll(handlers)
|
||||
..addAll(
|
||||
(updateMiddleware == null) ? [] : updateMiddleware.handlers));
|
||||
|
||||
Middleware removeMiddleware = getAnnotation(inner.remove, Middleware);
|
||||
delete(
|
||||
'/',
|
||||
(req, res) async => await this.remove(
|
||||
null,
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
])),
|
||||
middleware: []
|
||||
..addAll(handlers)
|
||||
..addAll(
|
||||
(removeMiddleware == null) ? [] : removeMiddleware.handlers));
|
||||
delete(
|
||||
'/:id',
|
||||
(req, res) async => await this.remove(
|
||||
toId(req.params['id']),
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
])),
|
||||
middleware: []
|
||||
..addAll(handlers)
|
||||
..addAll(
|
||||
(removeMiddleware == null) ? [] : removeMiddleware.handlers));
|
||||
|
||||
// REST compliance
|
||||
put('/', () => throw new AngelHttpException.notFound());
|
||||
patch('/', () => throw new AngelHttpException.notFound());
|
||||
|
||||
addHooks();
|
||||
void addRoutes([Service s]) {
|
||||
super.addRoutes(s ?? inner);
|
||||
}
|
||||
|
||||
/// Runs the [listener] before every service method specified.
|
||||
|
@ -388,192 +256,165 @@ class HookedService extends Service {
|
|||
}
|
||||
|
||||
@override
|
||||
Future index([Map _params]) async {
|
||||
Future index([Map _params]) {
|
||||
var params = _stripReq(_params);
|
||||
HookedServiceEvent before = await beforeIndexed._emit(
|
||||
new HookedServiceEvent(false, _getRequest(_params),
|
||||
return beforeIndexed
|
||||
._emit(new HookedServiceEvent(false, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.indexed,
|
||||
params: params));
|
||||
params: params))
|
||||
.then((before) {
|
||||
if (before._canceled) {
|
||||
HookedServiceEvent after = await beforeIndexed._emit(
|
||||
new HookedServiceEvent(true, _getRequest(_params),
|
||||
return beforeIndexed
|
||||
._emit(new HookedServiceEvent(true, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.indexed,
|
||||
params: params, result: before.result));
|
||||
return after.result;
|
||||
params: params, result: before.result))
|
||||
.then((after) => after.result);
|
||||
}
|
||||
|
||||
var result = await inner.index(params);
|
||||
HookedServiceEvent after = await afterIndexed._emit(new HookedServiceEvent(
|
||||
true,
|
||||
_getRequest(_params),
|
||||
_getResponse(_params),
|
||||
inner,
|
||||
HookedServiceEvent.indexed,
|
||||
params: params,
|
||||
result: result));
|
||||
return after.result;
|
||||
return inner.index(params).then((result) {
|
||||
return afterIndexed
|
||||
._emit(new HookedServiceEvent(true, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.indexed,
|
||||
params: params, result: result))
|
||||
.then((after) => after.result);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future read(id, [Map _params]) async {
|
||||
Future read(id, [Map _params]) {
|
||||
var params = _stripReq(_params);
|
||||
HookedServiceEvent before = await beforeRead._emit(new HookedServiceEvent(
|
||||
false,
|
||||
_getRequest(_params),
|
||||
_getResponse(_params),
|
||||
inner,
|
||||
HookedServiceEvent.indexed,
|
||||
id: id,
|
||||
params: params));
|
||||
|
||||
return beforeRead
|
||||
._emit(new HookedServiceEvent(false, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.read,
|
||||
id: id, params: params))
|
||||
.then((before) {
|
||||
if (before._canceled) {
|
||||
HookedServiceEvent after = await afterRead._emit(new HookedServiceEvent(
|
||||
true,
|
||||
_getRequest(_params),
|
||||
_getResponse(_params),
|
||||
inner,
|
||||
HookedServiceEvent.read,
|
||||
id: id,
|
||||
params: params,
|
||||
result: before.result));
|
||||
return after.result;
|
||||
return beforeRead
|
||||
._emit(new HookedServiceEvent(true, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.read,
|
||||
id: id, params: params, result: before.result))
|
||||
.then((after) => after.result);
|
||||
}
|
||||
|
||||
var result = await inner.read(id, params);
|
||||
HookedServiceEvent after = await afterRead._emit(new HookedServiceEvent(
|
||||
true,
|
||||
_getRequest(_params),
|
||||
_getResponse(_params),
|
||||
inner,
|
||||
HookedServiceEvent.read,
|
||||
id: id,
|
||||
params: params,
|
||||
result: result));
|
||||
return after.result;
|
||||
return inner.read(id, params).then((result) {
|
||||
return afterRead
|
||||
._emit(new HookedServiceEvent(true, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.read,
|
||||
id: id, params: params, result: result))
|
||||
.then((after) => after.result);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future create(data, [Map _params]) async {
|
||||
Future create(data, [Map _params]) {
|
||||
var params = _stripReq(_params);
|
||||
HookedServiceEvent before = await beforeCreated._emit(
|
||||
new HookedServiceEvent(false, _getRequest(_params),
|
||||
return beforeCreated
|
||||
._emit(new HookedServiceEvent(false, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.created,
|
||||
data: data, params: params));
|
||||
|
||||
data: data, params: params))
|
||||
.then((before) {
|
||||
if (before._canceled) {
|
||||
HookedServiceEvent after = await afterCreated._emit(
|
||||
new HookedServiceEvent(true, _getRequest(_params),
|
||||
return beforeCreated
|
||||
._emit(new HookedServiceEvent(true, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.created,
|
||||
data: data, params: params, result: before.result));
|
||||
return after.result;
|
||||
data: data, params: params, result: before.result))
|
||||
.then((after) => after.result);
|
||||
}
|
||||
|
||||
var result = await inner.create(data, params);
|
||||
HookedServiceEvent after = await afterCreated._emit(new HookedServiceEvent(
|
||||
true,
|
||||
_getRequest(_params),
|
||||
_getResponse(_params),
|
||||
inner,
|
||||
HookedServiceEvent.created,
|
||||
data: data,
|
||||
params: params,
|
||||
result: result));
|
||||
return after.result;
|
||||
return inner.create(data, params).then((result) {
|
||||
return afterCreated
|
||||
._emit(new HookedServiceEvent(true, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.created,
|
||||
data: data, params: params, result: result))
|
||||
.then((after) => after.result);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future modify(id, data, [Map _params]) async {
|
||||
Future modify(id, data, [Map _params]) {
|
||||
var params = _stripReq(_params);
|
||||
HookedServiceEvent before = await beforeModified._emit(
|
||||
new HookedServiceEvent(false, _getRequest(_params),
|
||||
return beforeModified
|
||||
._emit(new HookedServiceEvent(false, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.modified,
|
||||
id: id, data: data, params: params));
|
||||
|
||||
id: id, data: data, params: params))
|
||||
.then((before) {
|
||||
if (before._canceled) {
|
||||
HookedServiceEvent after = await afterModified._emit(
|
||||
new HookedServiceEvent(true, _getRequest(_params),
|
||||
return beforeModified
|
||||
._emit(new HookedServiceEvent(true, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.modified,
|
||||
id: id, data: data, params: params, result: before.result));
|
||||
return after.result;
|
||||
id: id, data: data, params: params, result: before.result))
|
||||
.then((after) => after.result);
|
||||
}
|
||||
|
||||
var result = await inner.modify(id, data, params);
|
||||
HookedServiceEvent after = await afterModified._emit(new HookedServiceEvent(
|
||||
true,
|
||||
_getRequest(_params),
|
||||
_getResponse(_params),
|
||||
inner,
|
||||
HookedServiceEvent.modified,
|
||||
id: id,
|
||||
data: data,
|
||||
params: params,
|
||||
result: result));
|
||||
return after.result;
|
||||
return inner.modify(id, data, params).then((result) {
|
||||
return afterModified
|
||||
._emit(new HookedServiceEvent(true, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.created,
|
||||
id: id, data: data, params: params, result: result))
|
||||
.then((after) => after.result);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future update(id, data, [Map _params]) async {
|
||||
Future update(id, data, [Map _params]) {
|
||||
var params = _stripReq(_params);
|
||||
HookedServiceEvent before = await beforeUpdated._emit(
|
||||
new HookedServiceEvent(false, _getRequest(_params),
|
||||
return beforeUpdated
|
||||
._emit(new HookedServiceEvent(false, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.updated,
|
||||
id: id, data: data, params: params));
|
||||
|
||||
id: id, data: data, params: params))
|
||||
.then((before) {
|
||||
if (before._canceled) {
|
||||
HookedServiceEvent after = await afterUpdated._emit(
|
||||
new HookedServiceEvent(true, _getRequest(_params),
|
||||
return beforeUpdated
|
||||
._emit(new HookedServiceEvent(true, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.updated,
|
||||
id: id, data: data, params: params, result: before.result));
|
||||
return after.result;
|
||||
id: id, data: data, params: params, result: before.result))
|
||||
.then((after) => after.result);
|
||||
}
|
||||
|
||||
var result = await inner.update(id, data, params);
|
||||
HookedServiceEvent after = await afterUpdated._emit(new HookedServiceEvent(
|
||||
true,
|
||||
_getRequest(_params),
|
||||
_getResponse(_params),
|
||||
inner,
|
||||
HookedServiceEvent.updated,
|
||||
id: id,
|
||||
data: data,
|
||||
params: params,
|
||||
result: result));
|
||||
return after.result;
|
||||
return inner.update(id, data, params).then((result) {
|
||||
return afterUpdated
|
||||
._emit(new HookedServiceEvent(true, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.updated,
|
||||
id: id, data: data, params: params, result: result))
|
||||
.then((after) => after.result);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future remove(id, [Map _params]) async {
|
||||
Future remove(id, [Map _params]) {
|
||||
var params = _stripReq(_params);
|
||||
HookedServiceEvent before = await beforeRemoved._emit(
|
||||
new HookedServiceEvent(false, _getRequest(_params),
|
||||
return beforeRemoved
|
||||
._emit(new HookedServiceEvent(false, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.removed,
|
||||
id: id, params: params));
|
||||
|
||||
id: id, params: params))
|
||||
.then((before) {
|
||||
if (before._canceled) {
|
||||
HookedServiceEvent after = await afterRemoved._emit(
|
||||
new HookedServiceEvent(true, _getRequest(_params),
|
||||
return beforeRemoved
|
||||
._emit(new HookedServiceEvent(true, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.removed,
|
||||
id: id, params: params, result: before.result));
|
||||
return after.result;
|
||||
id: id, params: params, result: before.result))
|
||||
.then((after) => after.result);
|
||||
}
|
||||
|
||||
var result = await inner.remove(id, params);
|
||||
HookedServiceEvent after = await afterRemoved._emit(new HookedServiceEvent(
|
||||
true,
|
||||
_getRequest(_params),
|
||||
_getResponse(_params),
|
||||
inner,
|
||||
HookedServiceEvent.removed,
|
||||
id: id,
|
||||
params: params,
|
||||
result: result));
|
||||
return after.result;
|
||||
return inner.remove(id, params).then((result) {
|
||||
return afterRemoved
|
||||
._emit(new HookedServiceEvent(true, _getRequest(_params),
|
||||
_getResponse(_params), inner, HookedServiceEvent.removed,
|
||||
id: id, params: params, result: result))
|
||||
.then((after) => after.result);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Fires an `after` event. This will not be propagated to clients,
|
||||
/// but will be broadcasted to WebSockets, etc.
|
||||
Future<HookedServiceEvent> fire(String eventName, result,
|
||||
[HookedServiceEventListener callback]) async {
|
||||
[HookedServiceEventListener callback]) {
|
||||
HookedServiceEventDispatcher dispatcher;
|
||||
|
||||
switch (eventName) {
|
||||
|
@ -600,15 +441,15 @@ class HookedService extends Service {
|
|||
}
|
||||
|
||||
var ev = new HookedServiceEvent(true, null, null, this, eventName);
|
||||
return await fireEvent(dispatcher, ev, callback);
|
||||
return fireEvent(dispatcher, ev, callback);
|
||||
}
|
||||
|
||||
/// Sends an arbitrary event down the hook chain.
|
||||
Future<HookedServiceEvent> fireEvent(
|
||||
HookedServiceEventDispatcher dispatcher, HookedServiceEvent event,
|
||||
[HookedServiceEventListener callback]) async {
|
||||
if (callback != null && event?._canceled != true) await callback(event);
|
||||
return await dispatcher._emit(event);
|
||||
[HookedServiceEventListener callback]) {
|
||||
if (callback != null && event?._canceled != true) callback(event);
|
||||
return dispatcher._emit(event);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -690,16 +531,16 @@ class HookedServiceEventDispatcher {
|
|||
}
|
||||
|
||||
/// Fires an event, and returns it once it is either canceled, or all listeners have run.
|
||||
Future<HookedServiceEvent> _emit(HookedServiceEvent event) async {
|
||||
Future<HookedServiceEvent> _emit(HookedServiceEvent event) {
|
||||
if (event?._canceled != true) {
|
||||
for (var listener in listeners) {
|
||||
await listener(event);
|
||||
listener(event);
|
||||
|
||||
if (event._canceled) return event;
|
||||
if (event._canceled) return new Future.value(event);
|
||||
}
|
||||
}
|
||||
|
||||
return event;
|
||||
return new Future.value(event);
|
||||
}
|
||||
|
||||
/// Returns a [Stream] containing all events fired by this dispatcher.
|
||||
|
|
|
@ -78,10 +78,11 @@ bool suitableForInjection(
|
|||
|
||||
/// Handles a request with a DI-enabled handler.
|
||||
RequestHandler handleContained(handler, InjectionRequest injection) {
|
||||
return (RequestContext req, ResponseContext res) async {
|
||||
return (RequestContext req, ResponseContext res) {
|
||||
if (injection.parameters.isNotEmpty &&
|
||||
injection.parameters.values.any((p) => p.match != null) &&
|
||||
!suitableForInjection(req, res, injection)) return true;
|
||||
!suitableForInjection(req, res, injection))
|
||||
return new Future.value(true);
|
||||
|
||||
List args = [];
|
||||
|
||||
|
@ -94,8 +95,7 @@ RequestHandler handleContained(handler, InjectionRequest injection) {
|
|||
named[name] = resolveInjection([k, v], injection, req, res, false);
|
||||
});
|
||||
|
||||
var result = Function.apply(handler, args, named);
|
||||
return result is Future ? await result : result;
|
||||
return Function.apply(handler, args, named);
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -181,6 +181,5 @@ InjectionRequest preInject(Function handler) {
|
|||
injection.named[name] = type;
|
||||
}
|
||||
}
|
||||
|
||||
return injection;
|
||||
}
|
||||
|
|
|
@ -45,13 +45,13 @@ class MapService extends Service {
|
|||
}
|
||||
|
||||
@override
|
||||
Future<List> index([Map params]) async {
|
||||
Future<List> index([Map params]) {
|
||||
if (allowQuery == false || params == null || params['query'] is! Map)
|
||||
return items;
|
||||
return new Future.value(items);
|
||||
else {
|
||||
Map query = params['query'];
|
||||
|
||||
return items.where((item) {
|
||||
return new Future.value(items.where((item) {
|
||||
for (var key in query.keys) {
|
||||
if (!item.containsKey(key))
|
||||
return false;
|
||||
|
@ -59,19 +59,19 @@ class MapService extends Service {
|
|||
}
|
||||
|
||||
return true;
|
||||
}).toList();
|
||||
}).toList());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map> read(id, [Map params]) async {
|
||||
return items.firstWhere(_matchesId(id),
|
||||
Future<Map> read(id, [Map params]) {
|
||||
return new Future.value(items.firstWhere(_matchesId(id),
|
||||
orElse: () => throw new AngelHttpException.notFound(
|
||||
message: 'No record found for ID $id'));
|
||||
message: 'No record found for ID $id')));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map> create(data, [Map params]) async {
|
||||
Future<Map> create(data, [Map params]) {
|
||||
if (data is! Map)
|
||||
throw new AngelHttpException.badRequest(
|
||||
message:
|
||||
|
@ -86,37 +86,37 @@ class MapService extends Service {
|
|||
..[autoSnakeCaseNames == false ? 'updatedAt' : 'updated_at'] = now;
|
||||
}
|
||||
items.add(result);
|
||||
return result;
|
||||
return new Future.value(result);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map> modify(id, data, [Map params]) async {
|
||||
Future<Map> modify(id, data, [Map params]) {
|
||||
if (data is! Map)
|
||||
throw new AngelHttpException.badRequest(
|
||||
message:
|
||||
'MapService does not support `modify` with ${data.runtimeType}.');
|
||||
if (!items.any(_matchesId(id))) return await create(data, params);
|
||||
if (!items.any(_matchesId(id))) return create(data, params);
|
||||
|
||||
var item = await read(id);
|
||||
return read(id).then((item) {
|
||||
var result = item..addAll(data);
|
||||
|
||||
if (autoIdAndDateFields == true)
|
||||
result
|
||||
..[autoSnakeCaseNames == false ? 'updatedAt' : 'updated_at'] =
|
||||
new DateTime.now().toIso8601String();
|
||||
return result;
|
||||
return new Future.value(result);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map> update(id, data, [Map params]) async {
|
||||
Future<Map> update(id, data, [Map params]) {
|
||||
if (data is! Map)
|
||||
throw new AngelHttpException.badRequest(
|
||||
message:
|
||||
'MapService does not support `update` with ${data.runtimeType}.');
|
||||
if (!items.any(_matchesId(id))) return await create(data, params);
|
||||
|
||||
var old = await read(id);
|
||||
if (!items.any(_matchesId(id))) return create(data, params);
|
||||
|
||||
return read(id).then((old) {
|
||||
if (!items.remove(old))
|
||||
throw new AngelHttpException.notFound(
|
||||
message: 'No record found for ID $id');
|
||||
|
@ -131,25 +131,26 @@ class MapService extends Service {
|
|||
new DateTime.now().toIso8601String();
|
||||
}
|
||||
items.add(result);
|
||||
return result;
|
||||
return new Future.value(result);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map> remove(id, [Map params]) async {
|
||||
Future<Map> remove(id, [Map params]) {
|
||||
if (id == null ||
|
||||
id == 'null' &&
|
||||
(allowRemoveAll == true ||
|
||||
params?.containsKey('provider') != true)) {
|
||||
items.clear();
|
||||
return {};
|
||||
return new Future.value({});
|
||||
}
|
||||
|
||||
var result = await read(id, params);
|
||||
|
||||
return read(id, params).then((result) {
|
||||
if (items.remove(result))
|
||||
return result;
|
||||
else
|
||||
throw new AngelHttpException.notFound(
|
||||
message: 'No record found for ID $id');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,6 +10,7 @@ import 'metadata.dart';
|
|||
import 'response_context.dart';
|
||||
import 'routable.dart';
|
||||
import 'server.dart' show Angel;
|
||||
|
||||
part 'injection.dart';
|
||||
|
||||
/// A convenience wrapper around an incoming HTTP request.
|
||||
|
@ -167,8 +168,8 @@ abstract class RequestContext {
|
|||
void inject(type, value) {
|
||||
if (!app.isProduction && type is Type) {
|
||||
if (!reflect(value).type.isAssignableTo(reflectType(type)))
|
||||
throw new ArgumentError(
|
||||
'Cannot inject $value (${value.runtimeType}) as an instance of $type.');
|
||||
throw new ArgumentError('Cannot inject $value (${value
|
||||
.runtimeType}) as an instance of $type.');
|
||||
}
|
||||
|
||||
_injections[type] = value;
|
||||
|
@ -230,12 +231,12 @@ abstract class RequestContext {
|
|||
}
|
||||
|
||||
/// Manually parses the request body, if it has not already been parsed.
|
||||
Future<BodyParseResult> parse() async {
|
||||
Future<BodyParseResult> parse() {
|
||||
if (_body != null)
|
||||
return _body;
|
||||
return new Future.value(_body);
|
||||
else
|
||||
_provisionalQuery = null;
|
||||
return _body = await parseOnce();
|
||||
return parseOnce().then((body) => _body = body);
|
||||
}
|
||||
|
||||
/// Override this method to one-time parse an incoming request.
|
||||
|
@ -243,7 +244,7 @@ abstract class RequestContext {
|
|||
Future<BodyParseResult> parseOnce();
|
||||
|
||||
/// Disposes of all resources.
|
||||
Future close() async {
|
||||
Future close() {
|
||||
_body = null;
|
||||
_acceptsAllCache = null;
|
||||
_acceptHeaderCache = null;
|
||||
|
@ -252,5 +253,6 @@ abstract class RequestContext {
|
|||
_injections.clear();
|
||||
serviceParams.clear();
|
||||
params.clear();
|
||||
return new Future.value();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -123,10 +123,11 @@ abstract class ResponseContext implements StreamSink<List<int>>, StringSink {
|
|||
/// If `true`, all response finalizers will be skipped.
|
||||
bool willCloseItself = false;
|
||||
|
||||
static StateError closed() => new StateError('Cannot modify a closed response.');
|
||||
static StateError closed() =>
|
||||
new StateError('Cannot modify a closed response.');
|
||||
|
||||
/// Sends a download as a response.
|
||||
Future download(File file, {String filename}) async {
|
||||
void download(File file, {String filename}) {
|
||||
if (!isOpen) throw closed();
|
||||
|
||||
headers["Content-Disposition"] =
|
||||
|
@ -135,9 +136,9 @@ abstract class ResponseContext implements StreamSink<List<int>>, StringSink {
|
|||
headers['content-length'] = file.lengthSync().toString();
|
||||
|
||||
if (streaming) {
|
||||
await file.openRead().pipe(this);
|
||||
file.openRead().pipe(this);
|
||||
} else {
|
||||
buffer.add(await file.readAsBytes());
|
||||
buffer.add(file.readAsBytesSync());
|
||||
end();
|
||||
}
|
||||
}
|
||||
|
@ -157,8 +158,8 @@ abstract class ResponseContext implements StreamSink<List<int>>, StringSink {
|
|||
}
|
||||
|
||||
/// Disposes of all resources.
|
||||
Future dispose() async {
|
||||
await close();
|
||||
void dispose() {
|
||||
close();
|
||||
properties.clear();
|
||||
encoders.clear();
|
||||
_buffer.clear();
|
||||
|
@ -197,11 +198,12 @@ abstract class ResponseContext implements StreamSink<List<int>>, StringSink {
|
|||
}
|
||||
|
||||
/// Renders a view to the response stream, and closes the response.
|
||||
Future render(String view, [Map data]) async {
|
||||
Future render(String view, [Map data]) {
|
||||
if (!isOpen) throw closed();
|
||||
write(await app.viewGenerator(view, data));
|
||||
write(app.viewGenerator(view, data));
|
||||
headers['content-type'] = ContentType.HTML.toString();
|
||||
end();
|
||||
return new Future.value();
|
||||
}
|
||||
|
||||
/// Redirects to user to the given URL.
|
||||
|
@ -293,11 +295,11 @@ abstract class ResponseContext implements StreamSink<List<int>>, StringSink {
|
|||
}
|
||||
|
||||
/// Copies a file's contents into the response buffer.
|
||||
Future sendFile(File file) async {
|
||||
void sendFile(File file) {
|
||||
if (!isOpen) throw closed();
|
||||
|
||||
headers['content-type'] = lookupMimeType(file.path);
|
||||
buffer.add(await file.readAsBytes());
|
||||
buffer.add(file.readAsBytesSync());
|
||||
end();
|
||||
}
|
||||
|
||||
|
@ -309,8 +311,7 @@ abstract class ResponseContext implements StreamSink<List<int>>, StringSink {
|
|||
|
||||
var text = serializer(value);
|
||||
|
||||
if (text.isEmpty)
|
||||
return;
|
||||
if (text.isEmpty) return;
|
||||
|
||||
if (contentType is String)
|
||||
headers['content-type'] = contentType;
|
||||
|
@ -337,10 +338,8 @@ abstract class ResponseContext implements StreamSink<List<int>>, StringSink {
|
|||
(correspondingRequest.injections[Stopwatch] as Stopwatch).stop();
|
||||
}
|
||||
|
||||
if (correspondingRequest?.injections?.containsKey(PoolResource) ==
|
||||
true) {
|
||||
(correspondingRequest.injections[PoolResource] as PoolResource)
|
||||
.release();
|
||||
if (correspondingRequest?.injections?.containsKey(PoolResource) == true) {
|
||||
(correspondingRequest.injections[PoolResource] as PoolResource).release();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -2,7 +2,6 @@ library angel_framework.http.routable;
|
|||
|
||||
import 'dart:async';
|
||||
import 'package:angel_route/angel_route.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
import '../util.dart';
|
||||
import 'angel_base.dart';
|
||||
import 'hooked_service.dart';
|
||||
|
@ -22,13 +21,23 @@ typedef Future RequestHandler(RequestContext req, ResponseContext res);
|
|||
/// Sequentially runs a list of [handlers] of middleware, and returns early if any does not
|
||||
/// return `true`. Works well with [Router].chain.
|
||||
RequestMiddleware waterfall(List handlers) {
|
||||
return (RequestContext req, res) async {
|
||||
return (req, res) {
|
||||
Future<bool> Function() runPipeline;
|
||||
|
||||
for (var handler in handlers) {
|
||||
var result = await req.app.executeHandler(handler, req, res);
|
||||
if (result != true) return result;
|
||||
if (handler == null) break;
|
||||
|
||||
if (runPipeline == null)
|
||||
runPipeline = () => req.app.executeHandler(handler, req, res);
|
||||
else {
|
||||
var current = runPipeline;
|
||||
runPipeline = () => current().then((result) =>
|
||||
!result ? result : req.app.executeHandler(handler, req, res));
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
runPipeline ??= () => new Future.value(true);
|
||||
return runPipeline();
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -39,7 +48,7 @@ class Routable extends Router {
|
|||
|
||||
Routable() : super();
|
||||
|
||||
Future close() async {
|
||||
void close() {
|
||||
_services.clear();
|
||||
configuration.clear();
|
||||
requestMiddleware.clear();
|
||||
|
@ -63,9 +72,11 @@ class Routable extends Router {
|
|||
|
||||
/// Assigns a middleware to a name for convenience.
|
||||
@override
|
||||
registerMiddleware(String name, @checked RequestHandler middleware) =>
|
||||
registerMiddleware(String name, middleware) {
|
||||
assert(middleware is RequestMiddleware);
|
||||
// ignore: deprecated_member_use
|
||||
super.registerMiddleware(name, middleware);
|
||||
}
|
||||
|
||||
/// Retrieves the service assigned to the given path.
|
||||
Service service(Pattern path) =>
|
||||
|
@ -116,7 +127,7 @@ class Routable extends Router {
|
|||
final handlers = [];
|
||||
|
||||
if (_router is AngelBase) {
|
||||
handlers.add((RequestContext req, ResponseContext res) async {
|
||||
handlers.add((RequestContext req, ResponseContext res) {
|
||||
req.app = _router;
|
||||
res.app = _router;
|
||||
return true;
|
||||
|
|
|
@ -9,7 +9,6 @@ import 'package:angel_route/angel_route.dart';
|
|||
import 'package:combinator/combinator.dart';
|
||||
export 'package:container/container.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:tuple/tuple.dart';
|
||||
import '../http/http.dart';
|
||||
import 'angel_base.dart';
|
||||
|
@ -27,7 +26,7 @@ final RegExp _straySlashes = new RegExp(r'(^/+)|(/+$)');
|
|||
typedef Future<HttpServer> ServerGenerator(address, int port);
|
||||
|
||||
/// A function that configures an [Angel] server in some way.
|
||||
typedef Future AngelConfigurer(Angel app);
|
||||
typedef FutureOr AngelConfigurer(Angel app);
|
||||
|
||||
/// A powerful real-time/REST/MVC server class.
|
||||
class Angel extends AngelBase {
|
||||
|
@ -202,12 +201,12 @@ class Angel extends AngelBase {
|
|||
/// Shuts down the server, and closes any open [StreamController]s.
|
||||
///
|
||||
/// The server will be **COMPLETE DEFUNCT** after this operation!
|
||||
Future close() async {
|
||||
await Future.forEach(services.values, (Service service) async {
|
||||
await service.close();
|
||||
Future close() {
|
||||
Future.forEach(services.values, (Service service) {
|
||||
service.close();
|
||||
});
|
||||
|
||||
await super.close();
|
||||
super.close();
|
||||
_preContained.clear();
|
||||
handlerCache.clear();
|
||||
_injections.clear();
|
||||
|
@ -220,8 +219,8 @@ class Angel extends AngelBase {
|
|||
shutdownHooks.clear();
|
||||
responseFinalizers.clear();
|
||||
_flattened = null;
|
||||
await _http?.close();
|
||||
return _http?.httpServer;
|
||||
_http?.close();
|
||||
return new Future.value(_http?.httpServer);
|
||||
}
|
||||
|
||||
@override
|
||||
|
@ -269,40 +268,37 @@ class Angel extends AngelBase {
|
|||
this.serializer = serializer;
|
||||
}
|
||||
|
||||
Future getHandlerResult(
|
||||
handler, RequestContext req, ResponseContext res) async {
|
||||
Future getHandlerResult(handler, RequestContext req, ResponseContext res) {
|
||||
if (handler is RequestHandler) {
|
||||
var result = await handler(req, res);
|
||||
return await getHandlerResult(result, req, res);
|
||||
var result = handler(req, res);
|
||||
return getHandlerResult(result, req, res);
|
||||
}
|
||||
|
||||
if (handler is Future) {
|
||||
var result = await handler;
|
||||
return await getHandlerResult(result, req, res);
|
||||
return handler.then((result) => getHandlerResult(result, req, res));
|
||||
}
|
||||
|
||||
if (handler is Function) {
|
||||
var result = await runContained(handler, req, res);
|
||||
return await getHandlerResult(result, req, res);
|
||||
var result = runContained(handler, req, res);
|
||||
return getHandlerResult(result, req, res);
|
||||
}
|
||||
|
||||
if (handler is Stream) {
|
||||
return await getHandlerResult(await handler.toList(), req, res);
|
||||
return getHandlerResult(handler.toList(), req, res);
|
||||
}
|
||||
|
||||
var middleware = (req.app ?? this).findMiddleware(handler);
|
||||
if (middleware != null) {
|
||||
return await getHandlerResult(middleware, req, res);
|
||||
return getHandlerResult(middleware, req, res);
|
||||
}
|
||||
|
||||
return handler;
|
||||
return new Future.value(handler);
|
||||
}
|
||||
|
||||
/// Runs some [handler]. Returns `true` if request execution should continue.
|
||||
Future<bool> executeHandler(
|
||||
handler, RequestContext req, ResponseContext res) async {
|
||||
var result = await getHandlerResult(handler, req, res);
|
||||
|
||||
handler, RequestContext req, ResponseContext res) {
|
||||
return getHandlerResult(handler, req, res).then((result) {
|
||||
if (result == null)
|
||||
return false;
|
||||
else if (result is bool) {
|
||||
|
@ -315,6 +311,7 @@ class Angel extends AngelBase {
|
|||
return false;
|
||||
} else
|
||||
return res.isOpen;
|
||||
});
|
||||
}
|
||||
|
||||
/// Use the serving methods in [AngelHttp] instead.
|
||||
|
@ -400,20 +397,22 @@ class Angel extends AngelBase {
|
|||
/// the execution will be faster, as the injection requirements were stored beforehand.
|
||||
Future runContained(
|
||||
Function handler, RequestContext req, ResponseContext res) {
|
||||
return new Future.sync(() {
|
||||
if (_preContained.containsKey(handler)) {
|
||||
return handleContained(handler, _preContained[handler])(req, res);
|
||||
}
|
||||
|
||||
return runReflected(handler, req, res);
|
||||
});
|
||||
}
|
||||
|
||||
/// Runs with DI, and *always* reflects. Prefer [runContained].
|
||||
Future runReflected(
|
||||
Function handler, RequestContext req, ResponseContext res) async {
|
||||
Function handler, RequestContext req, ResponseContext res) {
|
||||
var h =
|
||||
handleContained(handler, _preContained[handler] = preInject(handler));
|
||||
return await h(req, res);
|
||||
// return await closureMirror.apply(args).reflectee;
|
||||
return new Future.sync(() => h(req, res));
|
||||
// return closureMirror.apply(args).reflectee;
|
||||
}
|
||||
|
||||
/// Use the serving methods in [AngelHttp] instead.
|
||||
|
@ -432,8 +431,8 @@ class Angel extends AngelBase {
|
|||
}
|
||||
|
||||
/// Applies an [AngelConfigurer] to this instance.
|
||||
Future configure(AngelConfigurer configurer) async {
|
||||
await configurer(this);
|
||||
Future configure(AngelConfigurer configurer) {
|
||||
return new Future.sync(() => configurer(this));
|
||||
}
|
||||
|
||||
/// Mounts the child on this router. If [routable] is `null`,
|
||||
|
@ -447,7 +446,7 @@ class Angel extends AngelBase {
|
|||
/// NOTE: The above will not be properly copied if [path] is
|
||||
/// a [RegExp].
|
||||
@override
|
||||
use(path, [@checked Routable routable, String namespace = null]) {
|
||||
use(path, [Router routable, String namespace = null]) {
|
||||
if (routable == null) return all('*', path);
|
||||
|
||||
var head = path.toString().replaceAll(_straySlashes, '');
|
||||
|
@ -457,13 +456,13 @@ class Angel extends AngelBase {
|
|||
_preContained.addAll(routable._preContained);
|
||||
|
||||
if (routable.responseFinalizers.isNotEmpty) {
|
||||
responseFinalizers.add((req, res) async {
|
||||
responseFinalizers.add((req, res) {
|
||||
if (req.path.replaceAll(_straySlashes, '').startsWith(head)) {
|
||||
for (var finalizer in routable.responseFinalizers)
|
||||
await finalizer(req, res);
|
||||
finalizer(req, res);
|
||||
}
|
||||
|
||||
return true;
|
||||
return new Future.value(true);
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -493,8 +492,9 @@ class Angel extends AngelBase {
|
|||
}
|
||||
|
||||
@deprecated
|
||||
Future<ZoneSpecification> defaultZoneCreator(request, req, res) async {
|
||||
return new ZoneSpecification(
|
||||
Future<ZoneSpecification> defaultZoneCreator(request, req, res) {
|
||||
return new Future.value(
|
||||
new ZoneSpecification(
|
||||
print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
|
||||
if (logger != null) {
|
||||
logger.info(line);
|
||||
|
@ -502,6 +502,7 @@ class Angel extends AngelBase {
|
|||
return parent.print(zone, line);
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -518,9 +519,8 @@ class Angel extends AngelBase {
|
|||
factory Angel.fromSecurityContext(SecurityContext context) {
|
||||
var app = new Angel();
|
||||
|
||||
app._http =
|
||||
new AngelHttp.custom(app, (address, int port) async {
|
||||
return await HttpServer.bindSecure(address, port, context);
|
||||
app._http = new AngelHttp.custom(app, (address, int port) {
|
||||
return HttpServer.bindSecure(address, port, context);
|
||||
});
|
||||
|
||||
return app;
|
||||
|
|
|
@ -7,6 +7,7 @@ import '../util.dart';
|
|||
import 'angel_base.dart';
|
||||
import 'hooked_service.dart' show HookedService;
|
||||
import 'metadata.dart';
|
||||
import 'request_context.dart';
|
||||
import 'response_context.dart';
|
||||
import 'routable.dart';
|
||||
|
||||
|
@ -54,11 +55,14 @@ class Service extends Routable {
|
|||
'token'
|
||||
];
|
||||
|
||||
/// Handlers that must run to ensure this service's functionality.
|
||||
List get bootstrappers => [];
|
||||
|
||||
/// The [Angel] app powering this service.
|
||||
AngelBase app;
|
||||
|
||||
/// Closes this service, including any database connections or stream controllers.
|
||||
Future close() async {}
|
||||
void close() {}
|
||||
|
||||
/// Retrieves all resources.
|
||||
Future index([Map params]) {
|
||||
|
@ -99,18 +103,22 @@ class Service extends Routable {
|
|||
}
|
||||
|
||||
/// Generates RESTful routes pointing to this class's methods.
|
||||
void addRoutes() {
|
||||
void addRoutes([Service service]) {
|
||||
_addRoutesInner(service ?? this, bootstrappers);
|
||||
}
|
||||
|
||||
void _addRoutesInner(Service service,
|
||||
List handlers) {
|
||||
Map restProvider = {'provider': Providers.rest};
|
||||
|
||||
// Add global middleware if declared on the instance itself
|
||||
Middleware before = getAnnotation(this, Middleware);
|
||||
final handlers = [];
|
||||
Middleware before = getAnnotation(service, Middleware);
|
||||
|
||||
if (before != null) handlers.addAll(before.handlers);
|
||||
|
||||
Middleware indexMiddleware = getAnnotation(this.index, Middleware);
|
||||
get('/', (req, res) async {
|
||||
return await this.index(mergeMap([
|
||||
Middleware indexMiddleware = getAnnotation(service.index, Middleware);
|
||||
get('/', (req, res) {
|
||||
return this.index(mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
|
@ -120,28 +128,33 @@ class Service extends Routable {
|
|||
..addAll(handlers)
|
||||
..addAll((indexMiddleware == null) ? [] : indexMiddleware.handlers));
|
||||
|
||||
Middleware createMiddleware = getAnnotation(this.create, Middleware);
|
||||
post('/', (req, ResponseContext res) async {
|
||||
var r = await this.create(
|
||||
await req.lazyBody(),
|
||||
Middleware createMiddleware = getAnnotation(service.create, Middleware);
|
||||
post('/', (RequestContext req, ResponseContext res) {
|
||||
return req.lazyBody().then((body) {
|
||||
return this
|
||||
.create(
|
||||
body,
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
]));
|
||||
]))
|
||||
.then((r) {
|
||||
res.statusCode = 201;
|
||||
return r;
|
||||
});
|
||||
});
|
||||
},
|
||||
middleware: []
|
||||
..addAll(handlers)
|
||||
..addAll(
|
||||
(createMiddleware == null) ? [] : createMiddleware.handlers));
|
||||
|
||||
Middleware readMiddleware = getAnnotation(this.read, Middleware);
|
||||
Middleware readMiddleware = getAnnotation(service.read, Middleware);
|
||||
|
||||
get(
|
||||
'/:id',
|
||||
(req, res) async => await this.read(
|
||||
(req, res) => this.read(
|
||||
toId(req.params['id']),
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
|
@ -152,56 +165,56 @@ class Service extends Routable {
|
|||
..addAll(handlers)
|
||||
..addAll((readMiddleware == null) ? [] : readMiddleware.handlers));
|
||||
|
||||
Middleware modifyMiddleware = getAnnotation(this.modify, Middleware);
|
||||
Middleware modifyMiddleware = getAnnotation(service.modify, Middleware);
|
||||
patch(
|
||||
'/:id',
|
||||
(req, res) async => await this.modify(
|
||||
(RequestContext req, res) => req.lazyBody().then((body) => this.modify(
|
||||
toId(req.params['id']),
|
||||
await req.lazyBody(),
|
||||
body,
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
])),
|
||||
]))),
|
||||
middleware: []
|
||||
..addAll(handlers)
|
||||
..addAll(
|
||||
(modifyMiddleware == null) ? [] : modifyMiddleware.handlers));
|
||||
|
||||
Middleware updateMiddleware = getAnnotation(this.update, Middleware);
|
||||
Middleware updateMiddleware = getAnnotation(service.update, Middleware);
|
||||
post(
|
||||
'/:id',
|
||||
(req, res) async => await this.update(
|
||||
(RequestContext req, res) => req.lazyBody().then((body) => this.update(
|
||||
toId(req.params['id']),
|
||||
await req.lazyBody(),
|
||||
body,
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
])),
|
||||
]))),
|
||||
middleware: []
|
||||
..addAll(handlers)
|
||||
..addAll(
|
||||
(updateMiddleware == null) ? [] : updateMiddleware.handlers));
|
||||
put(
|
||||
'/:id',
|
||||
(req, res) async => await this.update(
|
||||
(RequestContext req, res) => req.lazyBody().then((body) => this.update(
|
||||
toId(req.params['id']),
|
||||
await req.lazyBody(),
|
||||
body,
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
restProvider,
|
||||
req.serviceParams
|
||||
])),
|
||||
]))),
|
||||
middleware: []
|
||||
..addAll(handlers)
|
||||
..addAll(
|
||||
(updateMiddleware == null) ? [] : updateMiddleware.handlers));
|
||||
|
||||
Middleware removeMiddleware = getAnnotation(this.remove, Middleware);
|
||||
Middleware removeMiddleware = getAnnotation(service.remove, Middleware);
|
||||
delete(
|
||||
'/',
|
||||
(req, res) async => await this.remove(
|
||||
(req, res) => this.remove(
|
||||
null,
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
|
@ -214,7 +227,7 @@ class Service extends Routable {
|
|||
(removeMiddleware == null) ? [] : removeMiddleware.handlers));
|
||||
delete(
|
||||
'/:id',
|
||||
(req, res) async => await this.remove(
|
||||
(req, res) => this.remove(
|
||||
toId(req.params['id']),
|
||||
mergeMap([
|
||||
{'query': req.query},
|
||||
|
|
|
@ -1,9 +1,17 @@
|
|||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:io'
|
||||
show
|
||||
stderr,
|
||||
HttpRequest,
|
||||
HttpResponse,
|
||||
HttpServer,
|
||||
Platform,
|
||||
SecurityContext;
|
||||
import 'package:angel_http_exception/angel_http_exception.dart';
|
||||
import 'package:angel_route/angel_route.dart';
|
||||
import 'package:combinator/combinator.dart';
|
||||
import 'package:dart2_constant/io.dart';
|
||||
import 'package:json_god/json_god.dart' as god;
|
||||
import 'package:pool/pool.dart';
|
||||
import 'package:stack_trace/stack_trace.dart';
|
||||
|
@ -17,6 +25,7 @@ final RegExp _straySlashes = new RegExp(r'(^/+)|(/+$)');
|
|||
/// Adapts `dart:io`'s [HttpServer] to serve Angel.
|
||||
class AngelHttp {
|
||||
final Angel app;
|
||||
final bool useZone;
|
||||
bool _closed = false;
|
||||
HttpServer _server;
|
||||
Future<HttpServer> Function(dynamic, int) _serverGenerator = HttpServer.bind;
|
||||
|
@ -24,7 +33,7 @@ class AngelHttp {
|
|||
|
||||
Pool _pool;
|
||||
|
||||
AngelHttp(this.app);
|
||||
AngelHttp(this.app, {this.useZone: true});
|
||||
|
||||
/// The function used to bind this instance to an HTTP server.
|
||||
Future<HttpServer> Function(dynamic, int) get serverGenerator =>
|
||||
|
@ -32,15 +41,18 @@ class AngelHttp {
|
|||
|
||||
/// An instance mounted on a server started by the [serverGenerator].
|
||||
factory AngelHttp.custom(
|
||||
Angel app, Future<HttpServer> Function(dynamic, int) serverGenerator) {
|
||||
return new AngelHttp(app).._serverGenerator = serverGenerator;
|
||||
Angel app, Future<HttpServer> Function(dynamic, int) serverGenerator,
|
||||
{bool useZone: true}) {
|
||||
return new AngelHttp(app, useZone: useZone)
|
||||
.._serverGenerator = serverGenerator;
|
||||
}
|
||||
|
||||
factory AngelHttp.fromSecurityContext(Angel app, SecurityContext context) {
|
||||
var http = new AngelHttp(app);
|
||||
factory AngelHttp.fromSecurityContext(Angel app, SecurityContext context,
|
||||
{bool useZone: true}) {
|
||||
var http = new AngelHttp(app, useZone: useZone);
|
||||
|
||||
http._serverGenerator = (address, int port) async {
|
||||
return await HttpServer.bindSecure(address, port, context);
|
||||
http._serverGenerator = (address, int port) {
|
||||
return HttpServer.bindSecure(address, port, context);
|
||||
};
|
||||
|
||||
return http;
|
||||
|
@ -53,7 +65,7 @@ class AngelHttp {
|
|||
/// the server.
|
||||
factory AngelHttp.secure(
|
||||
Angel app, String certificateChainPath, String serverKeyPath,
|
||||
{bool debug: false, String password}) {
|
||||
{bool debug: false, String password, bool useZone: true}) {
|
||||
var certificateChain =
|
||||
Platform.script.resolve(certificateChainPath).toFilePath();
|
||||
var serverKey = Platform.script.resolve(serverKeyPath).toFilePath();
|
||||
|
@ -61,7 +73,8 @@ class AngelHttp {
|
|||
serverContext.useCertificateChain(certificateChain, password: password);
|
||||
serverContext.usePrivateKey(serverKey, password: password);
|
||||
|
||||
return new AngelHttp.fromSecurityContext(app, serverContext);
|
||||
return new AngelHttp.fromSecurityContext(app, serverContext,
|
||||
useZone: useZone);
|
||||
}
|
||||
|
||||
/// The native HttpServer running this instance.
|
||||
|
@ -70,90 +83,35 @@ class AngelHttp {
|
|||
/// Starts the server.
|
||||
///
|
||||
/// Returns false on failure; otherwise, returns the HttpServer.
|
||||
Future<HttpServer> startServer([address, int port]) async {
|
||||
var host = address ?? InternetAddress.LOOPBACK_IP_V4;
|
||||
_server = await _serverGenerator(host, port ?? 0);
|
||||
|
||||
for (var configurer in app.startupHooks) {
|
||||
await app.configure(configurer);
|
||||
}
|
||||
|
||||
Future<HttpServer> startServer([address, int port]) {
|
||||
var host = address ?? '127.0.0.1';
|
||||
return _serverGenerator(host, port ?? 0).then((server) {
|
||||
_server = server;
|
||||
return Future.wait(app.startupHooks.map(app.configure)).then((_) {
|
||||
app.optimizeForProduction();
|
||||
_sub = _server.listen(handleRequest);
|
||||
return _server;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Shuts down the underlying server.
|
||||
Future<HttpServer> close() async {
|
||||
if (_closed) return _server;
|
||||
Future<HttpServer> close() {
|
||||
if (_closed) return new Future.value(_server);
|
||||
_closed = true;
|
||||
_sub?.cancel();
|
||||
|
||||
// TODO: Remove this try/catch in 1.2.0
|
||||
try {
|
||||
await app.close();
|
||||
} catch (_) {}
|
||||
|
||||
for (var configurer in app.shutdownHooks) await app.configure(configurer);
|
||||
return _server;
|
||||
var close = app.close().catchError((_) => null);
|
||||
return close.then((_) =>
|
||||
Future.wait(app.shutdownHooks.map(app.configure)).then((_) => _server));
|
||||
}
|
||||
|
||||
/// Handles a single request.
|
||||
Future handleRequest(HttpRequest request) async {
|
||||
var req = await createRequestContext(request);
|
||||
var res = await createResponseContext(request.response, req);
|
||||
|
||||
var zoneSpec = new ZoneSpecification(
|
||||
print: (self, parent, zone, line) {
|
||||
if (app.logger != null)
|
||||
app.logger.info(line);
|
||||
else
|
||||
parent.print(zone, line);
|
||||
},
|
||||
handleUncaughtError: (self, parent, zone, error, stackTrace) async {
|
||||
var trace = new Trace.from(stackTrace).terse;
|
||||
|
||||
try {
|
||||
AngelHttpException e;
|
||||
|
||||
if (error is FormatException) {
|
||||
e = new AngelHttpException.badRequest(message: error.message);
|
||||
} else if (error is AngelHttpException) {
|
||||
e = error;
|
||||
} else {
|
||||
e = new AngelHttpException(error,
|
||||
stackTrace: stackTrace, message: error?.toString());
|
||||
}
|
||||
|
||||
if (app.logger != null) {
|
||||
app.logger.severe(e.message ?? e.toString(), error, trace);
|
||||
}
|
||||
|
||||
await handleAngelHttpException(e, trace, req, res, request);
|
||||
} catch (e, st) {
|
||||
var trace = new Trace.from(st).terse;
|
||||
request.response.close();
|
||||
// Ideally, we won't be in a position where an absolutely fatal error occurs,
|
||||
// but if so, we'll need to log it.
|
||||
if (app.logger != null) {
|
||||
app.logger.severe(
|
||||
'Fatal error occurred when processing ${request.uri}.',
|
||||
e,
|
||||
trace);
|
||||
} else {
|
||||
stderr
|
||||
..writeln('Fatal error occurred when processing '
|
||||
'${request.uri}:')
|
||||
..writeln(e)
|
||||
..writeln(trace);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
var zone = Zone.current.fork(specification: zoneSpec);
|
||||
|
||||
return await zone.run(() async {
|
||||
Future handleRequest(HttpRequest request) {
|
||||
return createRequestContext(request).then((req) {
|
||||
return createResponseContext(request.response, req).then((res) {
|
||||
handle() {
|
||||
var path = req.path;
|
||||
if (path == '/') path = '';
|
||||
|
||||
|
@ -174,35 +132,104 @@ class AngelHttp {
|
|||
? app.handlerCache.putIfAbsent(cacheKey, resolveTuple)
|
||||
: resolveTuple();
|
||||
|
||||
req.inject(Zone, zone);
|
||||
req.inject(ZoneSpecification, zoneSpec);
|
||||
req.params.addAll(tuple.item2);
|
||||
req.inject(ParseResult, tuple.item3);
|
||||
|
||||
if (app.logger != null) req.inject(Stopwatch, new Stopwatch()..start());
|
||||
if (app.logger != null)
|
||||
req.inject(Stopwatch, new Stopwatch()..start());
|
||||
|
||||
var pipeline = tuple.item1;
|
||||
|
||||
Future<bool> Function() runPipeline;
|
||||
|
||||
for (var handler in pipeline) {
|
||||
if (handler == null || !await app.executeHandler(handler, req, res))
|
||||
break;
|
||||
if (handler == null) break;
|
||||
|
||||
if (runPipeline == null)
|
||||
runPipeline = () => app.executeHandler(handler, req, res);
|
||||
else {
|
||||
var current = runPipeline;
|
||||
runPipeline = () => current().then((result) =>
|
||||
!result ? result : app.executeHandler(handler, req, res));
|
||||
}
|
||||
}
|
||||
|
||||
await sendResponse(request, req, res);
|
||||
}).whenComplete(() {
|
||||
return runPipeline == null
|
||||
? sendResponse(request, req, res)
|
||||
: runPipeline().then((_) => sendResponse(request, req, res));
|
||||
}
|
||||
|
||||
if (useZone == false) {
|
||||
return handle().whenComplete(() => res.dispose());
|
||||
} else {
|
||||
var zoneSpec = new ZoneSpecification(
|
||||
print: (self, parent, zone, line) {
|
||||
if (app.logger != null)
|
||||
app.logger.info(line);
|
||||
else
|
||||
parent.print(zone, line);
|
||||
},
|
||||
handleUncaughtError: (self, parent, zone, error, stackTrace) {
|
||||
var trace = new Trace.from(stackTrace).terse;
|
||||
|
||||
return new Future(() {
|
||||
AngelHttpException e;
|
||||
|
||||
if (error is FormatException) {
|
||||
e = new AngelHttpException.badRequest(message: error.message);
|
||||
} else if (error is AngelHttpException) {
|
||||
e = error;
|
||||
} else {
|
||||
e = new AngelHttpException(error,
|
||||
stackTrace: stackTrace, message: error?.toString());
|
||||
}
|
||||
|
||||
if (app.logger != null) {
|
||||
app.logger.severe(e.message ?? e.toString(), error, trace);
|
||||
}
|
||||
|
||||
return handleAngelHttpException(e, trace, req, res, request);
|
||||
}).catchError((e, st) {
|
||||
var trace = new Trace.from(st).terse;
|
||||
request.response.close();
|
||||
// Ideally, we won't be in a position where an absolutely fatal error occurs,
|
||||
// but if so, we'll need to log it.
|
||||
if (app.logger != null) {
|
||||
app.logger.severe(
|
||||
'Fatal error occurred when processing ${request.uri}.',
|
||||
e,
|
||||
trace);
|
||||
} else {
|
||||
stderr
|
||||
..writeln('Fatal error occurred when processing '
|
||||
'${request.uri}:')
|
||||
..writeln(e)
|
||||
..writeln(trace);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
var zone = Zone.current.fork(specification: zoneSpec);
|
||||
req.inject(Zone, zone);
|
||||
req.inject(ZoneSpecification, zoneSpec);
|
||||
return zone.run(handle).whenComplete(() {
|
||||
res.dispose();
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Handles an [AngelHttpException].
|
||||
Future handleAngelHttpException(AngelHttpException e, StackTrace st,
|
||||
RequestContext req, ResponseContext res, HttpRequest request,
|
||||
{bool ignoreFinalizers: false}) async {
|
||||
{bool ignoreFinalizers: false}) {
|
||||
if (req == null || res == null) {
|
||||
try {
|
||||
app.logger?.severe(e, st);
|
||||
request.response
|
||||
..statusCode = HttpStatus.INTERNAL_SERVER_ERROR
|
||||
..statusCode = HttpStatus.internalServerError
|
||||
..write('500 Internal Server Error')
|
||||
..close();
|
||||
} finally {
|
||||
|
@ -212,12 +239,12 @@ class AngelHttp {
|
|||
|
||||
if (res.isOpen) {
|
||||
res.statusCode = e.statusCode;
|
||||
var result = await app.errorHandler(e, req, res);
|
||||
await app.executeHandler(result, req, res);
|
||||
var result = app.errorHandler(e, req, res);
|
||||
app.executeHandler(result, req, res);
|
||||
res.end();
|
||||
}
|
||||
|
||||
return await sendResponse(request, req, res,
|
||||
return sendResponse(request, req, res,
|
||||
ignoreFinalizers: ignoreFinalizers == true);
|
||||
}
|
||||
|
||||
|
@ -244,8 +271,12 @@ class AngelHttp {
|
|||
List<int> outputBuffer = res.buffer.toBytes();
|
||||
|
||||
if (res.encoders.isNotEmpty) {
|
||||
var allowedEncodings =
|
||||
req.headers[HttpHeaders.ACCEPT_ENCODING]?.map((str) {
|
||||
var allowedEncodings = req.headers
|
||||
.value('accept-encoding')
|
||||
?.split(',')
|
||||
?.map((s) => s.trim())
|
||||
?.where((s) => s.isNotEmpty)
|
||||
?.map((str) {
|
||||
// Ignore quality specifications in accept-encoding
|
||||
// ex. gzip;q=0.8
|
||||
if (!str.contains(';')) return str;
|
||||
|
@ -264,7 +295,7 @@ class AngelHttp {
|
|||
}
|
||||
|
||||
if (encoder != null) {
|
||||
request.response.headers.set(HttpHeaders.CONTENT_ENCODING, key);
|
||||
request.response.headers.set('content-encoding', key);
|
||||
outputBuffer = res.encoders[key].convert(outputBuffer);
|
||||
request.response.contentLength = outputBuffer.length;
|
||||
break;
|
||||
|
@ -278,10 +309,8 @@ class AngelHttp {
|
|||
..cookies.addAll(res.cookies)
|
||||
..add(outputBuffer);
|
||||
|
||||
return finalizers.then((_) async {
|
||||
await request.response.flush();
|
||||
await request.response.close();
|
||||
|
||||
return finalizers.then((_) {
|
||||
return request.response.close().then((_) {
|
||||
if (req.injections.containsKey(PoolResource)) {
|
||||
req.injections[PoolResource].release();
|
||||
}
|
||||
|
@ -296,13 +325,14 @@ class AngelHttp {
|
|||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Future<HttpRequestContextImpl> createRequestContext(HttpRequest request) {
|
||||
var path = request.uri.path.replaceAll(_straySlashes, '');
|
||||
if (path.length == 0) path = '/';
|
||||
return HttpRequestContextImpl.from(request, app, path).then((req) async {
|
||||
if (_pool != null) req.inject(PoolResource, await _pool.request());
|
||||
return HttpRequestContextImpl.from(request, app, path).then((req) {
|
||||
if (_pool != null) req.inject(PoolResource, _pool.request());
|
||||
if (app.injections.isNotEmpty) app.injections.forEach(req.inject);
|
||||
return req;
|
||||
});
|
||||
|
|
|
@ -27,7 +27,7 @@ class Controller {
|
|||
Controller({this.debug: false, this.injectSingleton: true});
|
||||
|
||||
@mustCallSuper
|
||||
Future configureServer(Angel app) async {
|
||||
Future configureServer(Angel app) {
|
||||
_app = app;
|
||||
|
||||
if (injectSingleton != false) _app.container.singleton(this);
|
||||
|
@ -56,6 +56,7 @@ class Controller {
|
|||
final routeBuilder = _routeBuilder(instanceMirror, routable, handlers);
|
||||
classMirror.instanceMembers.forEach(routeBuilder);
|
||||
configureRoutes(routable);
|
||||
return new Future.value();
|
||||
}
|
||||
|
||||
Function _routeBuilder(
|
||||
|
@ -85,9 +86,9 @@ class Controller {
|
|||
method.parameters[1].type.reflectedType == ResponseContext) {
|
||||
// Create a regular route
|
||||
routeMappings[name] = routable
|
||||
.addRoute(exposeDecl.method, exposeDecl.path, (req, res) async {
|
||||
var result = await reflectedMethod(req, res);
|
||||
return result is RequestHandler ? await result(req, res) : result;
|
||||
.addRoute(exposeDecl.method, exposeDecl.path, (req, res) {
|
||||
var result = reflectedMethod(req, res);
|
||||
return result is RequestHandler ? result(req, res) : result;
|
||||
}, middleware: middleware);
|
||||
return;
|
||||
}
|
||||
|
|
|
@ -14,10 +14,10 @@ export 'http_response_context.dart';
|
|||
|
||||
/// Boots a shared server instance. Use this if launching multiple isolates
|
||||
Future<HttpServer> startShared(address, int port) => HttpServer
|
||||
.bind(address ?? InternetAddress.LOOPBACK_IP_V4, port ?? 0, shared: true);
|
||||
.bind(address ?? '127.0.0.1', port ?? 0, shared: true);
|
||||
|
||||
Future<HttpServer> Function(dynamic, int) startSharedSecure(SecurityContext securityContext) {
|
||||
return (address, int port) => HttpServer.bindSecure(
|
||||
address ?? InternetAddress.LOOPBACK_IP_V4, port ?? 0, securityContext,
|
||||
address ?? '127.0.0.1', port ?? 0, securityContext,
|
||||
shared: true);
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:body_parser/body_parser.dart';
|
||||
import 'package:http_parser/http_parser.dart';
|
||||
import '../core/core.dart';
|
||||
|
||||
/// An implementation of [RequestContext] that wraps a [HttpRequest].
|
||||
|
@ -70,7 +71,7 @@ class HttpRequestContextImpl extends RequestContext {
|
|||
|
||||
/// Magically transforms an [HttpRequest] into a [RequestContext].
|
||||
static Future<HttpRequestContextImpl> from(
|
||||
HttpRequest request, Angel app, String path) async {
|
||||
HttpRequest request, Angel app, String path) {
|
||||
HttpRequestContextImpl ctx = new HttpRequestContextImpl();
|
||||
|
||||
String override = request.method;
|
||||
|
@ -116,10 +117,10 @@ class HttpRequestContextImpl extends RequestContext {
|
|||
ctx._io = request;
|
||||
|
||||
if (app.lazyParseBodies != true) {
|
||||
await ctx.parse();
|
||||
return ctx.parse().then((_) => ctx);
|
||||
}
|
||||
|
||||
return ctx;
|
||||
return new Future.value(ctx);
|
||||
}
|
||||
|
||||
@override
|
||||
|
@ -131,8 +132,13 @@ class HttpRequestContextImpl extends RequestContext {
|
|||
}
|
||||
|
||||
@override
|
||||
Future<BodyParseResult> parseOnce() async {
|
||||
return await parseBody(io,
|
||||
Future<BodyParseResult> parseOnce() {
|
||||
return parseBodyFromStream(
|
||||
io,
|
||||
io.headers.contentType != null
|
||||
? new MediaType.parse(io.headers.contentType.toString())
|
||||
: null,
|
||||
io.uri,
|
||||
storeOriginalBuffer: app.storeOriginalBuffer == true);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -111,10 +111,10 @@ class HttpResponseContextImpl extends ResponseContext {
|
|||
}
|
||||
|
||||
@override
|
||||
Future close() async {
|
||||
Future close() {
|
||||
if (_useStream) {
|
||||
try {
|
||||
await io.close();
|
||||
io.close();
|
||||
} catch(_) {
|
||||
// This only seems to occur on `MockHttpRequest`, but
|
||||
// this try/catch prevents a crash.
|
||||
|
@ -122,7 +122,8 @@ class HttpResponseContextImpl extends ResponseContext {
|
|||
}
|
||||
|
||||
_isClosed = true;
|
||||
await super.close();
|
||||
super.close();
|
||||
_useStream = false;
|
||||
return new Future.value();
|
||||
}
|
||||
}
|
|
@ -58,10 +58,10 @@ class AngelMetrics extends Angel {
|
|||
final AngelMetricsStats stats = new AngelMetricsStats._();
|
||||
|
||||
@override
|
||||
Future<HttpServer> close() async {
|
||||
Future<HttpServer> close() {
|
||||
_sub?.cancel();
|
||||
await _inner.close();
|
||||
return await super.close();
|
||||
_inner.close();
|
||||
return super.close();
|
||||
}
|
||||
|
||||
@override
|
||||
|
|
|
@ -23,13 +23,14 @@ main() async {
|
|||
|
||||
void start(int id) {
|
||||
var app = new Angel()..lazyParseBodies = true;
|
||||
var http = new AngelHttp.custom(app, startShared);
|
||||
var http = new AngelHttp.custom(app, startShared, useZone: false);
|
||||
|
||||
app.get('/', (req, ResponseContext res) {
|
||||
res.willCloseItself = true;
|
||||
res.io
|
||||
..write('Hello, world!')
|
||||
..close();
|
||||
res.write('Hello, world!');
|
||||
//res.willCloseItself = true;
|
||||
//res.io
|
||||
// ..write('Hello, world!')
|
||||
// ..close();
|
||||
return false;
|
||||
});
|
||||
|
||||
|
@ -41,7 +42,7 @@ void start(int id) {
|
|||
return oldHandler(e, req, res);
|
||||
};
|
||||
|
||||
http.startServer(InternetAddress.LOOPBACK_IP_V4, 3000).then((server) {
|
||||
http.startServer('127.0.0.1', 3000).then((server) {
|
||||
print(
|
||||
'Instance #$id listening at http://${server.address.address}:${server.port}');
|
||||
});
|
||||
|
|
|
@ -12,7 +12,7 @@ main() {
|
|||
|
||||
void start(int id) {
|
||||
HttpServer
|
||||
.bind(InternetAddress.LOOPBACK_IP_V4, 3000, shared: true)
|
||||
.bind('127.0.0.1', 3000, shared: true)
|
||||
.then((server) {
|
||||
print(
|
||||
'Instance #$id listening at http://${server.address.address}:${server.port}');
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
name: angel_framework
|
||||
version: 1.1.3
|
||||
version: 1.1.4
|
||||
description: A high-powered HTTP server with DI, routing and more.
|
||||
author: Tobe O <thosakwe@gmail.com>
|
||||
homepage: https://github.com/angel-dart/angel_framework
|
||||
|
@ -14,6 +14,7 @@ dependencies:
|
|||
combinator: ">=1.0.0-beta <2.0.0"
|
||||
container: ^0.1.2
|
||||
dart2_constant: ^1.0.0
|
||||
http_parser: ^3.0.0
|
||||
json_god: ^2.0.0-beta
|
||||
logging: ">=0.11.3 <1.0.0"
|
||||
matcher: ^0.12.0
|
||||
|
@ -23,6 +24,7 @@ dependencies:
|
|||
path: ">=1.0.0 <2.0.0"
|
||||
pool: ^1.0.0
|
||||
random_string: ^0.0.1
|
||||
stack_trace: ^1.0.0
|
||||
tuple: ^1.0.0
|
||||
dev_dependencies:
|
||||
mock_request: ^1.0.0
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:io' show BytesBuilder;
|
||||
import 'package:angel_framework/angel_framework.dart';
|
||||
import 'package:dart2_constant/convert.dart';
|
||||
import 'package:dart2_constant/io.dart';
|
||||
import 'package:mock_request/mock_request.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
|
@ -19,8 +20,8 @@ main() {
|
|||
app = new Angel();
|
||||
app.injectEncoders(
|
||||
{
|
||||
'deflate': ZLIB.encoder,
|
||||
'gzip': GZIP.encoder,
|
||||
'deflate': zlib.encoder,
|
||||
'gzip': gzip.encoder,
|
||||
},
|
||||
);
|
||||
|
||||
|
@ -55,50 +56,50 @@ void encodingTests(Angel getApp()) {
|
|||
|
||||
test('encodes if wildcard', () async {
|
||||
var rq = new MockHttpRequest('GET', Uri.parse('/hello'))
|
||||
..headers.set(HttpHeaders.ACCEPT_ENCODING, '*')
|
||||
..headers.set('accept-encoding', '*')
|
||||
..close();
|
||||
var rs = rq.response;
|
||||
await http.handleRequest(rq);
|
||||
|
||||
var body = await getBody(rs);
|
||||
expect(rs.headers.value(HttpHeaders.CONTENT_ENCODING), 'deflate');
|
||||
expect(body, ZLIB.encode(utf8.encode('Hello, world!')));
|
||||
expect(rs.headers.value('content-encoding'), 'deflate');
|
||||
expect(body, zlib.encode(utf8.encode('Hello, world!')));
|
||||
});
|
||||
|
||||
test('encodes if wildcard + multiple', () async {
|
||||
var rq = new MockHttpRequest('GET', Uri.parse('/hello'))
|
||||
..headers.set(HttpHeaders.ACCEPT_ENCODING, ['foo', 'bar', '*'])
|
||||
..headers.set('accept-encoding', ['foo', 'bar', '*'])
|
||||
..close();
|
||||
var rs = rq.response;
|
||||
await http.handleRequest(rq);
|
||||
|
||||
var body = await getBody(rs);
|
||||
expect(rs.headers.value(HttpHeaders.CONTENT_ENCODING), 'deflate');
|
||||
expect(body, ZLIB.encode(utf8.encode('Hello, world!')));
|
||||
expect(rs.headers.value('content-encoding'), 'deflate');
|
||||
expect(body, zlib.encode(utf8.encode('Hello, world!')));
|
||||
});
|
||||
|
||||
test('encodes if explicit', () async {
|
||||
var rq = new MockHttpRequest('GET', Uri.parse('/hello'))
|
||||
..headers.set(HttpHeaders.ACCEPT_ENCODING, 'gzip');
|
||||
..headers.set('accept-encoding', 'gzip');
|
||||
await rq.close();
|
||||
var rs = rq.response;
|
||||
await http.handleRequest(rq);
|
||||
|
||||
var body = await getBody(rs);
|
||||
expect(rs.headers.value(HttpHeaders.CONTENT_ENCODING), 'gzip');
|
||||
expect(body, GZIP.encode(utf8.encode('Hello, world!')));
|
||||
expect(rs.headers.value('content-encoding'), 'gzip');
|
||||
expect(body, gzip.encode(utf8.encode('Hello, world!')));
|
||||
});
|
||||
|
||||
test('only uses one encoder', () async {
|
||||
var rq = new MockHttpRequest('GET', Uri.parse('/hello'))
|
||||
..headers.set(HttpHeaders.ACCEPT_ENCODING, ['gzip', 'deflate']);
|
||||
..headers.set('accept-encoding', ['gzip', 'deflate']);
|
||||
await rq.close();
|
||||
var rs = rq.response;
|
||||
await http.handleRequest(rq);
|
||||
|
||||
var body = await getBody(rs);
|
||||
expect(rs.headers.value(HttpHeaders.CONTENT_ENCODING), 'gzip');
|
||||
expect(body, GZIP.encode(utf8.encode('Hello, world!')));
|
||||
expect(rs.headers.value('content-encoding'), 'gzip');
|
||||
expect(body, gzip.encode(utf8.encode('Hello, world!')));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:angel_framework/angel_framework.dart';
|
||||
import 'package:dart2_constant/convert.dart';
|
||||
import 'package:matcher/matcher.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
main() {
|
||||
|
@ -41,8 +40,8 @@ main() {
|
|||
test('toMap = toJson', () {
|
||||
var exc = new AngelHttpException.badRequest();
|
||||
expect(exc.toMap(), exc.toJson());
|
||||
var json = JSON.encode(exc.toJson());
|
||||
var exc2 = new AngelHttpException.fromJson(json);
|
||||
var json_ = json.encode(exc.toJson());
|
||||
var exc2 = new AngelHttpException.fromJson(json_);
|
||||
expect(exc2.toJson(), exc.toJson());
|
||||
});
|
||||
|
||||
|
@ -68,7 +67,9 @@ class _IsException extends Matcher {
|
|||
description.add('has status code $statusCode and message "$message"');
|
||||
|
||||
@override
|
||||
bool matches(@checked AngelHttpException item, Map matchState) {
|
||||
return item.statusCode == statusCode && item.message == message;
|
||||
bool matches(item, Map matchState) {
|
||||
return item is AngelHttpException &&
|
||||
item.statusCode == statusCode &&
|
||||
item.message == message;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:angel_framework/angel_framework.dart';
|
||||
import 'package:dart2_constant/convert.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:test/test.dart';
|
||||
|
||||
|
@ -32,6 +32,6 @@ main() {
|
|||
var response = await client
|
||||
.get('$url/foo', headers: {'X-HTTP-Method-Override': 'POST'});
|
||||
print('Response: ${response.body}');
|
||||
expect(JSON.decode(response.body), equals({'hello': 'world'}));
|
||||
expect(json.decode(response.body), equals({'hello': 'world'}));
|
||||
});
|
||||
}
|
||||
|
|
|
@ -51,12 +51,13 @@ main() {
|
|||
return 'DEFAULT $mode';
|
||||
});
|
||||
|
||||
app.logger = new Logger('parameter_meta_test')
|
||||
/*app.logger = new Logger('parameter_meta_test')
|
||||
..onRecord.listen((rec) {
|
||||
print(rec);
|
||||
if (rec.error != null) print(rec.error);
|
||||
if (rec.stackTrace != null) print(rec.stackTrace);
|
||||
});
|
||||
*/
|
||||
});
|
||||
|
||||
test('injects header or throws', () async {
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import 'dart:convert';
|
||||
import 'package:angel_framework/angel_framework.dart';
|
||||
import 'package:dart2_constant/convert.dart';
|
||||
import 'package:mock_request/mock_request.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
|
@ -16,8 +16,8 @@ main() {
|
|||
rq.close();
|
||||
await new AngelHttp(app).handleRequest(rq);
|
||||
var rs = rq.response;
|
||||
var body = await rs.transform(UTF8.decoder).join();
|
||||
expect(body, JSON.encode('bar'));
|
||||
var body = await rs.transform(utf8.decoder).join();
|
||||
expect(body, json.encode('bar'));
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:io' show stderr;
|
||||
import 'package:angel_framework/angel_framework.dart';
|
||||
import 'package:dart2_constant/convert.dart';
|
||||
import 'package:mock_request/mock_request.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
|
@ -36,22 +36,22 @@ main() {
|
|||
test('String type annotation', () async {
|
||||
var rq = new MockHttpRequest('GET', Uri.parse('/string/hello'))..close();
|
||||
await http.handleRequest(rq);
|
||||
var rs = await rq.response.transform(UTF8.decoder).join();
|
||||
expect(rs, JSON.encode('hello'));
|
||||
var rs = await rq.response.transform(utf8.decoder).join();
|
||||
expect(rs, json.encode('hello'));
|
||||
});
|
||||
|
||||
test('Primitive after parsed param injection', () async {
|
||||
var rq = new MockHttpRequest('GET', Uri.parse('/num/parsed/24'))..close();
|
||||
await http.handleRequest(rq);
|
||||
var rs = await rq.response.transform(UTF8.decoder).join();
|
||||
expect(rs, JSON.encode(24));
|
||||
var rs = await rq.response.transform(utf8.decoder).join();
|
||||
expect(rs, json.encode(24));
|
||||
});
|
||||
|
||||
test('globally-injected primitive', () async {
|
||||
var rq = new MockHttpRequest('GET', Uri.parse('/num/global'))..close();
|
||||
await http.handleRequest(rq);
|
||||
var rs = await rq.response.transform(UTF8.decoder).join();
|
||||
expect(rs, JSON.encode(305));
|
||||
var rs = await rq.response.transform(utf8.decoder).join();
|
||||
expect(rs, json.encode(305));
|
||||
});
|
||||
|
||||
test('unparsed primitive throws error', () async {
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:angel_framework/angel_framework.dart';
|
||||
import 'package:dart2_constant/convert.dart';
|
||||
import 'package:mock_request/mock_request.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
|
@ -13,9 +13,9 @@ main() {
|
|||
var app = new Angel()..get('/test/:id', (id) => 'Hello $id');
|
||||
var rq1 = mk(1), rq2 = mk(2), rq3 = mk(1);
|
||||
await Future.wait([rq1, rq2, rq3].map(new AngelHttp(app).handleRequest));
|
||||
var body1 = await rq1.response.transform(UTF8.decoder).join(),
|
||||
body2 = await rq2.response.transform(UTF8.decoder).join(),
|
||||
body3 = await rq3.response.transform(UTF8.decoder).join();
|
||||
var body1 = await rq1.response.transform(utf8.decoder).join(),
|
||||
body2 = await rq2.response.transform(utf8.decoder).join(),
|
||||
body3 = await rq3.response.transform(utf8.decoder).join();
|
||||
print('Response #1: $body1');
|
||||
print('Response #2: $body2');
|
||||
print('Response #3: $body3');
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:angel_framework/angel_framework.dart';
|
||||
import 'package:dart2_constant/convert.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:test/test.dart';
|
||||
|
||||
|
@ -96,7 +95,7 @@ main() {
|
|||
|
||||
client = new http.Client();
|
||||
var server =
|
||||
await new AngelHttp(app).startServer(InternetAddress.LOOPBACK_IP_V4, 0);
|
||||
await new AngelHttp(app).startServer('127.0.0.1', 0);
|
||||
url = "http://${server.address.host}:${server.port}";
|
||||
});
|
||||
|
||||
|
@ -118,10 +117,10 @@ main() {
|
|||
test('Can match url with multiple parameters', () async {
|
||||
var response = await client.get('$url/name/HELLO/last/WORLD');
|
||||
print('Response: ${response.body}');
|
||||
var json = JSON.decode(response.body);
|
||||
expect(json, new isInstanceOf<Map<String, String>>());
|
||||
expect(json['first'], equals('HELLO'));
|
||||
expect(json['last'], equals('WORLD'));
|
||||
var json_ = json.decode(response.body);
|
||||
expect(json_, new isInstanceOf<Map<String, String>>());
|
||||
expect(json_['first'], equals('HELLO'));
|
||||
expect(json_['last'], equals('WORLD'));
|
||||
});
|
||||
|
||||
test('Chained routes', () async {
|
||||
|
@ -131,16 +130,16 @@ main() {
|
|||
|
||||
test('Can nest another Angel instance', () async {
|
||||
var response = await client.post('$url/nes/ted/foo');
|
||||
var json = JSON.decode(response.body);
|
||||
expect(json['route'], equals('foo'));
|
||||
var json_ = json.decode(response.body);
|
||||
expect(json_['route'], equals('foo'));
|
||||
});
|
||||
|
||||
test('Can parse parameters from a nested Angel instance', () async {
|
||||
var response = await client.get('$url/todos/1337/action/test');
|
||||
var json = JSON.decode(response.body);
|
||||
print('JSON: $json');
|
||||
expect(json['id'], equals('1337'));
|
||||
expect(json['action'], equals('test'));
|
||||
var json_ = json.decode(response.body);
|
||||
print('JSON: $json_');
|
||||
expect(json_['id'], equals('1337'));
|
||||
expect(json_['action'], equals('test'));
|
||||
});
|
||||
|
||||
test('Can add and use named middleware', () async {
|
||||
|
@ -156,10 +155,11 @@ main() {
|
|||
|
||||
test('Can serialize function result as JSON', () async {
|
||||
Map headers = {'Content-Type': 'application/json'};
|
||||
String postData = JSON.encode({'it': 'works'});
|
||||
String postData = json.encode({'it': 'works'});
|
||||
var response =
|
||||
await client.post("$url/lambda", headers: headers, body: postData);
|
||||
expect(JSON.decode(response.body)['it'], equals('works'));
|
||||
print('Response: ${response.body}');
|
||||
expect(json.decode(response.body)['it'], equals('works'));
|
||||
});
|
||||
|
||||
test('Fallback routes', () async {
|
||||
|
@ -178,14 +178,14 @@ main() {
|
|||
test('Redirect to named routes', () async {
|
||||
var response = await client.get('$url/named');
|
||||
print(response.body);
|
||||
expect(JSON.decode(response.body), equals('Hello tests'));
|
||||
expect(json.decode(response.body), equals('Hello tests'));
|
||||
});
|
||||
|
||||
test('Match routes, even with query params', () async {
|
||||
var response =
|
||||
await client.get("$url/log?foo=bar&bar=baz&baz.foo=bar&baz.bar=foo");
|
||||
print(response.body);
|
||||
expect(JSON.decode(response.body), equals('Logged'));
|
||||
expect(json.decode(response.body), equals('Logged'));
|
||||
|
||||
response = await client.get("$url/query/foo?bar=baz");
|
||||
print(response.body);
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:angel_framework/angel_framework.dart';
|
||||
import 'package:dart2_constant/convert.dart';
|
||||
import 'package:matcher/matcher.dart';
|
||||
import 'package:mock_request/mock_request.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
@ -51,7 +51,7 @@ main() {
|
|||
ContentType.HTML.mimeType,
|
||||
);
|
||||
expect(rs.statusCode, e.statusCode);
|
||||
var body = await rs.transform(UTF8.decoder).join();
|
||||
var body = await rs.transform(utf8.decoder).join();
|
||||
expect(body, contains('<title>${e.message}</title>'));
|
||||
expect(body, contains('<li>foo</li>'));
|
||||
expect(body, contains('<li>bar</li>'));
|
||||
|
@ -59,9 +59,7 @@ main() {
|
|||
|
||||
test('plug-ins run on startup', () async {
|
||||
var app = new Angel();
|
||||
app.startupHooks.add((app) async {
|
||||
app.configuration['two'] = 2;
|
||||
});
|
||||
app.startupHooks.add((app) => app.configuration['two'] = 2);
|
||||
|
||||
var http = new AngelHttp(app);
|
||||
await http.startServer();
|
||||
|
@ -92,8 +90,8 @@ main() {
|
|||
app.get('/', (String a) => a);
|
||||
var rq = new MockHttpRequest('GET', Uri.parse('/'))..close();
|
||||
await http.handleRequest(rq);
|
||||
var body = await rq.response.transform(UTF8.decoder).join();
|
||||
expect(body, JSON.encode('b'));
|
||||
var body = await rq.response.transform(utf8.decoder).join();
|
||||
expect(body, json.encode('b'));
|
||||
});
|
||||
|
||||
test('global injected serializer', () async {
|
||||
|
@ -102,7 +100,7 @@ main() {
|
|||
app.get($foo.path, (req, ResponseContext res) => res.serialize(null));
|
||||
var rq = new MockHttpRequest('GET', $foo)..close();
|
||||
await http.handleRequest(rq);
|
||||
var body = await rq.response.transform(UTF8.decoder).join();
|
||||
var body = await rq.response.transform(utf8.decoder).join();
|
||||
expect(body, 'x');
|
||||
});
|
||||
|
||||
|
@ -157,7 +155,7 @@ main() {
|
|||
app.get('/wtf', () => throw new AngelHttpException.forbidden());
|
||||
app.get('/wtf2', () => throw new AngelHttpException.forbidden());
|
||||
http = new AngelHttp(app);
|
||||
await http.startServer(InternetAddress.LOOPBACK_IP_V4, 0);
|
||||
await http.startServer('127.0.0.1', 0);
|
||||
|
||||
var oldHandler = app.errorHandler;
|
||||
app.errorHandler = (e, req, res) {
|
||||
|
@ -208,9 +206,9 @@ class CustomCloseService extends Service {
|
|||
int value = 2;
|
||||
|
||||
@override
|
||||
Future close() {
|
||||
void close() {
|
||||
value = 3;
|
||||
return super.close();
|
||||
super.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
import 'dart:convert';
|
||||
import 'package:angel_framework/angel_framework.dart';
|
||||
import 'package:dart2_constant/convert.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:json_god/json_god.dart' as god;
|
||||
import 'package:stack_trace/stack_trace.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
class Todo extends Model {
|
||||
|
@ -23,7 +24,7 @@ main() {
|
|||
..use('/todos', new TypedService<Todo>(new MapService()))
|
||||
..errorHandler = (e, req, res) {
|
||||
print('Whoops: ${e.error}');
|
||||
print(e.stackTrace);
|
||||
if (e.stackTrace != null) print(new Chain.forTrace(e.stackTrace).terse);
|
||||
};
|
||||
|
||||
var server = await new AngelHttp(app).startServer();
|
||||
|
@ -45,7 +46,7 @@ main() {
|
|||
print(response.body);
|
||||
expect(response.body, equals('[]'));
|
||||
print(response.body);
|
||||
expect(JSON.decode(response.body).length, 0);
|
||||
expect(json.decode(response.body).length, 0);
|
||||
});
|
||||
|
||||
test('can create data', () async {
|
||||
|
@ -97,12 +98,12 @@ main() {
|
|||
String postData = god.serialize({'text': 'Hello, world!'});
|
||||
var created = await client
|
||||
.post("$url/todos", headers: headers, body: postData)
|
||||
.then((r) => JSON.decode(r.body));
|
||||
.then((r) => json.decode(r.body));
|
||||
var response = await client.delete("$url/todos/${created['id']}");
|
||||
expect(response.statusCode, 200);
|
||||
var json = god.deserialize(response.body);
|
||||
print(json);
|
||||
expect(json['text'], equals('Hello, world!'));
|
||||
var json_ = god.deserialize(response.body);
|
||||
print(json_);
|
||||
expect(json_['text'], equals('Hello, world!'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:io' show stderr;
|
||||
import 'package:angel_framework/angel_framework.dart';
|
||||
import 'package:dart2_constant/convert.dart';
|
||||
import 'package:dart2_constant/io.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:mock_request/mock_request.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
@ -23,8 +24,8 @@ main() {
|
|||
|
||||
app.injectEncoders(
|
||||
{
|
||||
'deflate': ZLIB.encoder,
|
||||
'gzip': GZIP.encoder,
|
||||
'deflate': zlib.encoder,
|
||||
'gzip': gzip.encoder,
|
||||
},
|
||||
);
|
||||
|
||||
|
@ -73,7 +74,7 @@ main() {
|
|||
_expectHelloBye(String path) async {
|
||||
var rq = new MockHttpRequest('GET', Uri.parse(path))..close();
|
||||
await http.handleRequest(rq);
|
||||
var body = await rq.response.transform(UTF8.decoder).join();
|
||||
var body = await rq.response.transform(utf8.decoder).join();
|
||||
expect(body, 'Hello, world!bye');
|
||||
}
|
||||
|
||||
|
@ -84,7 +85,7 @@ main() {
|
|||
test('cannot write after close', () async {
|
||||
var rq = new MockHttpRequest('GET', Uri.parse('/overwrite'))..close();
|
||||
await http.handleRequest(rq);
|
||||
var body = await rq.response.transform(UTF8.decoder).join();
|
||||
var body = await rq.response.transform(utf8.decoder).join();
|
||||
|
||||
if (rq.response.statusCode != 32)
|
||||
throw 'overwrite should throw error; response: $body';
|
||||
|
@ -94,7 +95,7 @@ main() {
|
|||
try {
|
||||
var rq = new MockHttpRequest('GET', Uri.parse('/error'))..close();
|
||||
await http.handleRequest(rq);
|
||||
var body = await rq.response.transform(UTF8.decoder).join();
|
||||
var body = await rq.response.transform(utf8.decoder).join();
|
||||
throw 'addError should throw error; response: $body';
|
||||
} on StateError {
|
||||
// Should throw error...
|
||||
|
|
Loading…
Reference in a new issue