readRef function

Future<Map> readRef(
  1. Uri uri,
  2. Map document,
  3. String ref, {
  4. Map<String, Map>? cache,
})

Implementation

Future<Map<dynamic, dynamic>> readRef(
  Uri uri,
  Map<dynamic, dynamic> document,
  String ref, {
  Map<String, Map<dynamic, dynamic>>? cache,
}) async {
  Map<dynamic, dynamic>? pendingData;
  if (cache != null) {
    pendingData = cache[ref];
    if (pendingData != null) return pendingData;
    cache[ref] = pendingData = {};
  }

  final index = ref.indexOf('#');
  final documentRef = index != -1 ? ref.substring(index + 2) : null;
  final fileRef = index != 0 ? ref.substring(0, index == -1 ? null : index) : null;

  if (fileRef != null) {
    final parent = _uri.dirname(uri.path);
    uri = uri.replace(path: _uri.normalize(_uri.join(parent, fileRef)));
    document = await readOpenApiWithRefs(uri);
  }

  var data = document;
  if (documentRef != null) {
    final segments = documentRef.split('/');
    for (final segment in segments) {
      data = data[segment] as Map<dynamic, dynamic>;
    }
    if (!data.containsKey('title')) data = {'title': segments.last, ...data};
  }

  final resolvedData = await _resolveDocumentRefs(uri, document, data, cache: cache);

  if (pendingData != null) {
    pendingData.addAll(resolvedData! as Map<dynamic, dynamic>);
    return pendingData;
  } else {
    return resolvedData! as Map<dynamic, dynamic>;
  }
}