emkore 0.3.1 copy "emkore: ^0.3.1" to clipboard
emkore: ^0.3.1 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.');
}
1
likes
0
points
45
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

License

unknown (license)

Dependencies

meta, uuid

More

Packages that depend on emkore