base64EncodeHook function

HiHook base64EncodeHook({
  1. String uid = 'base64:encode',
  2. List<String> events = const ['write', 'put'],
  3. HiPhase phase = HiPhase.pre,
  4. int priority = 0,
  5. bool urlSafe = false,
})

Creates a Base64 encode hook for write operations.

Encodes payload value to Base64 string before storage. Supports String and Uint8List input values.

Parameters

  • uid: Unique hook identifier, defaults to 'base64:encode'
  • events: Events to listen for, defaults to 'write', 'put'
  • phase: Hook phase, defaults to HiPhase.pre (encode before write)
  • urlSafe: Use URL-safe Base64 encoding

Payload Transformation

  • String → Base64 string (UTF-8 encoded first)
  • Uint8List → Base64 string
  • Other types → passed through unchanged

Example

engine.register(base64EncodeHook());

// Input: HiPayload(key: 'data', value: 'hello')
// Output: HiPayload(key: 'data', value: 'aGVsbG8=')

Implementation

HiHook<dynamic, dynamic> base64EncodeHook({
  String uid = 'base64:encode',
  List<String> events = const ['write', 'put'],
  HiPhase phase = HiPhase.pre,
  int priority = 0,
  bool urlSafe = false,
}) {
  return HiHook<dynamic, dynamic>(
    uid: uid,
    events: events,
    phase: phase,
    priority: priority,
    handler: (payload, ctx) {
      final value = payload.value;
      String? encoded;

      if (value is String) {
        final bytes = utf8.encode(value);
        encoded = urlSafe ? base64Url.encode(bytes) : base64.encode(bytes);
      } else if (value is Uint8List) {
        encoded = urlSafe ? base64Url.encode(value) : base64.encode(value);
      } else if (value is List<int>) {
        encoded = urlSafe
            ? base64Url.encode(Uint8List.fromList(value))
            : base64.encode(Uint8List.fromList(value));
      }

      if (encoded != null) {
        return HiContinue(
          payload: HiPayload(
            key: payload.key,
            value: encoded,
            metadata: payload.metadata,
          ),
        );
      }

      // Pass through unchanged for unsupported types
      return const HiContinue();
    },
  );
}