callFunction function

Future<Object?> callFunction(
  1. String name, [
  2. Object? data
])

Calls the callable named name.

data is encoded as CBOR and arrives at the function as JSON-shaped data; the result comes back decoded the same way.

Implementation

Future<Object?> callFunction(String name, [Object? data]) {
  final completer = Completer<Object?>();
  final receive = RawReceivePort();
  receive.handler = (Object? message) {
    receive.close();
    final bytes = message! as Uint8List;
    final seq = ByteData.sublistView(bytes).getInt64(8, Endian.host);
    if (seq < 0) {
      final reason = decodeSnapshotValue(bytes);
      completer.completeError(
        FunctionsException(
          seq.toInt(),
          seq == -2
              ? 'the result could not be encoded'
              : '${reason ?? "failed"}',
          name,
        ),
      );
      return;
    }
    completer.complete(decodeSnapshotValue(bytes));
  };

  final encoded = data == null
      ? Uint8List(0)
      : Uint8List.fromList(encodeVariant(data));
  final n = name.toNativeUtf8();
  final buf = calloc<Uint8>(encoded.isEmpty ? 1 : encoded.length);
  if (encoded.isNotEmpty) {
    buf.asTypedList(encoded.length).setAll(0, encoded);
  }
  final rc = fdbFunctionsCall(
    n.cast(),
    buf,
    encoded.length,
    receive.sendPort.nativePort,
  );
  calloc
    ..free(n)
    ..free(buf);
  if (rc != 0) {
    receive.close();
    return Future.error(
      rc == -3
          ? ArgumentError('these arguments cannot be encoded')
          : StateError('call $name failed to start ($rc)'),
    );
  }
  return completer.future;
}