onSuccess<R> method

FutureOr<R?> onSuccess<R>(
  1. DataResponse response,
  2. DataRequestLabel label
)
inherited

Implementation

FutureOr<R?> onSuccess<R>(
    DataResponse response, DataRequestLabel label) async {
  // remove all operations with this label
  OfflineOperation.remove(label, this as Adapter);

  final body = response.body;

  // this will happen when `returnBytes` is requested
  if (body is Uint8List) {
    return response as R;
  }

  if (label.kind == 'save') {
    if (label.model == null) {
      return null;
    }
    if (body == null) {
      // return original model if response was empty
      return label.model as R?;
    }

    final data = await deserialize(body as Map<String, dynamic>,
        key: label.model!._key);
    final model = data.model!;

    // if there has been a migration to a new key, delete the old one
    if (model._key != label.model!._key) {
      deleteLocalByKeys({label.model!._key!});
    }
    model.saveLocal();

    log(label, 'saved in local storage and remote');

    return model as R?;
  }

  if (label.kind == 'delete') {
    log(label, 'deleted in local storage and remote');
    return null;
  }

  final isFindAll = label.kind.startsWith('findAll');
  final isFindOne = label.kind.startsWith('findOne');
  final isCustom = label.kind == 'custom';

  final adapter = this as Adapter;

  // custom non-JSON request, return as-is
  if (isCustom &&
      !(response.headers['content-type']?.contains('json') ?? false)) {
    return response.body as R?;
  }

  final deserialized = await deserializeAndSave(body);
  deserialized._log(adapter, label);

  if (isFindAll || (isCustom && deserialized.model == null)) {
    late R? models;
    if (response.statusCode == 304) {
      models = adapter.findAllLocal() as R?;
    } else {
      models = deserialized.models as R?;
    }
    return models;
  }

  if (isFindOne || (isCustom && deserialized.model != null)) {
    late R? model;
    if (response.statusCode == 304) {
      model = adapter.findOneLocalById(label.id!) as R?;
    } else {
      model = deserialized.model as R?;
    }
    return model;
  }

  return null;
}