onRequest method

  1. @override
void onRequest(
  1. RequestOptions options,
  2. RequestInterceptorHandler handler
)

Called when the request is about to be sent.

Implementation

@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
  if ((options.extra['offlineSync'] == true ||
          options.extra['idempotencyKey'] is String) &&
      options.extra['isSyncRequest'] != true &&
      const {
        'POST',
        'PUT',
        'PATCH',
        'DELETE',
      }.contains(options.method.toUpperCase())) {
    final supplied = options.extra['idempotencyKey'];
    final existing = options.headers.entries.where(
      (e) => e.key.toLowerCase() == 'idempotency-key',
    );
    final id = supplied is String
        ? supplied
        : existing.isNotEmpty
        ? existing.first.value.toString()
        : const Uuid().v4();
    if (!RegExp(r'^[A-Za-z0-9._:-]{1,200}$').hasMatch(id)) {
      handler.reject(
        DioException(
          requestOptions: options,
          error: ArgumentError('Invalid idempotency key'),
        ),
      );
      return;
    }
    options.extra['like.operationId'] ??= id;
    options.headers.removeWhere(
      (name, _) => name.toLowerCase() == 'idempotency-key',
    );
    options.headers['Idempotency-Key'] = id;
  }
  handler.next(options);
}