-
Notifications
You must be signed in to change notification settings - Fork 40
/
api_helper_builder.dart
55 lines (49 loc) · 2.13 KB
/
api_helper_builder.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import 'package:build/build.dart';
import 'package:dart_style/dart_style.dart';
import 'api_builder.dart';
Builder apiHelperBuilder(final BuilderOptions _) => APIHelperBuilder();
/// A Code generator class runs after [APIBuilder] for generating the `api.helper.dart`
///
/// The generated file includes the function `getResponseByMsgType` which instantiates
/// the appropriate sub-class of [Response] based on its [Response.msgType]
class APIHelperBuilder extends Builder {
@override
Map<String, List<String>> get buildExtensions => const <String, List<String>>{
'.dart': <String>['.helper.dart']
};
@override
Future<void> build(BuildStep buildStep) async {
try {
generatedResponses.sort();
await buildStep.writeAsString(
buildStep.inputId.changeExtension('.helper.dart'),
DartFormatter().format(
'''
// AUTO-GENERATED - DO NOT MODIFY BY HAND
// Auto generated from 1st step of the flutter_deriv_api code generation process
// uses collected `msg_type`s from the 1st step to create a helper
// function that maps the `msg_type`s to equivalent Response objects
${generatedResponses.map((GeneratedResponseJson? response) => 'import \'../${response!.isManual ? 'manually' : 'generated'}/${response.fileName}.dart\';').join('\n')}
import '../response.dart';
/// A function that create a sub-type of [Response] based on
/// [responseMap]'s 'msg_type'
Response getGeneratedResponse(Map<String, dynamic> responseMap) {
switch (responseMap['msg_type']) {
${generatedResponses.map((GeneratedResponseJson response) => '''case '${response.msgType}':
return ${response.fullClassName}.fromJson(responseMap);
''').join()}
default:
return Response.fromJson(responseMap);
}
}
''',
),
);
} on Exception catch (e, stack) {
log
..severe('Failed to process ${buildStep.inputId} - $e')
..severe('Stack trace $stack');
return;
}
}
}