handlePut method

Future<Response> handlePut(
  1. Request request
)

Handles Put http requisitions. Requires a http Request (from the Shelf package).

Implementation

Future<Response> handlePut(Request request) async {
  if (!middlewareJwt(request)) {
    return Response.forbidden(jsonEncode({'error': 'middlewareJwt'}));
  }
  try {
    final content = await request.readAsString(); /*2*/
    final data = jsonDecode(content) as Map;
    final key = request.url.pathSegments[0];
    final dynamic seg = await config.db.getAll(key);

    if (seg == null) {
      return Response.notFound(jsonEncode({'error': 'Not found'}));
    } else {
      data['id'] = request.url.pathSegments[1];
      final position = (seg as List).indexWhere(
        (element) => element['id'] == request.url.pathSegments[1],
      );
      data.forEach((key, value) {
        seg[position][key] = value;
      });
      await config.db.save(key, seg);
      return Response.ok(
        jsonEncode(data),
        headers: {'content-type': 'application/json'},
      );
    }
  } catch (e) {
    return Response.notFound(jsonEncode({'error': 'Internal Error. $e'}));
  }
}