93 lines
3.0 KiB
Dart
93 lines
3.0 KiB
Dart
import 'package:EasyDartModule/base/webserver/WebServer.dart';
|
|
import 'package:build/build.dart';
|
|
import 'package:analyzer/dart/element/element.dart';
|
|
import 'package:source_gen/source_gen.dart';
|
|
import 'package:path/path.dart';
|
|
|
|
Builder routeGenerator(BuilderOptions options) {
|
|
return LibraryBuilder(
|
|
RouteGenerator(),
|
|
generatedExtension: '.route.dart',
|
|
);
|
|
}
|
|
|
|
class RouteGenerator extends GeneratorForAnnotation<RequestMapping> {
|
|
call(String name) {}
|
|
@override
|
|
generateForAnnotatedElement(
|
|
Element element, ConstantReader annotation, BuildStep buildStep) {
|
|
// 读取注解字段
|
|
String path = annotation.read('path').stringValue;
|
|
String method = annotation.read('method').read("_name").stringValue;
|
|
// String response = annotation.read("responseType").read("_name").stringValue;
|
|
// print("url:$path $method");
|
|
//0:路径 1:响应类型 2:调用函数 3:参数数量
|
|
Map<HttpMethod, List> routes = {};
|
|
if (method != HttpMethod.WS.name) {
|
|
if (path.endsWith("/")) {
|
|
path = path.substring(0, path.length - 1);
|
|
}
|
|
for (final method in element.children) {
|
|
for (final metaData in method.metadata) {
|
|
var anno = ConstantReader(metaData.computeConstantValue());
|
|
if (!anno.instanceOf(typeChecker)) {
|
|
continue;
|
|
}
|
|
|
|
int pl = (method as MethodElement).parameters.length;
|
|
// print(
|
|
// "url:$path-${anno.read("path").stringValue} method:${anno.read("method").read("_name").stringValue} response:${anno.read("responseType").read("_name").stringValue}");
|
|
//转换为枚举类型
|
|
|
|
var p = anno.read("path").stringValue;
|
|
if (!p.startsWith("/")) {
|
|
p = "$path/$p";
|
|
} else {
|
|
p = path + p;
|
|
}
|
|
//加入调用缓存
|
|
var mtd =
|
|
HttpMethod.valueOf(anno.read("method").read("_name").stringValue);
|
|
var list = routes[mtd];
|
|
if (list == null) {
|
|
list = [];
|
|
routes[mtd] = list;
|
|
}
|
|
list.add([
|
|
p,
|
|
HttpResponseType.valueOf(
|
|
anno.read("responseType").read("_name").stringValue),
|
|
() {
|
|
return method.name;
|
|
},
|
|
pl >= 2 ? 2 : 1
|
|
]);
|
|
}
|
|
// print("构建完毕");
|
|
}
|
|
} else {
|
|
//单独处理ws
|
|
routes[HttpMethod.valueOf(method)] = [[path]];
|
|
}
|
|
// 生成路由映射代码
|
|
final routesMapString = routes.entries.map((entry) {
|
|
return '${entry.key}: [${entry.value.map((e) {
|
|
return '[${e.map((f) {
|
|
if (f is String) {
|
|
return '"$f"';
|
|
} else if (f is Function) {
|
|
return "_callHandler.${f()}";
|
|
}
|
|
return f;
|
|
}).join(",")}]';
|
|
}).join(",")}],';
|
|
}).join('\n');
|
|
// print(routes);
|
|
return '''
|
|
part of '${basename(buildStep.inputId.path)}';
|
|
late var _callHandler;
|
|
final Map<HttpMethod, List<List>> routes = {$routesMapString};
|
|
''';
|
|
}
|
|
}
|