nyApi<T> function

Future nyApi<T>({
  1. required dynamic request(
    1. T
    ),
  2. Map<Type, dynamic> apiDecoders = const {},
  3. BuildContext? context,
  4. Map<String, dynamic> headers = const {},
  5. String? bearerToken,
  6. String? baseUrl,
  7. int? page,
  8. int? perPage,
  9. String queryParamPage = "page",
  10. String? queryParamPerPage,
  11. int? retry = 0,
  12. Duration? retryDelay,
  13. bool retryIf(
    1. DioException dioException
    )?,
  14. bool? shouldSetAuthHeaders,
  15. List<Type> events = const [],
})

API helper

Implementation

Future<dynamic> nyApi<T>(
    {required dynamic Function(T) request,
    Map<Type, dynamic> apiDecoders = const {},
    BuildContext? context,
    Map<String, dynamic> headers = const {},
    String? bearerToken,
    String? baseUrl,
    int? page,
    int? perPage,
    String queryParamPage = "page",
    String? queryParamPerPage,
    int? retry = 0,
    Duration? retryDelay,
    bool Function(DioException dioException)? retryIf,
    bool? shouldSetAuthHeaders,
    List<Type> events = const []}) async {
  assert(apiDecoders.containsKey(T),
      'Your config/decoders.dart is missing this class ${T.toString()} in apiDecoders.');

  dynamic apiService = apiDecoders[T];

  if (context != null) {
    apiService.setContext(context);
  }

  // add headers
  if (headers.isNotEmpty) {
    apiService.setHeaders(headers);
  }

  // add bearer token
  if (bearerToken != null) {
    apiService.setBearerToken(bearerToken);
  }

  // add baseUrl
  if (baseUrl != null) {
    apiService.setBaseUrl(baseUrl);
  }

  // add retryIf
  if (retryIf != null) {
    apiService.setRetryIf(retryIf);
  }

  /// [queryParamPage] by default is 'page'
  /// [queryParamPerPage] by default is 'per_page'
  if (page != null) {
    apiService.setPagination(page,
        paramPage: queryParamPage,
        paramPerPage: queryParamPerPage,
        perPage: perPage);
  }

  if (retry != null) {
    apiService.setRetry(retry);
  }

  if (retryDelay != null) {
    apiService.setRetryDelay(retryDelay);
  }

  if (shouldSetAuthHeaders != null) {
    apiService.setShouldSetAuthHeaders(shouldSetAuthHeaders);
  }

  dynamic result = await request(apiService);
  if (events.isNotEmpty) {
    Nylo nylo = Backpack.instance.nylo();

    for (var event in events) {
      NyEvent? nyEvent = nylo.getEvent(event);
      if (nyEvent == null) {
        continue;
      }
      Map<dynamic, NyListener> listeners = nyEvent.listeners;

      if (listeners.isEmpty) {
        return;
      }
      for (NyListener listener in listeners.values.toList()) {
        listener.setEvent(nyEvent);

        dynamic eventResult = await listener.handle({'data': result});
        if (eventResult != null && eventResult == false) {
          break;
        }
      }
    }
  }
  return result;
}