extractInlineResponseSchemas method

Map<String, dynamic> extractInlineResponseSchemas()

Implementation

Map<String, dynamic> extractInlineResponseSchemas() {
  final paths = getPaths();
  final Map<String, dynamic> inlineSchemas = {};

  paths.forEach((path, methods) {
    final cleanPath =
        path
            .split('/')
            .where(
              (segment) => segment.isNotEmpty && !segment.startsWith('{'),
            )
            .join('')
            .capitalize;

    final defaultModelName =
        cleanPath.isNotEmpty ? '${cleanPath}Response' : 'GenericResponse';

    methods.forEach((method, details) {
      final responses = details['responses'] ?? {};

      responses.forEach((code, responseDetail) {
        final schema =
            responseDetail['content']?['application/json']?['schema'];

        if (schema == null) return;

        // Object inline response
        if (schema['type'] == 'object' && schema['\$ref'] == null) {
          inlineSchemas[defaultModelName] = schema;
          return;
        }

        // Array with $ref items
        if (schema['type'] == 'array' && schema['items']?['\$ref'] != null) {
          final ref = schema['items']['\$ref'].split('/').last;

          final listModelName =
              '${ref.toString().pluralToSingular}ListResponse';

          inlineSchemas[listModelName] = {
            'type': 'object',
            'properties': {
              'items': {
                'type': 'array',
                'items': {'\$ref': '#/components/schemas/$ref'},
              },
            },
          };
          return;
        }

        // Array with inline object items
        if (schema['type'] == 'array' &&
            schema['items'] != null &&
            schema['items']['\$ref'] == null &&
            schema['items']['type'] == 'object') {
          final itemModelName = '${defaultModelName}Item';

          final listModelName = '${defaultModelName}ItemListResponse';

          inlineSchemas[itemModelName] = schema['items'];

          inlineSchemas[listModelName] = {
            'type': 'object',
            'properties': {
              'items': {
                'type': 'array',
                'items': {'\$ref': '#/components/schemas/$itemModelName'},
              },
            },
          };
        }
      });
    });
  });

  return inlineSchemas;
}