dvStudioInProcessTransport function

DVStudioTransport dvStudioInProcessTransport(
  1. DVStudioApi api
)

A transport that answers from a core.DVStudioApi in this process: the Studio an application carries inside itself, on a phone, a desktop, a TV or the web, reading and writing its own database through the same API a server answers Studio with.

Implementation

DVStudioTransport dvStudioInProcessTransport(core.DVStudioApi api) {
  const String csrf = 'in-process-studio-request';
  return (String method, String path, {Object? body}) async {
    final Uri uri = Uri.parse('http://studio.invalid/$path');
    if (!uri.path.startsWith('/api/')) {
      return const DVStudioReply(404, <String, Object?>{
        'error': 'not_found',
        'message': 'This Studio runs inside the application, which has no '
            'build manifest beside it.',
      });
    }
    final core.Response response = await api.respond(
      core.Request(
        method: method,
        url: uri,
        headers: core.Headers(<String, String>{
          'x-dartvel-csrf-token': csrf,
          if (body != null) 'content-type': 'application/json',
        }),
        bodyStream: body == null
            ? const Stream<List<int>>.empty()
            : Stream<List<int>>.value(utf8.encode(jsonEncode(body))),
      ),
      uri.path.substring('/api/'.length),
    );
    final List<int> bytes = await response.body?.bytes() ?? const <int>[];
    Object? decoded;
    try {
      decoded = bytes.isEmpty ? null : jsonDecode(utf8.decode(bytes));
    } on FormatException {
      decoded = null;
    }
    return DVStudioReply(response.status, decoded);
  };
}