platform/packages/framework/example/controller.dart

60 lines
1.4 KiB
Dart
Raw Normal View History

2021-05-14 10:34:09 +00:00
import 'package:angel3_container/mirrors.dart';
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';
2019-07-17 19:48:02 +00:00
import 'package:logging/logging.dart';
2021-05-14 10:34:09 +00:00
void main() async {
2019-07-17 19:48:02 +00:00
// Logging set up/boilerplate
Logger.root.onRecord.listen(print);
// Create our server.
var app = Angel(logger: Logger('angel'), reflector: MirrorsReflector());
var http = AngelHttp(app);
await app.mountController<ArtistsController>();
// Simple fallback to throw a 404 on unknown paths.
app.fallback((req, res) {
throw AngelHttpException.notFound(
2021-03-20 08:11:18 +00:00
message: 'Unknown path: "${req.uri!.path}"',
2019-07-17 19:48:02 +00:00
);
});
app.errorHandler = (e, req, res) => e.toJson();
await http.startServer('127.0.0.1', 3000);
print('Listening at ${http.uri}');
app.dumpTree();
}
class ArtistsController extends Controller {
List index() {
return ['Elvis', 'Stevie', 'Van Gogh'];
}
String getById(int id, RequestContext req) {
return 'You fetched ID: $id from IP: ${req.ip}';
}
@Expose.post
form(RequestContext req) async {
// Deserialize the body into an artist.
var artist = await req.deserializeBody((m) {
2021-03-20 08:11:18 +00:00
return Artist(name: m!['name'] as String? ?? '(unknown name)');
2019-07-17 19:48:02 +00:00
});
// Return it (it will be serialized to JSON).
return artist;
}
}
class Artist {
2021-03-20 08:11:18 +00:00
final String? name;
2019-07-17 19:48:02 +00:00
Artist({this.name});
Map<String, dynamic> toJson() {
return {'name': name};
}
}