repositoryTemplate function

String repositoryTemplate(
  1. String name,
  2. ProjectContext ctx
)

A repository. When the network module is installed it extends BaseRepository and uses the shared APIProvider; otherwise it emits a self-contained stub with TODOs so the file still compiles.

Implementation

String repositoryTemplate(String name, ProjectContext ctx) {
  final className = '${Naming.pascal(name)}Repository';
  final modelName = Naming.pascal(name);
  final pkg = ctx.packageName ?? 'app';
  final endpointConst = Naming.camel(name);

  if (ctx.hasNetwork) {
    return '''
import 'package:$pkg/data/models/${Naming.snake(name)}_model.dart';
import '../provider/network/api_endpoints.dart';
import 'repository.dart';

/// Repository for $modelName resources. Add the matching paths to
/// [ApiEndPoints] (e.g. `static const String $endpointConst = '$endpointConst';`).
class $className extends BaseRepository {
  Future<List<$modelName>> fetchAll() async {
    final response = await api.get(ApiEndPoints.$endpointConst);
    final list = (response as List).cast<Map<String, dynamic>>();
    return list.map($modelName.fromJson).toList();
  }

  Future<$modelName> fetchById(String id) async {
    final response = await api.get('\${ApiEndPoints.$endpointConst}/\$id');
    return $modelName.fromJson(response as Map<String, dynamic>);
  }

  Future<$modelName> create($modelName item) async {
    final response = await api.post(
      ApiEndPoints.$endpointConst,
      body: item.toJson(),
    );
    return $modelName.fromJson(response as Map<String, dynamic>);
  }

  Future<$modelName> update(String id, $modelName item) async {
    final response = await api.put(
      '\${ApiEndPoints.$endpointConst}/\$id',
      body: item.toJson(),
    );
    return $modelName.fromJson(response as Map<String, dynamic>);
  }

  Future<void> delete(String id) =>
      api.delete('\${ApiEndPoints.$endpointConst}/\$id');
}
''';
  }

  return '''
import 'package:$pkg/data/models/${Naming.snake(name)}_model.dart';

/// Repository for $modelName resources.
///
/// The `network` module is not installed, so these methods are stubs. Run
/// `river_cli init --modules network` to wire this up to the Dio APIProvider.
class $className {
  Future<List<$modelName>> fetchAll() async {
    // TODO: fetch from your data source.
    return <$modelName>[];
  }

  Future<$modelName> fetchById(String id) {
    throw UnimplementedError('fetchById is not implemented yet.');
  }

  Future<$modelName> create($modelName item) async => item;

  Future<$modelName> update(String id, $modelName item) async => item;

  Future<void> delete(String id) async {}
}
''';
}