triggerAndReturn<T extends DbResult> method

FutureOr<T> triggerAndReturn<T extends DbResult>(
  1. AccessEvent event,
  2. FutureOr<T> interoperation()
)

Trigger

Implementation

FutureOr<T> triggerAndReturn<T extends DbResult>(
    AccessEvent event, FutureOr<T> Function() interoperation) async {
  var type = _getTriggerType(event.type);
  if (type == TriggerType.non) return interoperation();

  var _trs = <Trigger>[
    ...?_triggers[event.access.collection]?[type],
    ...?_triggers[event.access.collection]?[TriggerType.onWrite]
  ];

  if (_trs.isEmpty) return interoperation();

  var _befNeed = _trs.where((element) => element._beforeNeed).isNotEmpty;
  var _afterNeed = _trs.where((element) => element._afterNeed).isNotEmpty;

  switch (type) {
    case TriggerType.onCreate:
      var _inter = await interoperation();
      if (_inter.success) {
        for (var tr in _trs) {
          tr.onEvent(event);
        }
      }
      return _inter;
    case TriggerType.onUpdate:
      if (_befNeed) {
        event.before ??= (await dataAccess._read(event.access)).data;
      }

      ///
      var _inter = (await interoperation()) as UpdateDbResult;
      if (_inter.success) {
        if (_afterNeed && _inter.newData == null) {
          event.after ??= (await dataAccess._read(event.access)).data;
        }
        for (var tr in _trs) {
          tr.onEvent(event);
        }
      } else {
        return _inter as T;
      }

      return _inter as T;
    case TriggerType.onDelete:
      if (_befNeed) {
        event.before ??= (await dataAccess._read(event.access)).data;
      }
      var _inter = await interoperation();
      if (_inter.success) {
        for (var tr in _trs) {
          tr.onEvent(event);
        }
      }
      return _inter;
    case TriggerType.onWrite:
      throw UnsupportedError(
          "Operation base trigger type can not be onWrite");
    case TriggerType.non:
      throw UnimplementedError();
  }
}