Last active
September 20, 2022 12:48
-
-
Save graphicbeacon/9fb6c6a951168d6a31d9b2cc442bcbe2 to your computer and use it in GitHub Desktop.
Solution for "Understanding Reflection in Dart" video tutorial on YouTube
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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