Skip to content

gracefullight/pkgs / .agents/skills/oma-mobile

oma-mobile

Unverified

Implement Flutter, React Native, or native Swift apps. Use for mobile screens, widgets, platform integrations, and application data flows.

variants/flutter/api-template.dart

View on GitHub
/// API Repository Template for Mobile Agent (Flutter)
///
/// This file is the Flutter analogue of `variants/swift-ios/api-template.swift`.
/// It provides a complete, commented [TodoRepository] showing:
///   - The abstract repository interface (domain layer)
///   - The offline-first implementation (data layer) with stale-while-revalidate caching
///   - The Drift-backed local cache (real @DriftDatabase + @DriftAccessor DAO)
///   - The Dio-backed remote data source
///   - Cache invalidation on every write (create / toggle / delete)
///
/// This is a reference showing every layer in one place. It is NOT a
/// single-file standalone compile: the `part` directives below pull in
/// build_runner output (freezed, drift, json_serializable). In production,
/// split it into the files listed under "File layout" and run
/// `dart run build_runner build --delete-conflicting-outputs`.
///
/// Caching contract (mandatory — mirrors the swift-ios ResponseCache rules):
///   - Cache DECODED domain entities ([Todo]) at the Repository layer,
///     NOT raw HTTP bytes or JSON strings at the Dio transport layer.
///   - [TodoRepositoryImpl.watchAll] emits the locally-cached Drift rows first
///     (instant render), then revalidates from the network and re-emits via the
///     Drift stream (stale-while-revalidate). The UI renders immediately then updates.
///   - Every write ([create] / [toggle] / [delete]) upserts or removes the
///     affected Drift row after a successful network response so the stream
///     re-emits the change without a separate read round-trip.
///   - Cache key = logical operation name + params (never URLs or raw path strings).
///   - TTL is explicit ([_kCacheTtl]). No implicit or infinite cache.
///   - Secrets → flutter_secure_storage. User-authored durable data → a separate
///     Drift table. This cache is for transient server-owned data only.
///
/// File layout (split into real files in production):
///   lib/core/database/
///     app_database.dart             <- [AppDatabase] @DriftDatabase definition
///   lib/features/todos/
///     domain/
///       todo.dart                   <- [Todo] domain entity (§ Domain Entity)
///       todo_repository.dart        <- [TodoRepository] abstract interface
///     data/
///       dtos/
///         todo_dto.dart             <- [TodoDto] JSON transfer object
///       local/
///         todos_dao.dart            <- [TodosDao] Drift @DriftAccessor DAO
///       remote/
///         todos_remote_data_source.dart  <- [TodosRemoteDataSource] Dio calls
///       todo_repository_impl.dart   <- [TodoRepositoryImpl] offline-first impl
///
/// See snippets.md for the Riverpod [StreamNotifier] that consumes this repository
/// and the flutter_test + mocktail tests that stub the interface seam.

import 'package:drift/drift.dart';
import 'package:dio/dio.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:json_annotation/json_annotation.dart';

// ---------------------------------------------------------------------------
// DOMAIN ENTITY
// ---------------------------------------------------------------------------
// lib/features/todos/domain/todo.dart

part 'api-template.freezed.dart';
part 'api-template.g.dart';

/// Pure domain entity — no Drift columns, no JSON annotations, no Dio types.
/// Equality, copyWith, and toString are generated by freezed.
/// Freezed 3 requires the class to be `abstract` (or `sealed`).
@freezed
abstract class Todo with _$Todo {
  const factory Todo({
    required int id,
    required String title,
    required bool completed,
    /// Timestamp set by the Repository when the entity is written to the cache.
    /// Used to evaluate staleness against [_kCacheTtl].
    required DateTime cachedAt,
  }) = _Todo;
}

// ---------------------------------------------------------------------------
// REPOSITORY INTERFACE (domain layer)
// ---------------------------------------------------------------------------
// lib/features/todos/domain/todo_repository.dart

/// Abstract contract that the presentation layer (Riverpod providers) depends on.
///
/// Concrete implementations ([TodoRepositoryImpl], stubs, mocks) swap behind
/// this interface seam. View models and providers NEVER import [TodoRepositoryImpl],
/// [TodosRemoteDataSource], or [TodosDao] directly.
abstract interface class TodoRepository {
  /// Returns a live [Stream] of all todos.
  ///
  /// Emits the locally-cached list immediately (may be empty on first launch),
  /// then silently revalidates from the network when the cache is stale or empty.
  /// Drift re-emits the stream automatically after each upsert, so the UI
  /// updates without any explicit refresh call.
  Stream<List<Todo>> watchAll();

  /// Fetches a single todo by [id].
  ///
  /// Returns the cached entity immediately when present, revalidating from the
  /// network in the background only when it is stale (older than the TTL). A
  /// `Future` cannot re-emit — watchers of [watchAll] observe the refreshed row
  /// via the Drift stream. Returns null when the id is absent both locally and
  /// remotely (HTTP 404).
  Future<Todo?> findById(int id);

  /// Creates a new todo with the given [title].
  ///
  /// Hits the network first, then upserts the returned entity into the local
  /// Drift cache so [watchAll()] emits the new item immediately.
  Future<Todo> create(String title);

  /// Toggles the [completed] flag on the todo with the given [id].
  ///
  /// Hits the network first, then upserts the updated entity into the local cache.
  Future<Todo> toggle(int id);

  /// Permanently deletes the todo with the given [id].
  ///
  /// Hits the network first, then removes the row from the local cache so
  /// [watchAll()] emits the deletion immediately.
  Future<void> delete(int id);
}

// ---------------------------------------------------------------------------
// JSON TRANSFER OBJECT (data layer)
// ---------------------------------------------------------------------------
// lib/features/todos/data/dtos/todo_dto.dart

/// JSON ↔ Dart mapping object. Isolated from the domain entity so that
/// API shape changes don't propagate into the domain.
@JsonSerializable()
class TodoDto {
  const TodoDto({
    required this.id,
    required this.title,
    required this.completed,
  });

  final int id;
  final String title;
  final bool completed;

  factory TodoDto.fromJson(Map<String, dynamic> json) =>
      _$TodoDtoFromJson(json);

  Map<String, dynamic> toJson() => _$TodoDtoToJson(this);

  /// Converts this DTO to a domain [Todo].
  ///
  /// [cachedAt] is provided by the Repository (not the network) so that
  /// TTL comparisons use the local clock, not the server's.
  Todo toDomain({required DateTime cachedAt}) => Todo(
        id: id,
        title: title,
        completed: completed,
        cachedAt: cachedAt,
      );
}

// ---------------------------------------------------------------------------
// DRIFT TABLE (data layer — local cache)
// ---------------------------------------------------------------------------
// lib/core/database/app_database.dart  (declared alongside the AppDatabase below)

/// One Drift row per server-owned Todo.
///
/// [cachedAt] is written by the Repository at insert/upsert time.
/// It is compared against [_kCacheTtl] to decide whether to revalidate.
class TodosTable extends Table {
  IntColumn get id => integer()();
  TextColumn get title => text()();
  BoolColumn get completed =>
      boolean().withDefault(const Constant(false))();
  DateTimeColumn get cachedAt => dateTime()();

  @override
  Set<Column> get primaryKey => {id};
}

// ---------------------------------------------------------------------------
// DRIFT DATABASE + DAO (data layer — typed queries)
// ---------------------------------------------------------------------------
// lib/core/database/app_database.dart + lib/features/todos/data/local/todos_dao.dart
//
// build_runner (drift_dev) generates the row data class [TodosTableData], the
// insert/update companion [TodosTableCompanion], the [_$AppDatabase] base, and
// the [_$TodosDaoMixin] into api-template.g.dart. See snippets.md §3c for the
// same declarations with the LazyDatabase connection/open-file wiring.

@DriftDatabase(tables: [TodosTable], daos: [TodosDao])
class AppDatabase extends _$AppDatabase {
  AppDatabase(super.executor);

  @override
  int get schemaVersion => 1;
}

/// Type-safe Data Access Object for the todos cache table.
///
/// Exposes [Stream]-returning methods so [TodoRepositoryImpl] can forward
/// live Drift updates directly to Riverpod without any manual polling.
@DriftAccessor(tables: [TodosTable])
class TodosDao extends DatabaseAccessor<AppDatabase> with _$TodosDaoMixin {
  TodosDao(super.db);

  /// Live stream — Drift re-emits on every INSERT / UPDATE / DELETE on the table.
  Stream<List<TodosTableData>> watchAll() => select(todosTable).watch();

  /// Returns the most recently cached row for [id], or null if not present.
  Future<TodosTableData?> findById(int id) =>
      (select(todosTable)..where((t) => t.id.equals(id))).getSingleOrNull();

  /// Upserts a batch of rows (INSERT OR REPLACE). Additive only — use
  /// [replaceAll] to mirror a full server list.
  Future<void> upsertAll(List<TodosTableCompanion> rows) =>
      batch((b) => b.insertAllOnConflictUpdate(todosTable, rows));

  /// Replace the whole cached list with the fresh server set in ONE
  /// transaction: delete rows the server no longer returns, then upsert the
  /// rest, so server-side deletions do not linger as ghost rows.
  Future<void> replaceAll(List<TodosTableCompanion> rows) {
    return transaction(() async {
      final freshIds = rows.map((r) => r.id.value).toList();
      await (delete(todosTable)..where((t) => t.id.isNotIn(freshIds))).go();
      await batch((b) => b.insertAllOnConflictUpdate(todosTable, rows));
    });
  }

  /// Upserts a single row. Used after create / toggle.
  Future<void> upsertOne(TodosTableCompanion row) =>
      into(todosTable).insertOnConflictUpdate(row);

  /// Removes the row for [id]. Used after delete.
  Future<void> deleteById(int id) =>
      (delete(todosTable)..where((t) => t.id.equals(id))).go();
}

// ---------------------------------------------------------------------------
// REMOTE DATA SOURCE (data layer — Dio calls)
// ---------------------------------------------------------------------------
// lib/features/todos/data/remote/todos_remote_data_source.dart

/// All Dio HTTP calls for the /todos resource.
///
/// This class is transport-only — no caching, no domain types.
/// It maps HTTP responses to [TodoDto] and surfaces [DioException] on failure.
/// Interceptors (auth, retry, logging) are registered on the [Dio] instance
/// in `core/network/dio_client.dart`, not here.
class TodosRemoteDataSource {
  TodosRemoteDataSource(this._dio);

  final Dio _dio;

  /// GET /todos — returns the full list.
  Future<List<TodoDto>> fetchAll() async {
    final response = await _dio.get<List<dynamic>>('/todos');
    return (response.data ?? [])
        .map((json) => TodoDto.fromJson(json as Map<String, dynamic>))
        .toList();
  }

  /// GET /todos/:id — returns a single item.
  Future<TodoDto> fetchById(int id) async {
    final response =
        await _dio.get<Map<String, dynamic>>('/todos/$id');
    return TodoDto.fromJson(response.data!);
  }

  /// POST /todos — creates a new item with the given [title].
  Future<TodoDto> create(String title) async {
    final response = await _dio.post<Map<String, dynamic>>(
      '/todos',
      data: {'title': title},
    );
    return TodoDto.fromJson(response.data!);
  }

  /// PATCH /todos/:id/toggle — flips the completed flag.
  Future<TodoDto> toggle(int id) async {
    final response = await _dio
        .patch<Map<String, dynamic>>('/todos/$id/toggle');
    return TodoDto.fromJson(response.data!);
  }

  /// DELETE /todos/:id — permanently removes the item.
  Future<void> delete(int id) => _dio.delete<void>('/todos/$id');
}

// ---------------------------------------------------------------------------
// OFFLINE-FIRST REPOSITORY IMPLEMENTATION (data layer)
// ---------------------------------------------------------------------------
// lib/features/todos/data/todo_repository_impl.dart

/// How long a cached list is considered fresh before a background revalidation
/// is triggered. Adjust per resource; NEVER use Duration.zero or "infinite".
const Duration _kCacheTtl = Duration(minutes: 5);

/// Offline-first implementation of [TodoRepository].
///
/// # Caching contract
///
/// ## Reads (stale-while-revalidate)
/// [watchAll] and [findById] emit the locally-cached Drift data first.
/// A background revalidation is triggered whenever the cache is empty or
/// older than [_kCacheTtl]. After the network response is upserted into
/// Drift, the DAO stream re-emits automatically — the UI updates without
/// any explicit refresh call.
///
/// ## Writes (invalidate-on-write)
/// [create] and [toggle] hit the network first, then upsert the returned
/// entity into Drift so the stream emits the change instantly.
/// [delete] hits the network first, then removes the Drift row so the
/// stream emits the deletion instantly.
///
/// ## Key strategy
/// Cache key = the DAO method name + the primary-key param (where applicable).
/// Examples: "watchAll" → the full [TodosTable]; "findById:42" → a single row.
/// Never key on URLs or path strings.
///
/// ## Boundaries
/// This class caches transient server-owned data only. Secrets belong in
/// [FlutterSecureStorage]. Durable user-authored data belongs in a separate
/// Drift table with an independent retention policy.
class TodoRepositoryImpl implements TodoRepository {
  TodoRepositoryImpl({
    required TodosDao dao,
    required TodosRemoteDataSource remote,
  })  : _dao = dao,
        _remote = remote;

  final TodosDao _dao;
  final TodosRemoteDataSource _remote;

  // ---------------------------------------------------------------------------
  // READ — stale-while-revalidate
  // ---------------------------------------------------------------------------

  @override
  Stream<List<Todo>> watchAll() async* {
    // 1. Read the current cache snapshot to determine staleness.
    final snapshot = await _dao.watchAll().first;
    final now = DateTime.now();

    // 2. Trigger background revalidation if cache is empty or stale.
    // `ignore()` is intentional — failure is non-fatal when the cache is warm.
    if (_isStaleOrEmpty(snapshot, now)) {
      _revalidateAll(now).ignore();
    }

    // 3. Forward the live Drift stream; it re-emits after every upsert.
    yield* _dao.watchAll().map(
          (rows) => rows.map(_rowToEntity).toList(),
        );
  }

  @override
  Future<Todo?> findById(int id) async {
    final cached = await _dao.findById(id);
    final now = DateTime.now();

    if (cached != null) {
      // Serve the cached row immediately. Revalidate in the background only
      // when it is stale; watchers of watchAll() observe the refreshed row via
      // the Drift stream. This Future returns the cached snapshot as-is.
      if (now.difference(cached.cachedAt) > _kCacheTtl) {
        _revalidateById(id, now).ignore();
      }
      return _rowToEntity(cached);
    }

    // Cache miss — fetch from network and persist.
    try {
      final dto = await _remote.fetchById(id);
      await _dao.upsertOne(_dtoToCompanion(dto, cachedAt: now));
      return dto.toDomain(cachedAt: now);
    } on DioException catch (e) {
      if (e.response?.statusCode == 404) return null;
      rethrow;
    }
  }

  // ---------------------------------------------------------------------------
  // WRITE — upsert / delete after success
  // ---------------------------------------------------------------------------

  @override
  Future<Todo> create(String title) async {
    // Network first; cache on success.
    final dto = await _remote.create(title);
    final now = DateTime.now();
    await _dao.upsertOne(_dtoToCompanion(dto, cachedAt: now));
    // watchAll() stream auto-emits the new row via Drift.
    return dto.toDomain(cachedAt: now);
  }

  @override
  Future<Todo> toggle(int id) async {
    // Network first; upsert updated entity on success.
    final dto = await _remote.toggle(id);
    final now = DateTime.now();
    await _dao.upsertOne(_dtoToCompanion(dto, cachedAt: now));
    // watchAll() stream auto-emits the updated row via Drift.
    return dto.toDomain(cachedAt: now);
  }

  @override
  Future<void> delete(int id) async {
    // Network first; remove local row on success.
    await _remote.delete(id);
    await _dao.deleteById(id);
    // watchAll() stream auto-emits the deletion via Drift.
  }

  // ---------------------------------------------------------------------------
  // Private helpers
  // ---------------------------------------------------------------------------

  bool _isStaleOrEmpty(List<TodosTableData> rows, DateTime now) {
    if (rows.isEmpty) return true;
    // Revalidate the whole list if any row is older than the TTL.
    return rows.any((row) => now.difference(row.cachedAt) > _kCacheTtl);
  }

  Future<void> _revalidateAll(DateTime now) async {
    try {
      final dtos = await _remote.fetchAll();
      // replaceAll (not upsertAll): mirror the full server list so rows the
      // server deleted are removed instead of lingering as ghost rows.
      await _dao.replaceAll(
        dtos.map((dto) => _dtoToCompanion(dto, cachedAt: now)).toList(),
      );
    } catch (_) {
      // Network failure is non-fatal when the cache is warm.
      // The existing stream emission (stale data) stands silently.
    }
  }

  Future<void> _revalidateById(int id, DateTime now) async {
    try {
      final dto = await _remote.fetchById(id);
      await _dao.upsertOne(_dtoToCompanion(dto, cachedAt: now));
    } catch (_) {
      // Non-fatal — caller already received the cached value.
    }
  }

  /// Maps a Drift row to a domain [Todo].
  Todo _rowToEntity(TodosTableData row) => Todo(
        id: row.id,
        title: row.title,
        completed: row.completed,
        cachedAt: row.cachedAt,
      );

  /// Maps a [TodoDto] to a Drift [TodosTableCompanion] for upsert.
  /// `cachedAt` is stamped from the local clock by the Repository, not the DTO.
  TodosTableCompanion _dtoToCompanion(
    TodoDto dto, {
    required DateTime cachedAt,
  }) =>
      TodosTableCompanion(
        id: Value(dto.id),
        title: Value(dto.title),
        completed: Value(dto.completed),
        cachedAt: Value(cachedAt),
      );
}
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 197kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall