SwaggerPath.fromResponse constructor

SwaggerPath.fromResponse(
  1. RequestOptions requestOptions,
  2. List<SwaggerSecurity> securities,
  3. Response? response, {
  4. bool includeResponse = false,
  5. List<RegExp> pathRegs = const [],
})

Implementation

factory SwaggerPath.fromResponse(
  RequestOptions requestOptions,
  List<SwaggerSecurity> securities,
  Response? response, {
  bool includeResponse = false,
  List<RegExp> pathRegs = const [],
}) {
  String _path = '';
  final Map<String, dynamic> _queryParams = requestOptions.queryParameters;
  if (requestOptions.extra.containsKey('path')) {
    _path = requestOptions.extra['path'];
    RegExp(r'\{(.*?)\}').allMatches(_path).forEach((e) {
      final _param = _path.substring(e.start + 1, e.end - 1);
      _queryParams.putIfAbsent(
        _param,
        () => {
          'in': 'path',
          'type': 'string',
        },
      );
    });
  } else {
    final _splitPaths = requestOptions.path.split('?');
    _path = _splitPaths.first;
    final _pathQueryParam =
        _splitPaths.length == 2 ? requestOptions.path.split('?').last : null;
    if (_pathQueryParam != null) {
      _queryParams.addAll(Uri.splitQueryString(_pathQueryParam));
    }
    final List<String> _segments = Uri.dataFromString(_path).pathSegments;
    for (int i = 0; i < _segments.length; i++) {
      final _segment = _segments[i];
      for (final _reg in pathRegs) {
        _reg.allMatches(_segment).forEach((e) {
          final _id = e.group(0);
          if (_id != null) {
            final _paramName =
                i == 0 ? 'id${i + 1}' : '${_segments[i - 1]}Id';
            _path = _path.replaceFirst(_id, '{$_paramName}');
            _queryParams.putIfAbsent(
              _paramName,
              () => {
                'in': 'path',
                'type': 'string',
              },
            );
          }
        });
      }
    }
  }
  final _requestBody = requestOptions.data;
  final List<Map<String, dynamic>> _security = [];
  requestOptions.headers.forEach((key, _) {
    final _index = securities.indexWhere((s) => s.name == key);
    if (_index != -1) {
      _security.add({key: []});
    }
  });
  return SwaggerPath(
    path: _path,
    tag: Uri.dataFromString(_path).pathSegments[1],
    method: requestOptions.method,
    summary: requestOptions.extra['summary'],
    description: requestOptions.extra['description'],
    responses: [
      SwaggerResponse(
        statusCode: (response?.statusCode ?? 0).toString(),
        statusMessage: response?.statusMessage ?? '',
        response: response != null ? SwaggerContent(response.data) : null,
      )
    ],
    requestBody: _requestBody != null ? SwaggerContent(_requestBody) : null,
    queryParams: _queryParams.isNotEmpty ? SwaggerQuery(_queryParams) : null,
    headers: _security,
    includeResponse: includeResponse,
  );
}