Skip to content

Instantly share code, notes, and snippets.

@graphicbeacon graphicbeacon/main.dart
Last active Jul 8, 2019

Embed
What would you like to do?
Solution for "Understanding Reflection in Dart" video tutorial on YouTube
import 'dart:io';
import 'dart:mirrors';
main() async {
var server = await HttpServer.bind('localhost', 8085);
await for (HttpRequest req in server) {
// Create InstanceMirror type from which
// we retrieve metadata information
var ref = reflect(Endpoint(req));
var path = req.uri.path;
var routeAnnotation = ref.type.metadata
.firstWhere((meta) => meta.reflectee is Route, orElse: () => null);
if (routeAnnotation != null && path == (routeAnnotation.reflectee as Route).url) {
ref.type.instanceMembers.forEach((_, member) {
// Make initial checks to target the correct members
if (member.isOperator ||
!member.isRegularMethod ||
member.owner.simpleName != #Endpoint) return;
// Read the @RouteMethod annotations
var routeMethod = member.metadata.firstWhere(
(meta) => meta.reflectee is RouteMethod,
orElse: () => null);
// Match correct @RouteMethod and...
if (routeMethod != null && (routeMethod.reflectee as RouteMethod).method == req.method) {
print(member.simpleName);
// ...invoke instance method
ref.invoke(member.simpleName, []);
}
});
}
await req.response.close();
}
}
// Annotations
class Route {
const Route(this.url);
final String url;
}
class RouteMethod {
const RouteMethod(this.method);
const RouteMethod.get() : this('GET');
const RouteMethod.post() : this('POST');
const RouteMethod.put() : this('PUT');
const RouteMethod.delete() : this('DELETE');
final String method;
}
// Annotated class
@Route('/')
class Endpoint {
Endpoint(this._req);
final HttpRequest _req;
@RouteMethod.get()
handleGet() => _req.response.write('Got GET request.');
@RouteMethod.post()
handlePost() => _req.response.write('Got POST request.');
@RouteMethod.put()
handlePut() => _req.response.write('Got PUT request.');
@RouteMethod.delete()
handleDelete() => _req.response.write('Got DELETE request.');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.