findOne method

Future<T?> findOne(
  1. Object id, {
  2. bool? remote,
  3. bool? background,
  4. Map<String, dynamic>? params,
  5. Map<String, String>? headers,
  6. OnSuccessOne<T>? onSuccess,
  7. OnErrorOne<T>? onError,
  8. DataRequestLabel? label,
})
inherited

Implementation

Future<T?> findOne(
  Object id, {
  bool? remote,
  bool? background,
  Map<String, dynamic>? params,
  Map<String, String>? headers,
  OnSuccessOne<T>? onSuccess,
  OnErrorOne<T>? onError,
  DataRequestLabel? label,
}) async {
  remote ??= _remote;
  background ??= false;
  params = await defaultParams & params;
  headers = await defaultHeaders & headers;

  final resolvedId = _resolveId(id);
  late T? model;

  label = DataRequestLabel('findOne',
      type: internalType, id: resolvedId?.toString(), withParent: label);

  if (!shouldLoadRemoteOne(id, remote!, params, headers) || background) {
    final key = graph.getKeyForId(internalType, resolvedId,
        keyIfAbsent: id is T ? id._key : null);
    model = localAdapter.findOne(key);
    if (model != null) {
      log(label,
          'returned from local storage${background ? ' and loading in the background' : ''}');
    }
    if (!background) {
      return model;
    }
  }

  final future = sendRequest(
    baseUrl.asUri / urlForFindOne(id, params) & params,
    method: methodForFindOne(id, params),
    headers: headers,
    label: label,
    onSuccess: (data, label) {
      onSuccess ??= (data, label, _) => this.onSuccess<T>(data, label);
      return onSuccess!.call(data, label, this as RemoteAdapter<T>);
    },
    onError: (e, label) async {
      onError ??= (e, label, _) => this.onError<T>(e, label);
      return onError!.call(e, label, this as RemoteAdapter<T>);
    },
  );

  if (background) {
    // ignore: unawaited_futures
    future.then((_) => Future.value(_));
    return model;
  } else {
    return await future;
  }
}