handleRequest method

dynamic handleRequest(
  1. HttpRequest request
)

Implementation

handleRequest(HttpRequest request) async {
  //await Future.delayed(Duration(milliseconds: 25));
  String authorization =
      request.headers.value('authorization') /* .toLowerCase() */;

  print('');

  String clientId = null;
  //if (clientId != null) print('Client $clientId');

  if (!instances.containsKey(clientId)) {
    // TODO Add async init

    instances[clientId] = rootSockyBuilder();
  }

  final server = instances[clientId];

  var function = request.uri.toString();

  print('${function}');

  if (function.startsWith('/_')) {
    var content = await utf8.decoder.bind(request).join();

    var data = json.decode(content);

    print('> $data');
    if (function == '/_login') {
      var user = SockyUser(id: Uuid().v4(), name: data['username']);
      users[user.id] = user;

      var token = Uuid().v4();
      userTokens[token] = user.id;

      print('< $token');
      request.response.write(json.encode({'token': token, 'user': user}));
    }
  } else {
    CallContext context = CallContext();

    if (authorization != null) {
      String bearerToken = authorization.split(' ').last;

      if (userTokens.containsKey(bearerToken)) {
        context.user = users[userTokens[bearerToken]];
      } else {
        request.response.statusCode = HttpStatus.forbidden;
        await request.response.close();
        return;
      }
    }
    // TODO Check if Endpoint requires authorization

    List<String> fParts =
        function.split('/').where((s) => s.isNotEmpty).toList();

    dynamic socket = server;

    for (String part in fParts.sublist(0, fParts.length - 1)) {
      if (socket is Map) {
        socket = socket[part];
      } else {
        socket = socket.sub['/' + part];
      }
    }

    if (socket is Map) return; // TODO Exception

    Function func = socket.map[fParts.last];

    if (func == null) {
      request.response.statusCode = 404;
      await request.response.close();
      return;
    }

    var content = await utf8.decoder.bind(request).join();

    // TODO Check if this always works, and how!
    // var content = await request.single;

// TODO Add JSON Option
    //var data = msgpack.deserialize(content);

    var data = json.decode(content);

    print('> $data');

    var result;
    try {
      result = await func(data, context);

      print('< $result');
      request.response.write(json.encode(result));
    } catch (e, st) {
      print(e);
      print(st);
      // TODO Custom Exception
      request.response.statusCode = 500; // TODO Use other status code
      request.response.write((e.toString()));
    }
  }

  await request.response.close();
}