Interceptor Example

Database & APIs
Resolved

Hello,

Interceptors are a new feature in FF, and there is almost no documentation available for them.

I successfully built this interceptor, which I use to remove an attribute from a JSON payload.

While the end result seems simple, it required many trials and errors to make it work effectively. I would say that the secret lies in properly configuring the newOptions object with the necessary attributes.

Below is the code I've used. I hope it will be helpful to others.

What have you tried so far?
// Automatic FlutterFlow imports
import '/backend/schema/structs/index.dart';
import '/backend/schema/enums/enums.dart';
import '/backend/supabase/supabase.dart';
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'dart:convert';
import '/backend/api_requests/api_interceptor.dart';

class removeAttributeInterceptor extends FFApiInterceptor {
  @override
  Future<ApiCallOptions> onRequest({
    required ApiCallOptions options,
  }) async {
    // Parse the body JSON string into a Dart map and remove 'NameOfAttributeToRemove'
    Map<String, dynamic> bodyObject = jsonDecode(options.body ?? '');
    bodyObject.removeWhere((key, value) => key == 'NameOfAttributeToRemove');
    String bodyString = jsonEncode(bodyObject);
    // useful for debuging
    // print('options: ' + options.toString() );

    // recreate the options object with the modified body
    final ApiCallOptions newOptions = ApiCallOptions(
      callName: options.callName, // likely optional at this point
      callType: options.callType,
      bodyType: options.bodyType, // important for JSON body
      apiUrl: options.apiUrl,
      params: options.params,
      headers: options.headers,
      returnBody: options.returnBody, // usually set to true
      body: bodyString, // modified body
    );

    // Return the modified options
    return newOptions;
  }

  @override
  Future<ApiCallResponse> onResponse({
    required ApiCallResponse response,
    required Future<ApiCallResponse> Function() retryFn,
  }) async {
    // Perform any necessary calls or modifications to the [response] prior to returning it

    // Return the original response
    return response;
  }
}

Did you check FlutterFlow's Documentation for this topic?
Yes
3
3 replies