emkore 0.3.3 copy "emkore: ^0.3.3" to clipboard
emkore: ^0.3.3 copied to clipboard

Clean Architecture core library for Dart with use cases, entities, validation, authorization, and interceptor pipelines.

example/example.dart

/// Comprehensive emkore example demonstrating Clean Architecture patterns
///
/// This example shows the complete emkore workflow including:
/// - Entity definition with system fields
/// - Use case interfaces and interactors
/// - Repository pattern with Unit of Work
/// - Validation and error handling
/// - Multitenancy support
/// - Full CRUD operations
library;

import 'package:emkore/emkore.dart' as emkore;

// Import example implementation
import 'usecase/example/interface/create_example.usecase.dart';
import 'usecase/example/interface/retrieve_example.usecase.dart';
import 'usecase/example/interface/list_example.usecase.dart';
import 'usecase/example/interface/update_example.usecase.dart';
import 'usecase/example/interface/delete_example.usecase.dart';

import 'usecase/example/create_example.interactor.dart';
import 'usecase/example/retrieve_example.interactor.dart';
import 'usecase/example/list_example.interactor.dart';
import 'usecase/example/update_example.interactor.dart';
import 'usecase/example/delete_example.interactor.dart';

import 'repository/example/memory/example.uow.dart';

/// Example Actor with comprehensive permissions
class ExampleActor extends emkore.Actor {
  @override
  final String id;

  @override
  final String businessId;

  @override
  final String token;

  ExampleActor({
    required this.id,
    required this.businessId,
    this.token = 'example_token',
  }) {
    permissions = [
      emkore.Permission(resource: 'example', action: 'create'),
      emkore.Permission(resource: 'example', action: 'retrieve'),
      emkore.Permission(resource: 'example', action: 'list'),
      emkore.Permission(resource: 'example', action: 'update'),
      emkore.Permission(resource: 'example', action: 'delete'),
    ];
  }
}

/// Demonstrates complete CRUD workflow with emkore
void main() async {
  print('πŸ—οΈ Emkore Clean Architecture - Complete Example\n');

  // 1. Setup: Create UnitOfWork factory and interactors
  final uowFactory = InMemoryExampleUnitOfWorkFactory();
  final createInteractor = CreateExampleInteractor(uowFactory);
  final retrieveInteractor = RetrieveExampleInteractor(uowFactory);
  final listInteractor = ListExampleInteractor(uowFactory);
  final updateInteractor = UpdateExampleInteractor(uowFactory);
  final deleteInteractor = DeleteExampleInteractor(uowFactory);

  // 2. Create actor with permissions (demonstrates multitenancy)
  final actor = ExampleActor(
    id: 'user_example_001',
    businessId: 'company_example_001',
  );

  print('πŸ‘€ Actor: ${actor.id} (Business: ${actor.businessId})');
  print('πŸ”‘ Permissions: ${actor.permissions.length} granted\n');

  try {
    // 3. CREATE: Demonstrate entity creation with validation
    print('πŸ“ Step 1: Creating new example entity...');
    final createInput = CreateExampleInput(
      name: 'Example Product',
      description: 'A sample product demonstrating emkore patterns',
      count: 100,
      price: 2500, // $25.00 in cents
      isActive: true,
      owner: emkore.ResourceScope.business,
    );

    final created = await createInteractor.execute(
      actor: actor,
      input: createInput,
    );

    print('βœ… Created: ${created.name} (ID: ${created.id})');
    print('   Description: ${created.description}');
    print('   Price: \$${(created.price / 100).toStringAsFixed(2)}');
    print('   Count: ${created.count}');
    print('   Active: ${created.isActive}\n');

    // 4. RETRIEVE: Get the created entity
    print('πŸ” Step 2: Retrieving created entity...');
    final retrieveInput = RetrieveExampleInput(created.id);
    final retrieved = await retrieveInteractor.execute(
      actor: actor,
      input: retrieveInput,
    );

    print('βœ… Retrieved: ${retrieved.name}');
    print('   Created at: ${retrieved.createdAt}');
    print('   Owner ID: ${retrieved.ownerId}\n');

    // 5. LIST: Demonstrate filtering and pagination
    print('πŸ“‹ Step 3: Listing entities with filtering...');
    final listInput = ListExampleInput(isActive: true, limit: 10, offset: 0);
    final entities = await listInteractor.execute(
      actor: actor,
      input: listInput,
    );

    print('βœ… Found ${entities.length} active entities:');
    for (final entity in entities) {
      print(
        '   - ${entity.name} (\$${(entity.price / 100).toStringAsFixed(2)})',
      );
    }
    print('');

    // 6. UPDATE: Modify the entity
    print('✏️ Step 4: Updating entity...');
    final updateInput = UpdateExampleInput(
      id: created.id,
      name: 'Updated Product Name',
      description: 'Updated description showing entity modification',
      count: 150,
      price: 3000, // $30.00
      isActive: true,
    );

    final updated = await updateInteractor.execute(
      actor: actor,
      input: updateInput,
    );

    print('βœ… Updated: ${updated.name}');
    print('   New price: \$${(updated.price / 100).toStringAsFixed(2)}');
    print('   New count: ${updated.count}');
    print('   Updated at: ${updated.updatedAt}\n');

    // 7. DELETE: Clean up
    print('πŸ—‘οΈ Step 5: Deleting entity...');
    final deleteInput = DeleteExampleInput(created.id);
    await deleteInteractor.execute(actor: actor, input: deleteInput);

    print('βœ… Entity deleted successfully\n');

    // 8. Verify deletion
    print('πŸ” Step 6: Verifying deletion...');
    final finalList = await listInteractor.execute(
      actor: actor,
      input: ListExampleInput(limit: 10),
    );

    print('βœ… Verification complete: ${finalList.length} entities remaining\n');
  } catch (e) {
    print('❌ Error occurred: $e\n');

    if (e is emkore.ValidationException) {
      print('πŸ’‘ This was a validation error - check your input data');
    } else if (e is emkore.AuthorizationException) {
      print('πŸ’‘ This was an authorization error - check actor permissions');
    } else if (e is emkore.EntityNotFoundException) {
      print('πŸ’‘ The requested entity was not found');
    }
  }

  // 9. Demonstrate validation error handling
  print('🚨 Step 7: Demonstrating validation error handling...');
  try {
    final invalidInput = CreateExampleInput(
      name: '', // Invalid: empty name
      description: 'x' * 300, // Invalid: too long
      count: -1, // Invalid: negative count
      price: -100, // Invalid: negative price
      isActive: false,
      owner: emkore.ResourceScope.business,
    );

    await createInteractor.execute(actor: actor, input: invalidInput);
  } catch (e) {
    print('βœ… Validation error caught as expected: ${e.toString()}');
    print('πŸ’‘ Validation ensures data integrity\n');
  }

  print('πŸŽ‰ Example completed successfully!');
  print('\nKey emkore features demonstrated:');
  print('βœ… Clean Architecture layers (Entity, UseCase, Repository)');
  print('βœ… Unit of Work pattern with transaction support');
  print('βœ… Permission-based authorization');
  print('βœ… Comprehensive validation with error handling');
  print('βœ… Multitenancy with business ID isolation');
  print('βœ… Type-safe JSON handling');
  print('βœ… Complete CRUD operations');
  print('βœ… Money value objects for financial data');
  print('\nπŸ“š For complete test examples and advanced patterns,');
  print('   see example_e2e_test.dart and the repository implementations.');
}
0
likes
160
points
302
downloads

Publisher

verified publisheremko.dev

Weekly Downloads

Clean Architecture core library for Dart with use cases, entities, validation, authorization, and interceptor pipelines.

Homepage

Topics

#clean #architecture #core #emko #domain

Documentation

API reference

License

BSD-3-Clause (license)

Dependencies

meta, uuid

More

Packages that depend on emkore