adamlofts/mysql1_dart

Return wanted type from transaction

jonasborggren opened this issue · 0 comments

The ability to get the object you return from the queryBlock function would be nice. For my REST API I want to return a object using the id of a insert query. I want to use a transaction to make sure all the queries work correctly, however the transaction function lacks any return type, and it returns the error only if there is one.

Existing code:

Future transaction(Function queryBlock) async {
await query('start transaction');
try {
await queryBlock(TransactionContext._(this));
} catch (e) {
await query('rollback');
if (e is! _RollbackError) {
rethrow;
}
return e;
}
await query('commit');
}

Suggested code:

Future<T?> transaction<T>(
    Future<T> Function(TransactionContext) queryBlock, {
    Function(Object)? onError,
  }) async {
    await query('start transaction');
    try {
      // Run the query block
      final result = await queryBlock(TransactionContext._(this));
      // Neat, we made it here! Commit the changes!
      await query('commit');
      // Return the result of the query block
      return result;
    } catch (e) {
      // Run rollback!
      await query('rollback');
      if (e is! _RollbackError) {
        rethrow;
      }
      // Tell the client about the error
      onError?.call(e);
      return null;
    }
  }