buildOpenApiSpec function

Map<String, dynamic> buildOpenApiSpec(
  1. SwaggerServer server,
  2. SchemaRegistry registry
)

Implementation

Map<String, dynamic> buildOpenApiSpec(
  SwaggerServer server,
  SchemaRegistry registry,
) {
  final paths = <String, dynamic>{};

  for (final controller in server.visibleControllers) {
    for (final method in controller.methods) {
      if (method.isHidden) continue;

      final fullPath = _buildFullPath(controller.path, method.path);
      final pathItem =
          paths.putIfAbsent(fullPath, () => <String, dynamic>{})
              as Map<String, dynamic>;

      pathItem[method.httpMethod] = _buildOperation(
        controller,
        method,
        registry,
        fullPath,
      );
    }
  }

  final schemasMap = registry.schemasMap;

  if (schemasMap.isEmpty) {
    return {
      'openapi': '3.0.3',
      'info': {
        'title': server.info.title,
        'version': server.info.version,
        if (server.info.description case final String d) 'description': d,
      },
      'paths': paths,
    };
  }

  // Prune schemas that are never $ref'd from paths or other reachable schemas.
  final referenced = <String>{};
  _collectRefs(paths, referenced);
  // Also collect refs within schemas themselves (transitive reachability).
  var changed = true;
  while (changed) {
    changed = false;
    for (final entry in schemasMap.entries) {
      if (referenced.contains(entry.key)) {
        final before = referenced.length;
        _collectRefs(entry.value, referenced);
        if (referenced.length > before) changed = true;
      }
    }
  }
  final prunedSchemas = {
    for (final entry in schemasMap.entries)
      if (referenced.contains(entry.key)) entry.key: entry.value,
  };

  return {
    'openapi': '3.0.3',
    'info': {
      'title': server.info.title,
      'version': server.info.version,
      if (server.info.description case final String d) 'description': d,
    },
    'paths': paths,
    if (prunedSchemas.isNotEmpty) 'components': {'schemas': prunedSchemas},
  };
}