generateApi method
Implementation
Future<void> generateApi(Map<String, dynamic> json) async {
final paths = json['paths'] as Map<String, dynamic>;
const indent = ' ';
final api = StringBuffer('// import \'package:get/get.dart\';\n');
api.writeln('import \'models.dart\';\n');
api.writeln('''
abstract class GetConnect {
get(path, {query}) {}
onInit() {}
post(path, body) {}
put(path, body) {}
delete(path) {}
}
class ApiProvider extends GetConnect {
@override
void onInit() {
// httpClient.baseUrl = 'https://api.github.com';
}
''');
for (final entry in paths.entries) {
final path = entry.key;
final methods = entry.value as Map<String, dynamic>;
for (final methodEntry in methods.entries) {
final method = methodEntry.key.toUpperCase();
final operation = methodEntry.value as Map<String, dynamic>;
final summary = operation['summary'] as String?;
final description = operation['description'] as String?;
final operationId = operation['operationId'] as String?;
final parameters = operation['parameters'] as List<dynamic>?;
final pathParams =
parameters?.where((p) => p['in'] == 'path').toList() ?? [];
final queryParams =
parameters?.where((p) => p['in'] == 'query').toList() ?? [];
final formDataParams =
parameters?.where((p) => p['in'] == 'formData').toList() ?? [];
final bodyParams =
parameters?.where((p) => p['in'] == 'body').toList() ?? [];
final bodyParam = (bodyParams.isNotEmpty ? bodyParams.first : null)
as Map<String, dynamic>?;
final responses = operation['responses'] as Map<String, dynamic>?;
final successResponse = responses?.remove('200') ??
responses?.values.first as Map<String, dynamic>?;
if (summary != null) {
api.writeln('$indent/// $summary');
}
if (description != null) {
api.writeln('$indent/// $description');
}
if (operationId != null) {
api.writeln('$indent/// Operation ID: $operationId');
}
if (formDataParams.isNotEmpty) {
api.write('$indent/// body type: ');
for (final param in formDataParams) {
final name = param['name'] as String;
final type = _mapType(param);
final require = param['required'] as bool?;
api.write(
' ${require != null && require ? 'required ' : ''}$type $name,');
}
api.writeln('}');
}
var hasResponse = !(successResponse == null ||
['post', 'put'].contains(method) ||
_getClassName(successResponse) == null);
if (!hasResponse) {
api.write(' Future $operationId(');
} else {
api.write(
'${indent}Future<${_getClassName(successResponse)}> $operationId(');
}
var hasPathParam = false;
for (final param in pathParams) {
final name = param['name'] as String;
final type = _mapType(param);
api.write('$type $name');
hasPathParam = true;
}
var hasBrace = false;
if (queryParams.isNotEmpty) {
api.writeln('${hasPathParam ? ', ' : ''}{');
for (final param in queryParams) {
final name = param['name'] as String;
final type = _mapType(param);
final require = param['required'] as bool?;
api.write(
'${indent * 3}${require != null && require ? 'required ' : ''}$type $name,');
}
hasBrace = true;
}
if (formDataParams.isNotEmpty) {
api.writeln('${hasPathParam ? ', ' : ''}{');
api.writeln('${indent * 3}required Map<String, dynamic> body');
hasBrace = true;
}
if (bodyParam != null) {
if (!hasBrace) api.writeln('${hasPathParam ? ', ' : ''}{');
final type = _mapType(bodyParam['schema']);
final require = bodyParam['required'] as bool?;
api.writeln(
'${indent * 3}${require != null && require ? 'required ' : ''}$type body,');
hasBrace = true;
}
if (hasBrace) api.write('$indent}');
api.writeln(') async {');
var reqPath = path;
for (final param in pathParams) {
final name = param['name'] as String;
if (reqPath.contains('{$name}')) {
reqPath = reqPath.replaceAll('{$name}', '\$$name');
} else {
reqPath += reqPath.endsWith('/') ? '\${$name}' : '/\${$name}';
}
}
var queryStr = '';
if (queryParams.isNotEmpty) {
StringBuffer strBuffer = StringBuffer('{');
for (final param in queryParams) {
final name = param['name'] as String;
strBuffer.write('\'$name\': $name,');
}
strBuffer.write('}');
queryStr = strBuffer.toString();
}
api.write(
' ${hasResponse ? 'final res =' : ''} await ${method.toLowerCase()}(\'$reqPath\'');
if (bodyParam != null || formDataParams.isNotEmpty) {
api.write(', body');
}
if (queryStr.isNotEmpty) api.write(', query: $queryStr');
api.writeln(');');
// if (hasRequestBody) {
// final requestBodyType =
// _getClassName(operationId ?? '${path.toCapitalCase()}Request');
// api.writeln(' request.body = json.encode(requestBody.toJson());');
// }
if (hasResponse && _getClassName(successResponse) != null) {
var resName = _getClassName(successResponse)!;
if (resName.startsWith('List')) {
var type = resName.substring(5, resName.length - 1);
api.writeln(
' return res.body[\'data\'].map((e) => $type.fromJson(e)).toList() as $resName;');
} else if (baseType.contains(resName)) {
api.writeln(' return res.body[\'data\'];');
} else {
api.writeln(' return $resName.fromJson(res.body[\'data\']);');
}
}
api.writeln(' }\n');
}
}
api.writeln('}');
final filePath = '$outputDir/api.dart';
final file = File(filePath);
await generateFile(file, api.toString());
}